# Table of Contents - [gm — web3.py 7.6.1 documentation](#gm-web3-py-7-6-1-documentation) - [Overview — web3.py 7.6.1 documentation](#overview-web3-py-7-6-1-documentation) - [Quickstart — web3.py 7.6.1 documentation](#quickstart-web3-py-7-6-1-documentation) - [Providers — web3.py 7.6.1 documentation](#providers-web3-py-7-6-1-documentation) - [Transactions — web3.py 7.6.1 documentation](#transactions-web3-py-7-6-1-documentation) - [Middleware — web3.py 7.6.1 documentation](#middleware-web3-py-7-6-1-documentation) - [Troubleshooting — web3.py 7.6.1 documentation](#troubleshooting-web3-py-7-6-1-documentation) - [Web3 Internals — web3.py 7.6.1 documentation](#web3-internals-web3-py-7-6-1-documentation) - [Web3 API — web3.py 7.6.1 documentation](#web3-api-web3-py-7-6-1-documentation) - [Release Notes — web3.py 7.6.1 documentation](#release-notes-web3-py-7-6-1-documentation) - [Accounts — web3.py 7.6.1 documentation](#accounts-web3-py-7-6-1-documentation) - [Contracts — web3.py 7.6.1 documentation](#contracts-web3-py-7-6-1-documentation) - [Ethereum Name Service (ENS) — web3.py 7.6.1 documentation](#ethereum-name-service-ens-web3-py-7-6-1-documentation) - [Migration Guide — web3.py 7.6.1 documentation](#migration-guide-web3-py-7-6-1-documentation) - [Events and Logs — web3.py 7.6.1 documentation](#events-and-logs-web3-py-7-6-1-documentation) - [Net API — web3.py 7.6.1 documentation](#net-api-web3-py-7-6-1-documentation) - [Tracing API — web3.py 7.6.1 documentation](#tracing-api-web3-py-7-6-1-documentation) - [Gas Price API — web3.py 7.6.1 documentation](#gas-price-api-web3-py-7-6-1-documentation) - [Code of Conduct — web3.py 7.6.1 documentation](#code-of-conduct-web3-py-7-6-1-documentation) - [Utils — web3.py 7.6.1 documentation](#utils-web3-py-7-6-1-documentation) - [Constants — web3.py 7.6.1 documentation](#constants-web3-py-7-6-1-documentation) - [gm — web3.py 7.6.1 documentation](#gm-web3-py-7-6-1-documentation) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Beacon API — web3.py 7.6.1 documentation](#beacon-api-web3-py-7-6-1-documentation) - [Geth API — web3.py 7.6.1 documentation](#geth-api-web3-py-7-6-1-documentation) - [Unknown](#unknown) - [Resources and Learning Material — web3.py 7.6.1 documentation](#resources-and-learning-material-web3-py-7-6-1-documentation) - [Unknown](#unknown) - [Unknown](#unknown) - [Index — web3.py 7.6.1 documentation](#index-web3-py-7-6-1-documentation) - [Unknown](#unknown) - [ENS API — web3.py 7.6.1 documentation](#ens-api-web3-py-7-6-1-documentation) - [web3.eth API — web3.py 7.6.1 documentation](#web3-eth-api-web3-py-7-6-1-documentation) - [Contributing — web3.py 7.6.1 documentation](#contributing-web3-py-7-6-1-documentation) - [Search — web3.py 7.6.1 documentation](#search-web3-py-7-6-1-documentation) - [Python Module Index — web3.py 7.6.1 documentation](#python-module-index-web3-py-7-6-1-documentation) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) --- # gm — web3.py 7.6.1 documentation * [](#) * gm * [View page source](_sources/index.rst.txt) * * * gm[](#gm "Link to this heading") ================================== ![Banner Image](_images/banner-snek.jpg) **web3.py** is a Python library for interacting with Ethereum. It’s commonly found in [decentralized apps (dapps)](https://ethereum.org/dapps/) to help with sending transactions, interacting with smart contracts, reading block data, and a variety of other use cases. For project updates, follow [@EthereumPython](https://twitter.com/EthereumPython) and sign up for new post notifications on the [blog](https://snakecharmers.ethereum.org/) . Getting Started[](#getting-started "Link to this heading") ------------------------------------------------------------ Note 👋 Brand new to Ethereum? 0. Don’t travel alone! Join the Ethereum Python Community [Discord](https://discord.gg/GHryRvPB84) . 1. Read this [blog post series](https://snakecharmers.ethereum.org/a-developers-guide-to-ethereum-pt-1) for a gentle introduction to Ethereum blockchain concepts. 2. The [Overview](overview.html#overview) page will give you a quick idea of what else web3.py can do. 3. Try building a little something! * Ready to code? → [Quickstart](quickstart.html#quickstart) * Quick tour? → [Overview](overview.html#overview) * Synchronous help? → [Discord](https://discord.gg/GHryRvPB84) * Asynchronous help? → [StackExchange](https://ethereum.stackexchange.com/questions/tagged/web3.py) * Report a bug? → [Github](https://github.com/ethereum/web3.py/issues) * Want to help us? → [Contribute](contributing.html#contributing) * Looking for inspiration? → [Resources and Learning Material](resources.html#resources) Table of Contents[](#table-of-contents "Link to this heading") ---------------------------------------------------------------- Intro * [Quickstart](quickstart.html) * [Overview](overview.html) * [Release Notes](release_notes.html) Guides * [Providers](providers.html) * [Accounts](web3.eth.account.html) * [Transactions](transactions.html) * [Contracts](web3.contract.html) * [Events and Logs](filters.html) * [Middleware](middleware.html) * [Web3 Internals](internals.html) * [Ethereum Name Service (ENS)](ens_overview.html) * [Troubleshooting](troubleshooting.html) * [Migration Guide](migration.html) API * [Web3 API](web3.main.html) * [web3.eth API](web3.eth.html) * [Beacon API](web3.beacon.html) * [Net API](web3.net.html) * [Geth API](web3.geth.html) * [Tracing API](web3.tracing.html) * [Utils](web3.utils.html) * [Gas Price API](gas_price.html) * [ENS API](ens.html) * [Constants](constants.html) Community * [Resources and Learning Material](resources.html) * [Contributing](contributing.html) * [Code of Conduct](code_of_conduct.html) Indices and tables[](#indices-and-tables "Link to this heading") ------------------------------------------------------------------ * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html) --- # Overview — web3.py 7.6.1 documentation * [](index.html) * Overview * [View page source](_sources/overview.rst.txt) * * * Overview[](#overview "Link to this heading") ============================================== The purpose of this page is to give you a sense of everything web3.py can do and to serve as a quick reference guide. You’ll find a summary of each feature with links to learn more. Configuration[](#configuration "Link to this heading") -------------------------------------------------------- After installing web3.py (via `pip install web3`), you’ll need to configure a provider endpoint and any middleware you want to use beyond the defaults. ### Providers[](#providers "Link to this heading") [Providers](providers.html) are how web3.py connects to a blockchain. The library comes with the following built-in providers: * [`HTTPProvider`](providers.html#web3.providers.rpc.HTTPProvider "web3.providers.rpc.HTTPProvider") for connecting to http and https based JSON-RPC servers. * [`IPCProvider`](providers.html#web3.providers.ipc.IPCProvider "web3.providers.ipc.IPCProvider") for connecting to ipc socket based JSON-RPC servers. * [`LegacyWebSocketProvider`](providers.html#web3.providers.legacy_websocket.LegacyWebSocketProvider "web3.providers.legacy_websocket.LegacyWebSocketProvider") (deprecated) for connecting to websocket based JSON-RPC servers. * `AsyncHTTPProvider` for connecting to http and https based JSON-RPC servers asynchronously. * [`AsyncIPCProvider`](providers.html#web3.providers.persistent.AsyncIPCProvider "web3.providers.persistent.AsyncIPCProvider") for connecting to ipc socket based JSON-RPC servers asynchronously via a persistent connection. * [`WebSocketProvider`](providers.html#web3.providers.persistent.WebSocketProvider "web3.providers.persistent.WebSocketProvider") for connecting to websocket based JSON-RPC servers asynchronously via a persistent connection. #### Examples[](#examples "Link to this heading") \>>> 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 For more context, see the [Providers](providers.html) documentation. ### Middleware[](#middleware "Link to this heading") Your web3.py instance may be further configured via [Middleware](middleware.html) . web3.py middleware is described using an onion metaphor, where each layer of middleware may affect both the incoming request and outgoing response from your provider. The documentation includes a [visualization](middleware.html#modifying-middleware) of this idea. Several middleware are [included by default](middleware.html#default-middleware) . You may add to ([`add`](middleware.html#Web3.middleware_onion.add "Web3.middleware_onion.add") , [`inject`](middleware.html#Web3.middleware_onion.inject "Web3.middleware_onion.inject") , [`replace`](middleware.html#Web3.middleware_onion.replace "Web3.middleware_onion.replace") ) or disable ([`remove`](middleware.html#Web3.middleware_onion.remove "Web3.middleware_onion.remove") , [`clear`](middleware.html#Web3.middleware_onion.clear "Web3.middleware_onion.clear") ) any of these middleware. Accounts and Private Keys[](#accounts-and-private-keys "Link to this heading") -------------------------------------------------------------------------------- Private keys are required to approve any transaction made on your behalf. The manner in which your key is secured will determine how you create and send transactions in web3.py. A local node, like [Geth](https://geth.ethereum.org/) , may manage your keys for you. You can reference those keys using the [`web3.eth.accounts`](web3.eth.html#web3.eth.Eth.accounts "web3.eth.Eth.accounts") property. A hosted node, like [Infura](https://infura.io/) , will have no knowledge of your keys. In this case, you’ll need to have your private key available locally for signing transactions. Full documentation on the distinction between keys can be found [here](web3.eth.account.html#eth-account) . The separate guide to [Transactions](transactions.html) may also help clarify how to manage keys. Base API[](#base-api "Link to this heading") ---------------------------------------------- The [Web3](web3.main.html#web3-base) class includes a number of convenient utility functions: ### Encoding and Decoding Helpers[](#encoding-and-decoding-helpers "Link to this heading") * [`Web3.is_encodable()`](web3.main.html#web3.w3.is_encodable "web3.w3.is_encodable") * [`Web3.to_bytes()`](web3.main.html#web3.Web3.to_bytes "web3.Web3.to_bytes") * [`Web3.to_hex()`](web3.main.html#web3.Web3.to_hex "web3.Web3.to_hex") * [`Web3.to_int()`](web3.main.html#web3.Web3.to_int "web3.Web3.to_int") * [`Web3.to_json()`](web3.main.html#web3.Web3.to_json "web3.Web3.to_json") * [`Web3.to_text()`](web3.main.html#web3.Web3.to_text "web3.Web3.to_text") ### Address Helpers[](#address-helpers "Link to this heading") * [`Web3.is_address()`](web3.main.html#web3.Web3.is_address "web3.Web3.is_address") * [`Web3.is_checksum_address()`](web3.main.html#web3.Web3.is_checksum_address "web3.Web3.is_checksum_address") * [`Web3.to_checksum_address()`](web3.main.html#web3.Web3.to_checksum_address "web3.Web3.to_checksum_address") ### Currency Conversions[](#currency-conversions "Link to this heading") * [`Web3.from_wei()`](web3.main.html#web3.Web3.from_wei "web3.Web3.from_wei") * [`Web3.to_wei()`](web3.main.html#web3.Web3.to_wei "web3.Web3.to_wei") ### Cryptographic Hashing[](#cryptographic-hashing "Link to this heading") * [`Web3.keccak()`](web3.main.html#web3.Web3.keccak "web3.Web3.keccak") * [`Web3.solidity_keccak()`](web3.main.html#web3.Web3.solidity_keccak "web3.Web3.solidity_keccak") web3.eth API[](#web3-eth-api "Link to this heading") ------------------------------------------------------ The most commonly used APIs for interacting with Ethereum can be found under the [web3.eth API](web3.eth.html#web3-eth) namespace. ### Fetching Data[](#fetching-data "Link to this heading") Viewing account balances ([`get_balance`](web3.eth.html#web3.eth.Eth.get_balance "web3.eth.Eth.get_balance") ), transactions ([`get_transaction`](web3.eth.html#web3.eth.Eth.get_transaction "web3.eth.Eth.get_transaction") ), and block data ([`get_block`](web3.eth.html#web3.eth.Eth.get_block "web3.eth.Eth.get_block") ) are some of the most common starting points in web3.py. #### API[](#api "Link to this heading") * [`web3.eth.get_balance()`](web3.eth.html#web3.eth.Eth.get_balance "web3.eth.Eth.get_balance") * [`web3.eth.get_block()`](web3.eth.html#web3.eth.Eth.get_block "web3.eth.Eth.get_block") * [`web3.eth.get_block_transaction_count()`](web3.eth.html#web3.eth.Eth.get_block_transaction_count "web3.eth.Eth.get_block_transaction_count") * [`web3.eth.get_code()`](web3.eth.html#web3.eth.Eth.get_code "web3.eth.Eth.get_code") * [`web3.eth.get_proof()`](web3.eth.html#web3.eth.Eth.get_proof "web3.eth.Eth.get_proof") * [`web3.eth.get_storage_at()`](web3.eth.html#web3.eth.Eth.get_storage_at "web3.eth.Eth.get_storage_at") * [`web3.eth.get_transaction()`](web3.eth.html#web3.eth.Eth.get_transaction "web3.eth.Eth.get_transaction") * [`web3.eth.get_transaction_by_block()`](web3.eth.html#web3.eth.Eth.get_transaction_by_block "web3.eth.Eth.get_transaction_by_block") * [`web3.eth.get_transaction_count()`](web3.eth.html#web3.eth.Eth.get_transaction_count "web3.eth.Eth.get_transaction_count") * [`web3.eth.get_uncle_by_block()`](web3.eth.html#web3.eth.Eth.get_uncle_by_block "web3.eth.Eth.get_uncle_by_block") * [`web3.eth.get_uncle_count()`](web3.eth.html#web3.eth.Eth.get_uncle_count "web3.eth.Eth.get_uncle_count") ### Sending Transactions[](#sending-transactions "Link to this heading") The most common use cases will be satisfied with [`send_transaction`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") or the combination of [`sign_transaction`](web3.eth.html#web3.eth.Eth.sign_transaction "web3.eth.Eth.sign_transaction") and [`send_raw_transaction`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction") . For more context, see the full guide to [Transactions](transactions.html) . Note If interacting with a smart contract, a dedicated API exists. See the next section, [Contracts](#overview-contracts) . #### API[](#id2 "Link to this heading") * [`web3.eth.send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") * [`web3.eth.sign_transaction()`](web3.eth.html#web3.eth.Eth.sign_transaction "web3.eth.Eth.sign_transaction") * [`web3.eth.send_raw_transaction()`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction") * [`web3.eth.replace_transaction()`](web3.eth.html#web3.eth.Eth.replace_transaction "web3.eth.Eth.replace_transaction") * [`web3.eth.modify_transaction()`](web3.eth.html#web3.eth.Eth.modify_transaction "web3.eth.Eth.modify_transaction") * [`web3.eth.wait_for_transaction_receipt()`](web3.eth.html#web3.eth.Eth.wait_for_transaction_receipt "web3.eth.Eth.wait_for_transaction_receipt") * [`web3.eth.get_transaction_receipt()`](web3.eth.html#web3.eth.Eth.get_transaction_receipt "web3.eth.Eth.get_transaction_receipt") * [`web3.eth.sign()`](web3.eth.html#web3.eth.Eth.sign "web3.eth.Eth.sign") * [`web3.eth.sign_typed_data()`](web3.eth.html#web3.eth.Eth.sign_typed_data "web3.eth.Eth.sign_typed_data") * [`web3.eth.estimate_gas()`](web3.eth.html#web3.eth.Eth.estimate_gas "web3.eth.Eth.estimate_gas") * [`web3.eth.generate_gas_price()`](web3.eth.html#web3.eth.Eth.generate_gas_price "web3.eth.Eth.generate_gas_price") * [`web3.eth.set_gas_price_strategy()`](web3.eth.html#web3.eth.Eth.set_gas_price_strategy "web3.eth.Eth.set_gas_price_strategy") Contracts[](#contracts "Link to this heading") ------------------------------------------------ web3.py can help you deploy, read from, or execute functions on a deployed contract. Deployment requires that the contract already be compiled, with its bytecode and ABI available. This compilation step can be done within [Remix](http://remix.ethereum.org/) or one of the many contract development frameworks, such as [Ape](https://docs.apeworx.io/ape/stable/index.html) . Once the contract object is instantiated, calling `transact` on the [`constructor`](web3.contract.html#web3.contract.Contract.constructor "web3.contract.Contract.constructor") method will deploy an instance of the contract: \>>> ExampleContract \= w3.eth.contract(abi\=abi, bytecode\=bytecode) \>>> tx\_hash \= ExampleContract.constructor().transact() \>>> tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash) \>>> tx\_receipt.contractAddress '0x8a22225eD7eD460D7ee3842bce2402B9deaD23D3' Once a deployed contract is loaded into a Contract object, the functions of that contract are available on the `functions` namespace: \>>> deployed\_contract \= w3.eth.contract(address\=tx\_receipt.contractAddress, abi\=abi) \>>> deployed\_contract.functions.myFunction(42).transact() If you want to read data from a contract (or see the result of transaction locally, without executing it on the network), you can use the [`ContractFunction.call`](web3.contract.html#web3.contract.ContractFunction.call "web3.contract.ContractFunction.call") method, or the more concise [`ContractCaller`](web3.contract.html#web3.contract.ContractCaller "web3.contract.ContractCaller") syntax: \# Using ContractFunction.call \>>> deployed\_contract.functions.getMyValue().call() 42 \# Using ContractCaller \>>> deployed\_contract.caller().getMyValue() 42 For more, see the full [Contracts](web3.contract.html#contracts) documentation. ### API[](#id3 "Link to this heading") * [`web3.eth.contract()`](web3.eth.html#web3.eth.Eth.contract "web3.eth.Eth.contract") * [`Contract.address`](web3.contract.html#web3.contract.Contract.address "web3.contract.Contract.address") * [`Contract.abi`](web3.contract.html#web3.contract.Contract.abi "web3.contract.Contract.abi") * [`Contract.bytecode`](web3.contract.html#web3.contract.Contract.bytecode "web3.contract.Contract.bytecode") * [`Contract.bytecode_runtime`](web3.contract.html#web3.contract.Contract.bytecode_runtime "web3.contract.Contract.bytecode_runtime") * [`Contract.functions`](web3.contract.html#web3.contract.Contract.functions "web3.contract.Contract.functions") * [`Contract.events`](web3.contract.html#web3.contract.Contract.events "web3.contract.Contract.events") * [`Contract.fallback`](web3.contract.html#web3.contract.Contract.fallback.call "web3.contract.Contract.fallback.call") * [`Contract.constructor()`](web3.contract.html#web3.contract.Contract.constructor "web3.contract.Contract.constructor") * [`Contract.encode_abi()`](web3.contract.html#web3.contract.Contract.encode_abi "web3.contract.Contract.encode_abi") * [`web3.contract.ContractFunction`](web3.contract.html#web3.contract.ContractFunction "web3.contract.ContractFunction") * `web3.contract.ContractEvents` Events, Logs, and Filters[](#events-logs-and-filters "Link to this heading") ------------------------------------------------------------------------------ If you want to react to new blocks being mined or specific events being emitted by a contract, you can leverage `get_logs`, subscriptions, or filters. See the [Events and Logs](filters.html) guide for more information. ### API[](#id4 "Link to this heading") * [`web3.eth.subscribe()`](web3.eth.html#web3.eth.Eth.subscribe "web3.eth.Eth.subscribe") * [`web3.eth.filter()`](web3.eth.html#web3.eth.Eth.filter "web3.eth.Eth.filter") * [`web3.eth.get_filter_changes()`](web3.eth.html#web3.eth.Eth.get_filter_changes "web3.eth.Eth.get_filter_changes") * [`web3.eth.get_filter_logs()`](web3.eth.html#web3.eth.Eth.get_filter_logs "web3.eth.Eth.get_filter_logs") * [`web3.eth.uninstall_filter()`](web3.eth.html#web3.eth.Eth.uninstall_filter "web3.eth.Eth.uninstall_filter") * [`web3.eth.get_logs()`](web3.eth.html#web3.eth.Eth.get_logs "web3.eth.Eth.get_logs") * [`Contract.events.your_event_name.create_filter()`](web3.contract.html#web3.contract.Contract.events.your_event_name.create_filter "web3.contract.Contract.events.your_event_name.create_filter") * [`Contract.events.your_event_name.build_filter()`](web3.contract.html#web3.contract.Contract.events.your_event_name.build_filter "web3.contract.Contract.events.your_event_name.build_filter") * [`Filter.get_new_entries()`](filters.html#web3.utils.filters.Filter.get_new_entries "web3.utils.filters.Filter.get_new_entries") * [`Filter.get_all_entries()`](filters.html#web3.utils.filters.Filter.get_all_entries "web3.utils.filters.Filter.get_all_entries") * [`Filter.format_entry()`](filters.html#web3.utils.filters.Filter.format_entry "web3.utils.filters.Filter.format_entry") * [`Filter.is_valid_entry()`](filters.html#web3.utils.filters.Filter.is_valid_entry "web3.utils.filters.Filter.is_valid_entry") Net API[](#net-api "Link to this heading") -------------------------------------------- Some basic network properties are available on the `web3.net` object: * [`web3.net.listening`](web3.net.html#web3.net.listening "web3.net.listening") * [`web3.net.peer_count`](web3.net.html#web3.net.peer_count "web3.net.peer_count") * [`web3.net.version`](web3.net.html#web3.net.version "web3.net.version") ENS[](#ens "Link to this heading") ------------------------------------ [Ethereum Name Service (ENS)](https://ens.domains/) provides the infrastructure for human-readable addresses. If an address is registered with the ENS registry, the domain name can be used in place of the address itself. For example, the registered domain name `ethereum.eth` will resolve to the address `0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe`. web3.py has support for ENS, documented [here](ens_overview.html#ens-overview) . --- # Quickstart — web3.py 7.6.1 documentation * [](index.html) * Quickstart * [View page source](_sources/quickstart.rst.txt) * * * Quickstart[](#quickstart "Link to this heading") ================================================== Note All code starting with a `$` is meant to run on your terminal. All code starting with a `>>>` is meant to run in a python interpreter, like [ipython](https://pypi.org/project/ipython/) . [Installation](#id2) [](#installation "Link to this heading") --------------------------------------------------------------- web3.py can be installed (preferably in a [virtualenv](troubleshooting.html#setup-environment) ) using `pip` as follows: $ pip install web3 Note If you run into problems during installation, you might have a broken environment. See the troubleshooting guide to [setting up a clean environment](troubleshooting.html#setup-environment) . [Using Web3](#id3) [](#using-web3 "Link to this heading") ----------------------------------------------------------- This library depends on a connection to an Ethereum node. We call these connections _Providers_ and there are several ways to configure them. The full details can be found in the [Providers](providers.html#providers) documentation. This Quickstart guide will highlight a couple of the most common use cases. ### [Test Provider](#id4) [](#test-provider "Link to this heading") If you’re just learning the ropes or doing some quick prototyping, you can use a test provider, [eth-tester](https://github.com/ethereum/eth-tester) . This provider includes some accounts prepopulated with test ether and instantly includes each transaction into a block. web3.py makes this test provider available via `EthereumTesterProvider`. Note The `EthereumTesterProvider` requires additional dependencies. Install them via `pip install "web3[tester]"`, then import and instantiate the provider as seen below. \>>> from web3 import Web3, EthereumTesterProvider \>>> w3 \= Web3(EthereumTesterProvider()) \>>> w3.is\_connected() True ### [Local Providers](#id5) [](#local-providers "Link to this heading") The hardware requirements are [steep](https://ethereum.org/en/developers/docs/nodes-and-clients/run-a-node/#top) , but the safest way to interact with Ethereum is to run an Ethereum client on your own hardware. For locally run nodes, an IPC connection is the most secure option, but HTTP and websocket configurations are also available. By default, the popular [Geth client](https://geth.ethereum.org/) exposes port `8545` to serve HTTP requests and `8546` for websocket requests. Connecting to this local node can be done as follows: \>>> 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 ### [Remote Providers](#id6) [](#remote-providers "Link to this heading") The quickest way to interact with the Ethereum blockchain is to use a [remote node provider](https://ethereum.org/en/developers/docs/nodes-and-clients/nodes-as-a-service/#popular-node-services) . You can connect to a remote node by specifying the endpoint, just like the previous local node example: \>>> from web3 import Web3, AsyncWeb3 \>>> w3 \= Web3(Web3.HTTPProvider('https://')) \>>> w3 \= AsyncWeb3(AsyncWeb3.AsyncHTTPProvider('https://')) \>>> w3 \= await AsyncWeb3(AsyncWeb3.WebSocketProvider('wss://')) This endpoint is provided by the remote node service, typically after you create an account. [Getting Blockchain Info](#id7) [](#getting-blockchain-info "Link to this heading") ------------------------------------------------------------------------------------- It’s time to start using web3.py! Once properly configured, the `w3` instance will allow you to interact with the Ethereum blockchain. Try getting all the information about the latest block: \>>> 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'), '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': \[\]} web3.py can help you read block data, sign and send transactions, deploy and interact with contracts, and a number of other features. A few suggestions from here: * The [Overview](overview.html) page provides a summary of web3.py’s features. * The [`w3.eth`](web3.eth.html#web3.eth.Eth "web3.eth.Eth") API contains the most frequently used methods. * A guide to [Contracts](web3.contract.html#contracts) includes deployment and usage examples. * The nuances of [Transactions](transactions.html) are explained in another guide. Note It is recommended that your development environment have the `PYTHONWARNINGS=default` environment variable set. Some deprecation warnings will not show up without this variable being set. --- # Providers — web3.py 7.6.1 documentation * [](index.html) * Providers * [View page source](_sources/providers.rst.txt) * * * Providers[](#providers "Link to this heading") ================================================ Using Ethereum requires access to an Ethereum node. If you have the means, you’re encouraged to [run your own node](https://ethereum.org/en/developers/docs/nodes-and-clients/run-a-node/) . (Note that you do not need to stake ether to run a node.) If you’re unable to run your own node, you can use a [remote node](https://ethereum.org/en/developers/docs/nodes-and-clients/nodes-as-a-service/) . Once you have access to a node, you can connect to it using a **provider**. Providers generate [JSON-RPC](https://ethereum.org/en/developers/docs/apis/json-rpc/) requests and return the response. This is done by submitting the request to an HTTP, WebSocket, or IPC socket-based server. Note web3.py supports one provider per instance. If you have an advanced use case that requires multiple providers, create and configure a new web3 instance per connection. If you are already happily connected to your Ethereum node, then you can skip the rest of this providers section. Choosing a Provider[](#choosing-a-provider "Link to this heading") -------------------------------------------------------------------- Most nodes have a variety of ways to connect to them. Most commonly: 1. IPC (uses local filesystem: fastest and most secure) 2. WebSocket (works remotely, faster than HTTP) 3. HTTP (more nodes support it) If you’re not sure how to decide, choose this way: * If you have the option of running web3.py on the same machine as the node, choose IPC. * If you must connect to a node on a different computer, use WebSocket. * If your node does not support WebSocket, use HTTP. Once you have decided how to connect, you’ll select and configure the appropriate provider class: * [`HTTPProvider`](#web3.providers.rpc.HTTPProvider "web3.providers.rpc.HTTPProvider") * [`IPCProvider`](#web3.providers.ipc.IPCProvider "web3.providers.ipc.IPCProvider") * `AsyncHTTPProvider` * [`AsyncIPCProvider`](#web3.providers.persistent.AsyncIPCProvider "web3.providers.persistent.AsyncIPCProvider") (Persistent Connection Provider) * [`WebSocketProvider`](#web3.providers.persistent.WebSocketProvider "web3.providers.persistent.WebSocketProvider") (Persistent Connection Provider) Each provider above links to the documentation on how to properly initialize that provider. Once you have reviewed the relevant documentation for the provider of your choice, you are ready to [get started with web3.py](quickstart.html#first-w3-use) . ### Provider via Environment Variable[](#provider-via-environment-variable "Link to this heading") Alternatively, you can set the environment variable `WEB3_PROVIDER_URI` before starting your script, and web3 will look for that provider first. Valid formats for this environment variable are: * `file:///path/to/node/rpc-json/file.ipc` * `http://192.168.1.2:8545` * `https://node.ontheweb.com` * `ws://127.0.0.1:8546` Auto-initialization Provider Shortcuts[](#auto-initialization-provider-shortcuts "Link to this heading") ---------------------------------------------------------------------------------------------------------- ### Geth dev Proof of Authority[](#geth-dev-proof-of-authority "Link to this heading") To connect to a `geth --dev` Proof of Authority instance with the POA middleware loaded by default: \>>> from web3.auto.gethdev import w3 \# confirm that the connection succeeded \>>> w3.is\_connected() True Or, connect to an async web3 instance: \>>> from web3.auto.gethdev import async\_w3 \>>> await async\_w3.provider.connect() \# confirm that the connection succeeded \>>> await async\_w3.is\_connected() True Built In Providers[](#built-in-providers "Link to this heading") ------------------------------------------------------------------ Web3 ships with the following providers which are appropriate for connecting to local and remote JSON-RPC servers. ### HTTPProvider[](#httpprovider "Link to this heading") _class_ web3.providers.rpc.HTTPProvider(_endpoint\_uri_, _request\_kwargs\={}_, _session\=None_, _exception\_retry\_configuration\=ExceptionRetryConfiguration()_)[](#web3.providers.rpc.HTTPProvider "Link to this definition") This provider handles interactions with an HTTP or HTTPS based JSON-RPC server. * `endpoint_uri` should be the full URI to the RPC endpoint such as `'https://localhost:8545'`. For RPC servers behind HTTP connections running on port 80 and HTTPS connections running on port 443 the port can be omitted from the URI. * `request_kwargs` should be a dictionary of keyword arguments which will be passed onto each http/https POST request made to your node. * `session` allows you to pass a `requests.Session` object initialized as desired. * `exception_retry_configuration` is an instance of the [`ExceptionRetryConfiguration`](internals.html#web3.providers.rpc.utils.ExceptionRetryConfiguration "web3.providers.rpc.utils.ExceptionRetryConfiguration") class which allows you to configure how the provider should handle exceptions when making certain requests. Setting this to `None` will disable exception retries. \>>> from web3 import Web3 \>>> w3 \= Web3(Web3.HTTPProvider("http://127.0.0.1:8545")) Note that you should create only one HTTPProvider with the same provider URL per python process, as the HTTPProvider recycles underlying TCP/IP network connections, for better performance. Multiple HTTPProviders with different URLs will work as expected. Under the hood, the `HTTPProvider` uses the python requests library for making requests. If you would like to modify how requests are made, you can use the `request_kwargs` to do so. A common use case for this is increasing the timeout for each request. \>>> from web3 import Web3 \>>> w3 \= Web3(Web3.HTTPProvider("http://127.0.0.1:8545", request\_kwargs\={'timeout': 60})) To tune the connection pool size, you can pass your own `requests.Session`. \>>> from web3 import Web3 \>>> adapter \= requests.adapters.HTTPAdapter(pool\_connections\=20, pool\_maxsize\=20) \>>> session \= requests.Session() \>>> session.mount('http://', adapter) \>>> session.mount('https://', adapter) \>>> w3 \= Web3(Web3.HTTPProvider("http://127.0.0.1:8545", session\=session)) ### IPCProvider[](#ipcprovider "Link to this heading") _class_ web3.providers.ipc.IPCProvider(_ipc\_path\=None_, _timeout\=10_)[](#web3.providers.ipc.IPCProvider "Link to this definition") This provider handles interaction with an IPC Socket based JSON-RPC server. * `ipc_path` is the filesystem path to the IPC socket: \>>> from web3 import Web3 \>>> w3 \= Web3(Web3.IPCProvider("~/Library/Ethereum/geth.ipc")) If no `ipc_path` is specified, it will use a default depending on your operating system. * On Linux and FreeBSD: `~/.ethereum/geth.ipc` * On Mac OS: `~/Library/Ethereum/geth.ipc` * On Windows: `\\.\pipe\geth.ipc` ### AsyncHTTPProvider[](#asynchttpprovider "Link to this heading") _class_ web3.providers.rpc.AsyncHTTPProvider(_endpoint\_uri_, _request\_kwargs\={}_, _exception\_retry\_configuration\=ExceptionRetryConfiguration()_)[](#web3.providers.rpc.AsyncHTTPProvider "Link to this definition") This provider handles interactions with an HTTP or HTTPS based JSON-RPC server asynchronously. * `endpoint_uri` should be the full URI to the RPC endpoint such as `'https://localhost:8545'`. For RPC servers behind HTTP connections running on port 80 and HTTPS connections running on port 443 the port can be omitted from the URI. * `request_kwargs` should be a dictionary of keyword arguments which will be passed onto each http/https POST request made to your node. * `exception_retry_configuration` is an instance of the [`ExceptionRetryConfiguration`](internals.html#web3.providers.rpc.utils.ExceptionRetryConfiguration "web3.providers.rpc.utils.ExceptionRetryConfiguration") class which allows you to configure how the provider should handle exceptions when making certain requests. Setting this to `None` will disable exception retries. The `cache_async_session()` method allows you to use your own `aiohttp.ClientSession` object. \>>> from aiohttp import ClientSession \>>> from web3 import AsyncWeb3, AsyncHTTPProvider \>>> w3 \= AsyncWeb3(AsyncHTTPProvider(endpoint\_uri)) \>>> \# If you want to pass in your own session: \>>> custom\_session \= ClientSession() \>>> await w3.provider.cache\_async\_session(custom\_session) \# This method is an async method so it needs to be handled accordingly Under the hood, the `AsyncHTTPProvider` uses the python [aiohttp](https://docs.aiohttp.org/en/stable/) library for making requests. ### Persistent Connection Providers[](#persistent-connection-providers "Link to this heading") #### Persistent Connection Base Class[](#persistent-connection-base-class "Link to this heading") Note This class is not meant to be used directly. If your provider class inherits from this class, look to these docs for additional configuration options. _class_ web3.providers.persistent.PersistentConnectionProvider(_request\_timeout: [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.13)") \= 50.0_, _subscription\_response\_queue\_size: [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") \= 500_, _silence\_listener\_task\_exceptions: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)") \= False_)[](#web3.providers.persistent.PersistentConnectionProvider "Link to this definition") This is a base provider class, inherited by the following providers: > * [`WebSocketProvider`](#web3.providers.persistent.WebSocketProvider "web3.providers.persistent.WebSocketProvider") > > * [`AsyncIPCProvider`](#web3.providers.persistent.AsyncIPCProvider "web3.providers.persistent.AsyncIPCProvider") > It handles interactions with a persistent connection to a JSON-RPC server. Among its configuration, it houses all of the [`RequestProcessor`](internals.html#web3.providers.persistent.request_processor.RequestProcessor "web3.providers.persistent.request_processor.RequestProcessor") logic for handling the asynchronous sending and receiving of requests and responses. See the [Request Processing for Persistent Connection Providers](internals.html#internals-persistent-connection-providers) section for more details on the internals of persistent connection providers. * `request_timeout` is the timeout in seconds, used when sending data over the connection and waiting for a response to be received from the listener task. Defaults to `50.0`. * `subscription_response_queue_size` is the size of the queue used to store subscription responses, defaults to `500`. While messages are being consumed, this queue should never fill up as it is a transient queue and meant to handle asynchronous receiving and processing of responses. When in sync with the socket stream, this queue should only ever store 1 to a few messages at a time. * `silence_listener_task_exceptions` is a boolean that determines whether exceptions raised by the listener task are silenced. Defaults to `False`, raising any exceptions that occur in the listener task. #### AsyncIPCProvider[](#asyncipcprovider "Link to this heading") _class_ web3.providers.persistent.AsyncIPCProvider(_ipc\_path\=None_, _max\_connection\_retries\=5_)[](#web3.providers.persistent.AsyncIPCProvider "Link to this definition") This provider handles asynchronous, persistent interaction with an IPC Socket based JSON-RPC server. * `ipc_path` is the filesystem path to the IPC socket: * `read_buffer_limit` is the maximum size of data, in bytes, that can be read from the socket at one time. Defaults to 20MB (20 \* 1024 \* 1024). Raises `ReadBufferLimitReached` if the limit is reached, suggesting that the buffer limit be increased. This provider inherits from the [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") class. Refer to the [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") documentation for details on additional configuration options available for this provider. If no `ipc_path` is specified, it will use a default depending on your operating system. * On Linux and FreeBSD: `~/.ethereum/geth.ipc` * On Mac OS: `~/Library/Ethereum/geth.ipc` * On Windows: `\\.\pipe\geth.ipc` #### WebSocketProvider[](#websocketprovider "Link to this heading") _class_ web3.providers.persistent.WebSocketProvider(_endpoint\_uri: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _websocket\_kwargs: Dict\[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\ , Any\] \= {}_)[](#web3.providers.persistent.WebSocketProvider "Link to this definition") This provider handles interactions with an WS or WSS based JSON-RPC server. * `endpoint_uri` should be the full URI to the RPC endpoint such as `'ws://localhost:8546'`. * `websocket_kwargs` this should be a dictionary of keyword arguments which will be passed onto the ws/wss websocket connection. This provider inherits from the [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") class. Refer to the [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") documentation for details on additional configuration options available for this provider. Under the hood, the `WebSocketProvider` uses the python websockets library for making requests. If you would like to modify how requests are made, you can use the `websocket_kwargs` to do so. See the [websockets documentation](https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#websockets.client.WebSocketClientProtocol) for available arguments. #### Using Persistent Connection Providers[](#using-persistent-connection-providers "Link to this heading") The `AsyncWeb3` class may be used as a context manager, utilizing the `async with` syntax, when instantiating with a [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") . This will automatically close the connection when the context manager exits and is the recommended way to initiate a persistent connection to the provider. A similar example using a `websockets` connection as an asynchronous context manager can be found in the [websockets connection](https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#websockets.client.connect) docs. \>>> 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("web3.providers.AsyncIPCProvider") # for the AsyncIPCProvider ... logger \= logging.getLogger("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(): ... print(f"{response}\\n") ... \# handle responses here ... ... if some\_condition: ... \# unsubscribe from new block headers and break out of ... \# iterator ... await w3.eth.unsubscribe(subscription\_id) ... break ... ... \# still an open connection, make any other requests and get ... \# responses via send / receive ... latest\_block \= await w3.eth.get\_block("latest") ... print(f"Latest block: {latest\_block}") ... ... \# the connection closes automatically when exiting the context ... \# manager (the \`async with\` block) \>>> asyncio.run(context\_manager\_subscription\_example()) The `AsyncWeb3` class may also be used as an asynchronous iterator, utilizing the `async for` syntax, when instantiating with a [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") . This may be used to set up an indefinite websocket connection and reconnect automatically if the connection is lost. A similar example using a `websockets` connection as an asynchronous iterator can be found in the [websockets connection](https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#websockets.client.connect) docs. \>>> import asyncio \>>> import websockets \>>> from web3 import AsyncWeb3 \>>> from web3.providers.persistent import ( ... AsyncIPCProvider, ... WebSocketProvider, ... ) \>>> async def subscription\_iterator\_example(): ... \# async for w3 in AsyncWeb3(AsyncIPCProvider("./path/to/filename.ipc")): # for the AsyncIPCProvider ... async for w3 in AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")): \# for the WebSocketProvider ... try: ... ... ... except websockets.ConnectionClosed: ... continue \# run the example \>>> asyncio.run(subscription\_iterator\_example()) Awaiting the instantiation with a [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") , or instantiating and awaiting the `connect()` method is also possible. Both of these examples are shown below. \>>> async def await\_instantiation\_example(): ... \# w3 = await AsyncWeb3(AsyncIPCProvider("./path/to/filename.ipc")) # for the AsyncIPCProvider ... w3 \= await AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")) \# for the WebSocketProvider ... ... \# some code here ... ... \# manual cleanup ... await w3.provider.disconnect() \# run the example \>>> asyncio.run(await\_instantiation\_example) \>>> async def await\_provider\_connect\_example(): ... \# w3 = AsyncWeb3(AsyncIPCProvider("./path/to/filename.ipc")) # for the AsyncIPCProvider ... w3 \= AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")) \# for the WebSocketProvider ... await w3.provider.connect() ... ... \# some code here ... ... \# manual cleanup ... await w3.provider.disconnect() \# run the example \>>> asyncio.run(await\_provider\_connect\_example) [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") classes use the [`RequestProcessor`](internals.html#web3.providers.persistent.request_processor.RequestProcessor "web3.providers.persistent.request_processor.RequestProcessor") class under the hood to sync up the receiving of responses and response processing for one-to-one and one-to-many request-to-response requests. Refer to the [`RequestProcessor`](internals.html#web3.providers.persistent.request_processor.RequestProcessor "web3.providers.persistent.request_processor.RequestProcessor") documentation for details. #### AsyncWeb3 with Persistent Connection Providers[](#asyncweb3-with-persistent-connection-providers "Link to this heading") When an `AsyncWeb3` class is connected to a [`PersistentConnectionProvider`](#web3.providers.persistent.PersistentConnectionProvider "web3.providers.persistent.PersistentConnectionProvider") , some attributes and methods become available. > socket[](#socket "Link to this definition") > > The public API for interacting with the websocket connection is available via the `socket` attribute of the `Asyncweb3` class. This attribute is an instance of the [`PersistentConnection`](#web3.providers.persistent.persistent_connection.PersistentConnection "web3.providers.persistent.persistent_connection.PersistentConnection") > class and is the main interface for interacting with the socket connection. #### Interacting with the Persistent Connection[](#interacting-with-the-persistent-connection "Link to this heading") _class_ web3.providers.persistent.persistent\_connection.PersistentConnection[](#web3.providers.persistent.persistent_connection.PersistentConnection "Link to this definition") This class handles interactions with a persistent socket connection. It is available via the `socket` attribute on the `AsyncWeb3` class. The `PersistentConnection` class has the following methods and attributes: subscriptions[](#web3.providers.persistent.persistent_connection.PersistentConnection.subscriptions "Link to this definition") This attribute returns the current active subscriptions as a dict mapping the subscription `id` to a dict of metadata about the subscription request. process\_subscriptions()[](#web3.providers.persistent.persistent_connection.PersistentConnection.process_subscriptions "Link to this definition") This method is available for listening to websocket subscriptions indefinitely. It is an asynchronous iterator that yields strictly one-to-many (e.g. `eth_subscription` responses) request-to-response messages from the websocket connection. To receive responses for one-to-one request-to-response calls, use the standard API for making requests via the appropriate module (e.g. `block_num = await w3.eth.block_number`) The responses from this method are formatted by _web3.py_ formatters and run through the middleware that were present at the time of subscription. Examples on how to use this method can be seen above in the [Using Persistent Connection Providers](#using-persistent-connection-providers) section. send(_method: RPCEndpoint_, _params: Sequence\[Any\]_)[](#web3.providers.persistent.persistent_connection.PersistentConnection.send "Link to this definition") This method is available strictly for sending raw requests to the socket, if desired. It is not recommended to use this method directly, as the responses will not be formatted by _web3.py_ formatters or run through the middleware. Instead, use the methods available on the respective web3 module. For example, use `w3.eth.get_block("latest")` instead of `w3.socket.send("eth_getBlockByNumber", ["latest", True])`. recv()[](#web3.providers.persistent.persistent_connection.PersistentConnection.recv "Link to this definition") The `recv()` method can be used to receive the next response for a request from the socket. The response from this method is the raw response. This is not the recommended way to receive a response for a request, as it is not formatted by _web3.py_ formatters or run through the middleware. Instead, use the methods available on the respective web3 module (e.g. `block_num = await w3.eth.block_number`) for retrieving responses for one-to-one request-to-response calls. make\_request(_method: RPCEndpoint_, _params: Sequence\[Any\]_)[](#web3.providers.persistent.persistent_connection.PersistentConnection.make_request "Link to this definition") This method is available for making requests to the socket and retrieving the response. It is not recommended to use this method directly, as the responses will not be properly formatted by _web3.py_ formatters or run through the middleware. Instead, use the methods available on the respective web3 module. For example, use `w3.eth.get_block("latest")` instead of `w3.socket.make_request("eth_getBlockByNumber", ["latest", True])`. ### LegacyWebSocketProvider[](#legacywebsocketprovider "Link to this heading") Warning `LegacyWebSocketProvider` is deprecated and is likely to be removed in a future major release. Please use `WebSocketProvider` instead. _class_ web3.providers.legacy\_websocket.LegacyWebSocketProvider(_endpoint\_uri_\[, _websocket\_timeout_, _websocket\_kwargs_\])[](#web3.providers.legacy_websocket.LegacyWebSocketProvider "Link to this definition") This provider handles interactions with an WS or WSS based JSON-RPC server. * `endpoint_uri` should be the full URI to the RPC endpoint such as `'ws://localhost:8546'`. * `websocket_timeout` is the timeout in seconds, used when receiving or sending data over the connection. Defaults to 10. * `websocket_kwargs` this should be a dictionary of keyword arguments which will be passed onto the ws/wss websocket connection. \>>> from web3 import Web3 \>>> w3 \= Web3(Web3.LegacyWebSocketProvider("ws://127.0.0.1:8546")) Under the hood, `LegacyWebSocketProvider` uses the python `websockets` library for making requests. If you would like to modify how requests are made, you can use the `websocket_kwargs` to do so. See the [websockets documentation](https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#websockets.client.WebSocketClientProtocol) for available arguments. Unlike HTTP connections, the timeout for WS connections is controlled by a separate `websocket_timeout` argument, as shown below. \>>> from web3 import Web3 \>>> w3 \= Web3(Web3.LegacyWebSocketProvider("ws://127.0.0.1:8546", websocket\_timeout\=60)) ### AutoProvider[](#autoprovider "Link to this heading") `AutoProvider` is the default used when initializing [`web3.Web3`](web3.main.html#web3.Web3 "web3.Web3") without any providers. There’s rarely a reason to use it explicitly. ### EthereumTesterProvider[](#ethereumtesterprovider "Link to this heading") Warning Experimental: This provider is experimental. There are still significant gaps in functionality. However it is being actively developed and supported. _class_ web3.providers.eth\_tester.EthereumTesterProvider(_ethereum\_tester\=None_, _api\_endpoints\=None_)[](#web3.providers.eth_tester.EthereumTesterProvider "Link to this definition") _class_ web3.providers.eth\_tester.AsyncEthereumTesterProvider(_ethereum\_tester\=None_, _api\_endpoints\=None_)[](#web3.providers.eth_tester.AsyncEthereumTesterProvider "Link to this definition") This provider integrates with the `eth-tester` library. The `ethereum_tester` constructor argument should be an instance of the `EthereumTester` or a subclass of `BaseChainBackend` class provided by the `eth-tester` library. The `api_endpoints` argument should be a `dict` of RPC endpoints. You can see the structure and defaults [here](https://github.com/ethereum/web3.py/blob/283b536c7d53e605c61468941e3fc07a6c5d0c09/web3/providers/eth_tester/defaults.py#L228) . If you would like a custom `eth-tester` instance to test with, see the `eth-tester` library [documentation](https://github.com/ethereum/eth-tester) for details. \>>> from web3 import Web3, EthereumTesterProvider \>>> w3 \= Web3(EthereumTesterProvider()) Note To install the needed dependencies to use EthereumTesterProvider, you can install the pip extras package that has the correct interoperable versions of the `eth-tester` and `py-evm` dependencies needed: e.g. `pip install "web3[tester]"` --- # Transactions — web3.py 7.6.1 documentation * [](index.html) * Transactions * [View page source](_sources/transactions.rst.txt) * * * Transactions[](#transactions "Link to this heading") ====================================================== There are a handful of ways to interact with transactions in web3.py. See the [Web3.eth module](web3.eth.html#web3-eth-methods) for a full list of transaction-related methods. Note that you may also [batch requests](web3.main.html#batch-requests) that read transaction data, but not send new transactions in a batch request. The rest of this guide covers the decision tree for how to send a transaction. Note Prefer to view this code in a Jupyter Notebook? View the repo [here](https://github.com/wolovim/ethereum-notebooks/blob/master/Sending%20Transactions.ipynb) . There are two methods for sending transactions using web3.py: [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") and [`send_raw_transaction()`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction") . A brief guide: 1. Want to sign a transaction offline or send pre-signed transactions? * use [`sign_transaction`](https://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account.sign_transaction "(in eth-account v0.13)") + [`send_raw_transaction()`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction") 2. Are you primarily using the same account for all transactions and would you prefer to save a few lines of code? * configure the `build` method for [`SignAndSendRawMiddlewareBuilder`](middleware.html#web3.middleware.SignAndSendRawMiddlewareBuilder "web3.middleware.SignAndSendRawMiddlewareBuilder") , then * use [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") 3. Otherwise: * load account via eth-account ([`w3.eth.account.from_key(pk)`](https://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account.from_key "(in eth-account v0.13)") ), then * use [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") Interacting with or deploying a contract? * Option 1: [`transact()`](web3.contract.html#web3.contract.ContractFunction.transact "web3.contract.ContractFunction.transact") uses [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") under the hood * Option 2: [`build_transaction()`](web3.contract.html#web3.contract.ContractFunction.build_transaction "web3.contract.ContractFunction.build_transaction") + [`sign_transaction`](https://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account.sign_transaction "(in eth-account v0.13)") + [`send_raw_transaction()`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction") An example for each can be found below. Chapter 0: `w3.eth.send_transaction` with `eth-tester`[](#chapter-0-w3-eth-send-transaction-with-eth-tester "Link to this heading") ------------------------------------------------------------------------------------------------------------------------------------- Many tutorials use `eth-tester` (via EthereumTesterProvider) for convenience and speed of conveying ideas/building a proof of concept. Transactions sent by test accounts are auto-signed. from web3 import Web3, EthereumTesterProvider w3 \= Web3(EthereumTesterProvider()) \# eth-tester populates accounts with test ether: acct1 \= w3.eth.accounts\[0\] some\_address \= "0x0000000000000000000000000000000000000000" \# when using one of its generated test accounts, \# eth-tester signs the tx (under the hood) before sending: tx\_hash \= w3.eth.send\_transaction({ "from": acct1, "to": some\_address, "value": 123123123123123 }) tx \= w3.eth.get\_transaction(tx\_hash) assert tx\["from"\] \== acct1 Chapter 1: `w3.eth.send_transaction` + signer middleware[](#chapter-1-w3-eth-send-transaction-signer-middleware "Link to this heading") ----------------------------------------------------------------------------------------------------------------------------------------- The [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") method is convenient and to-the-point. If you want to continue using the pattern after graduating from `eth-tester`, you can utilize web3.py middleware to sign transactions from a particular account: from web3.middleware import SignAndSendRawMiddlewareBuilder import os \# Note: Never commit your key in your code! Use env variables instead: pk \= os.environ.get('PRIVATE\_KEY') \# Instantiate an Account object from your key: acct2 \= w3.eth.account.from\_key(pk) \# For the sake of this example, fund the new account: w3.eth.send\_transaction({ "from": acct1, "value": w3.to\_wei(3, 'ether'), "to": acct2.address }) \# Add acct2 as auto-signer: w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(acct2), layer\=0) \# pk also works: w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(pk), layer=0) \# Transactions from \`acct2\` will then be signed, under the hood, in the middleware: tx\_hash \= w3.eth.send\_transaction({ "from": acct2.address, "value": 3333333333, "to": some\_address }) tx \= w3.eth.get\_transaction(tx\_hash) assert tx\["from"\] \== acct2.address \# Optionally, you can set a default signer as well: \# w3.eth.default\_account = acct2.address \# Then, if you omit a "from" key, acct2 will be used. Chapter 2: `w3.eth.send_raw_transaction`[](#chapter-2-w3-eth-send-raw-transaction "Link to this heading") ----------------------------------------------------------------------------------------------------------- if you don’t opt for the middleware, you’ll need to: * build each transaction, * [`sign_transaction`](https://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account.sign_transaction "(in eth-account v0.13)") , and * then use [`send_raw_transaction()`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction") . \# 1. Build a new tx transaction \= { 'from': acct2.address, 'to': some\_address, 'value': 1000000000, 'nonce': w3.eth.get\_transaction\_count(acct2.address), 'gas': 200000, 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, } \# 2. Sign tx with a private key signed \= w3.eth.account.sign\_transaction(transaction, pk) \# 3. Send the signed transaction tx\_hash \= w3.eth.send\_raw\_transaction(signed.raw\_transaction) tx \= w3.eth.get\_transaction(tx\_hash) assert tx\["from"\] \== acct2.address Chapter 3: Contract transactions[](#chapter-3-contract-transactions "Link to this heading") --------------------------------------------------------------------------------------------- The same concepts apply for contract interactions, at least under the hood. Executing a function on a smart contract requires sending a transaction, which is typically done in one of two ways: * executing the [`transact()`](web3.contract.html#web3.contract.ContractFunction.transact "web3.contract.ContractFunction.transact") function, or * [`build_transaction()`](web3.contract.html#web3.contract.ContractFunction.build_transaction "web3.contract.ContractFunction.build_transaction") , then signing and sending the raw transaction. ######################################### \#### SMOL CONTRACT FOR THIS EXAMPLE: #### ######################################### \# // SPDX-License-Identifier: MIT \# pragma solidity 0.8.17; # \# contract Billboard { \# string public message; # \# constructor(string memory \_message) { \# message = \_message; \# } # \# function writeBillboard(string memory \_message) public { \# message = \_message; \# } \# } \# 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" --- # Middleware — web3.py 7.6.1 documentation * [](index.html) * Middleware * [View page source](_sources/middleware.rst.txt) * * * Middleware[](#middleware "Link to this heading") ================================================== `Web3` is instantiated with layers of middleware by default. They sit between the public `Web3` methods and the [Providers](providers.html) , and are used to perform sanity checks, convert data types, enable ENS support, and more. Each layer can modify the request and/or response. While several middleware are enabled by default, others are available for optional use, and you’re free to create your own! Each middleware layer gets invoked before the request reaches the provider, and then processes the result after the provider returns, in reverse order. However, it is possible for a middleware to return early from a call without the request ever getting to the provider (or even reaching the middleware that are in deeper layers). Configuring Middleware[](#configuring-middleware "Link to this heading") -------------------------------------------------------------------------- Middleware can be added, removed, replaced, and cleared at runtime. To make that easier, you can name the middleware for later reference. ### Middleware Order[](#middleware-order "Link to this heading") Think of the middleware as being layered in an onion, where you initiate a web3.py request at the outermost layer of the onion, and the Ethereum node (like geth) receives and responds to the request inside the innermost layer of the onion. Here is a (simplified) diagram: New request from web3.py | | v \`\`\`\`\`Layer 2\`\`\`\`\`\` \`\`\`\`\`\`\` \`\`\`\`\`\`\` \`\`\`\`\` | \`\`\`\` \`\`\`\` v \`\`\`\` \`\`\` \`\`\` \`. \`\`\`\`\`\`\`\`Layer 1\`\`\`\`\`\`\` \`.\` \`\` \`\`\`\` \`\`\`\`\` .\` \`. \`\`\` | \`\`\` \`.\` .\` \`\`\` v \`\`\` \`. \`. \`.\` \`\`\` .\` \`\` .\` \`Layer 0\` \`\` .\` \`\` \`. \`\`\`\`\` \`\`\`\`\`\` . .\` \`. \`\` \`\`\` | \`\`\` .\` . . \`\` \`.\` | \`\` . . . \`. \`\` JSON-RPC call .\` . .\` . . \`\` | . \`\` . \`\` . . v . . . . .\` . . . \`\` . . . Ethereum node .\` . . . . . . . . . \`\` \`. | . . . . . .\` | .\` . . \`. .\` .\` Response .\` .\` . . . \`.\` | \`.\` \`. . \`. . \`\`\` | \`\`\`\` \`. . . \`. \`\`\`\`\` v \`\`\`\` \`. \`\` . .\` \`\`\`Layer 0\`\` \`\` \`. . \`. \`.\` \`. . \`. | \`.\` \`. .\` \`\`\` | \`\`\` .\` \`. \`\`\` v \`\`\`\` \`.\` \`\` \`\`\`\`\`\` \`\`\`\`\` .\` \`\` \`\`\`\`\`Layer 1\`\`\`\`\` \`.\` \`\`\` \`\`\` \`\`\`\` | \`\`\` \`\`\`\`\` v \`\`\`\` \`\`\`\`\`\` \`\`\`\`\` \`\`\`\`\`\`\`\`\`Layer 2\`\`\`\`\`\`\`\`\`\` | v Returned value in web3.py The middleware are maintained in `Web3.middleware_onion`. See below for the API. When specifying middleware in a list, or retrieving the list of middleware, they will be returned in the order of outermost layer first and innermost layer last. In the above example, that means that `w3.middleware_onion.middleware` would return the middleware in the order of: `[2, 1, 0]`. ### Middleware Stack API[](#middleware-stack-api "Link to this heading") To add or remove items in different layers, use the following API: Web3.middleware\_onion.add(_middleware_, _name\=None_)[](#Web3.middleware_onion.add "Link to this definition") Middleware will be added to the outermost layer. That means the new middleware will modify the request first, and the response last. You can optionally name it with any hashable object, typically a string. \>>> w3 \= Web3(...) \>>> w3.middleware\_onion.add(web3.middleware.GasPriceStrategyMiddleware) \# or \>>> w3.middleware\_onion.add(web3.middleware.GasPriceStrategyMiddleware, 'gas\_price\_strategy') Web3.middleware\_onion.inject(_middleware_, _name\=None_, _layer\=None_)[](#Web3.middleware_onion.inject "Link to this definition") Inject a named middleware to an arbitrary layer. The current implementation only supports injection at the innermost or outermost layers. Note that injecting to the outermost layer is equivalent to calling [`Web3.middleware_onion.add()`](#Web3.middleware_onion.add "Web3.middleware_onion.add") . \# Either of these will put the gas\_price\_strategy middleware at the innermost layer \>>> w3 \= Web3(...) \>>> w3.middleware\_onion.inject(web3.middleware.GasPriceStrategyMiddleware, layer\=0) \# or \>>> w3.middleware\_onion.inject(web3.middleware.GasPriceStrategyMiddleware, 'gas\_price\_strategy', layer\=0) Web3.middleware\_onion.remove(_middleware_)[](#Web3.middleware_onion.remove "Link to this definition") Middleware will be removed from whatever layer it was in. If you added the middleware with a name, use the name to remove it. If you added the middleware as an object, use the object again later to remove it: \>>> w3 \= Web3(...) \>>> w3.middleware\_onion.remove(web3.middleware.GasPriceStrategyMiddleware) \# or \>>> w3.middleware\_onion.remove('gas\_price\_strategy') Web3.middleware\_onion.replace(_old\_middleware_, _new\_middleware_)[](#Web3.middleware_onion.replace "Link to this definition") Middleware will be replaced from whatever layer it was in. If the middleware was named, it will continue to have the same name. If it was un-named, then you will now reference it with the new middleware object. \>>> from web3.middleware import GasPriceStrategyMiddleware, AttributeDictMiddleware \>>> w3 \= Web3(provider, middleware\=\[GasPriceStrategyMiddleware, AttributeDictMiddleware\]) \>>> w3.middleware\_onion.replace(GasPriceStrategyMiddleware, AttributeDictMiddleware) \# this is now referenced by the new middleware object, so to remove it: \>>> w3.middleware\_onion.remove(AttributeDictMiddleware) \# or, if it was named \>>> w3.middleware\_onion.replace('gas\_price\_strategy', AttributeDictMiddleware) \# this is still referenced by the original name, so to remove it: \>>> w3.middleware\_onion.remove('gas\_price\_strategy') Web3.middleware\_onion.clear()[](#Web3.middleware_onion.clear "Link to this definition") Empty all the middleware, including the default ones. \>>> w3 \= Web3(...) \>>> w3.middleware\_onion.clear() \>>> assert len(w3.middleware\_onion) \== 0 Web3.middleware\_onion.middleware[](#Web3.middleware_onion.middleware "Link to this definition") Return all the current middleware for the `Web3` instance in the appropriate order for importing into a new `Web3` instance. \>>> w3\_1 \= Web3(...) \# add uniquely named middleware: \>>> w3\_1.middleware\_onion.add(web3.middleware.GasPriceStrategyMiddleware, 'test\_middleware') \# export middleware from first w3 instance \>>> middleware \= w3\_1.middleware\_onion.middleware \# import into second instance \>>> w3\_2 \= Web3(..., middleware\=middleware) \>>> assert w3\_1.middleware\_onion.middleware \== w3\_2.middleware\_onion.middleware \>>> assert w3\_2.middleware\_onion.get('test\_middleware') ### Instantiate with Custom Middleware[](#instantiate-with-custom-middleware "Link to this heading") Instead of working from the default list, you can specify a custom list of middleware when initializing Web3: Web3(middleware\=\[my\_middleware1, my\_middleware2\]) Warning This will _replace_ the default middleware. To keep the default functionality, either use `middleware_onion.add()` from above, or add the default middleware to your list of new middleware. Default Middleware[](#default-middleware "Link to this heading") ------------------------------------------------------------------ The following middleware are included by default: * `gas_price_strategy` * `ens_name_to_address` * `attrdict` * `validation` * `gas_estimate` The defaults are defined in the `get_default_middleware()` method in `web3/manager.py`. ### AttributeDict[](#attributedict "Link to this heading") _class_ web3.middleware.AttributeDictMiddleware[](#web3.middleware.AttributeDictMiddleware "Link to this definition") This middleware recursively converts any dictionary type in the result of a call to an `AttributeDict`. This enables dot-syntax access, like `eth.get_block('latest').number` in addition to `eth.get_block('latest')['number']`. Note Accessing a property via attribute breaks type hinting. For this reason, this feature is available as a middleware, which may be removed if desired. ### ENS Name to Address Resolution[](#ens-name-to-address-resolution "Link to this heading") _class_ web3.middleware.ENSNameToAddressMiddleware[](#web3.middleware.ENSNameToAddressMiddleware "Link to this definition") This middleware converts Ethereum Name Service (ENS) names into the address that the name points to. For example [`w3.eth.send_transaction`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") will accept .eth names in the ‘from’ and ‘to’ fields. Note This middleware only converts ENS names on chains where the proper ENS contracts are deployed to support this functionality. All other cases will result in a `NameNotFound` error. ### Gas Price Strategy[](#gas-price-strategy "Link to this heading") _class_ web3.middleware.GasPriceStrategyMiddleware[](#web3.middleware.GasPriceStrategyMiddleware "Link to this definition") Warning Gas price strategy is only supported for legacy transactions. The London fork introduced `maxFeePerGas` and `maxPriorityFeePerGas` transaction parameters which should be used over `gasPrice` whenever possible. This adds a `gasPrice` to transactions if applicable and when a gas price strategy has been set. See [Gas Price API](gas_price.html#gas-price) for information about how gas price is derived. ### Buffered Gas Estimate[](#buffered-gas-estimate "Link to this heading") _class_ web3.middleware.BufferedGasEstimateMiddleware[](#web3.middleware.BufferedGasEstimateMiddleware "Link to this definition") This adds a gas estimate to transactions if `gas` is not present in the transaction parameters. Sets gas to: `min(w3.eth.estimate_gas + gas_buffer, gas_limit)` where the gas\_buffer default is 100,000 ### Validation[](#validation "Link to this heading") _class_ web3.middleware.ValidationMiddleware[](#web3.middleware.ValidationMiddleware "Link to this definition") This middleware includes block and transaction validators which perform validations for transaction parameters. Optional Middleware[](#optional-middleware "Link to this heading") -------------------------------------------------------------------- `Web3` includes optional middleware for common use cases. Below is a list of available middleware which are not enabled by default. ### Stalecheck[](#stalecheck "Link to this heading") web3.middleware.StalecheckMiddlewareBuilder()[](#web3.middleware.StalecheckMiddlewareBuilder "Link to this definition") This middleware checks how stale the blockchain is, and interrupts calls with a failure if the blockchain is too old. * `allowable_delay` is the length in seconds that the blockchain is allowed to be behind of `time.time()` Because this middleware takes an argument, you must create the middleware with a method call. two\_day\_stalecheck \= StalecheckMiddlewareBuilder.build(60 \* 60 \* 24 \* 2) web3.middleware\_onion.add(two\_day\_stalecheck) If the latest block in the blockchain is older than 2 days in this example, then the middleware will raise a `StaleBlockchain` exception on every call except `web3.eth.get_block()`. ### Proof of Authority[](#proof-of-authority "Link to this heading") _class_ web3.middleware.ExtraDataToPOAMiddleware[](#web3.middleware.ExtraDataToPOAMiddleware "Link to this definition") Important It is **crucial** that this middleware is injected at the 0th layer of the middleware onion, using `w3.middleware_onion.inject(ExtraDataToPOAMiddleware, layer=0)`, to guarantee it is the _first_ middleware to process the response and modify the `extraData` field. This ensures it processes the field before any other middleware attempts to validate it. `ExtraDataToPOAMiddleware` is required to connect to `geth --dev` and may also be needed for other EVM compatible blockchains like Polygon or BNB Chain (Binance Smart Chain). If the middleware is not injected at the 0th layer of the middleware onion, you may get errors like the example below when interacting with your EVM node. web3.exceptions.ExtraDataLengthError: The field extraData is 97 bytes, but should be 32. It is quite likely that you are connected to a POA chain. Refer to http://web3py.readthedocs.io/en/stable/middleware.html#proof-of-authority for more details. The full extraData is: HexBytes('...') The easiest way to connect to a default `geth --dev` instance which loads the middleware is: \>>> from web3.auto.gethdev import w3 \# confirm that the connection succeeded \>>> w3.client\_version 'Geth/v1.14.12-stable-4bb3c89d/linux-amd64/go1.22.4' This example connects to a local `geth --dev` instance on Linux with a unique IPC location and loads the middleware: \>>> from web3 import Web3, IPCProvider \# connect to the IPC location started with 'geth --dev --datadir ~/mynode' \>>> w3 \= Web3(IPCProvider('~/mynode/geth.ipc')) \>>> from web3.middleware import ExtraDataToPOAMiddleware \# inject the poa compatibility middleware to the innermost layer (0th layer) \>>> w3.middleware\_onion.inject(ExtraDataToPOAMiddleware, layer\=0) \# confirm that the connection succeeded \>>> w3.client\_version 'Geth/v1.14.12-stable-4bb3c89d/linux-amd64/go1.22.4' #### Why is `ExtraDataToPOAMiddleware` necessary?[](#why-is-extradatatopoamiddleware-necessary "Link to this heading") There is no strong community consensus on a single Proof-of-Authority (PoA) standard yet. Some nodes have successful experiments running though. One is go-ethereum (geth), which uses a prototype PoA for its development mode and the Goerli test network. Unfortunately, it does deviate from the yellow paper specification, which constrains the `extraData` field in each block to a maximum of 32-bytes. Geth is one such example where PoA uses more than 32 bytes, so this middleware modifies the block data a bit before returning it. ### Locally Managed Log and Block Filters[](#locally-managed-log-and-block-filters "Link to this heading") web3.middleware.LocalFilterMiddleware()[](#web3.middleware.LocalFilterMiddleware "Link to this definition") This middleware provides an alternative to ethereum node managed filters. When used, Log and Block filter logic are handled locally while using the same web3 filter api. Filter results are retrieved using JSON-RPC endpoints that don’t rely on server state. \>>> from web3 import Web3, EthereumTesterProvider \>>> w3 \= Web3(EthereumTesterProvider()) \>>> from web3.middleware import LocalFilterMiddleware \>>> w3.middleware\_onion.add(LocalFilterMiddleware) \# Normal block and log filter apis behave as before. \>>> block\_filter \= w3.eth.filter("latest") \>>> log\_filter \= myContract.events.myEvent.build\_filter().deploy() ### Signing[](#signing "Link to this heading") web3.middleware.SignAndSendRawMiddlewareBuilder()[](#web3.middleware.SignAndSendRawMiddlewareBuilder "Link to this definition") This middleware automatically captures transactions, signs them, and sends them as raw transactions. The `from` field on the transaction, or `w3.eth.default_account` must be set to the address of the private key for this middleware to have any effect. The `build` method for this middleware builder takes a single argument: > * `private_key_or_account` A single private key or a tuple, list or set of private keys. > > > Keys can be in any of the following formats: > > > > * An `eth_account.LocalAccount` object > > > > * An `eth_keys.PrivateKey` object > > > > * A raw private key as a hex string or byte string > > > Important Since this middleware signs transactions, it must always run after any middleware that modifies the transaction. Therefore, it is recommended to inject the signing middleware at the 0th layer of the middleware onion using `w3.middleware_onion.inject(SignAndSendRawMiddlewareBuilder.build(...), layer=0)`. Ensure that any transaction-modifying middleware exists in a higher layer within the onion so that it runs before the signing middleware. Note If used with `ExtraDataToPOAMiddleware`, the injection order doesn’t matter, as the `extraData` field isn’t involved in transaction signing. The key is ensuring `SignAndSendRawMiddlewareBuilder` runs after any middleware that modifies the transaction. \>>> from web3 import Web3, EthereumTesterProvider \>>> w3 \= Web3(EthereumTesterProvider) \>>> from web3.middleware import SignAndSendRawMiddlewareBuilder \>>> from eth\_account import Account \>>> acct \= Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') \>>> w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(acct), layer\=0) \>>> w3.eth.default\_account \= acct.address [Hosted nodes](web3.eth.account.html#local-vs-hosted) (like Infura or Alchemy) only support signed transactions. This often results in `send_raw_transaction` being used repeatedly. Instead, we can automate this process with `SignAndSendRawMiddlewareBuilder.build(private_key_or_account)`. \>>> from web3 import Web3 \>>> w3 \= Web3(Web3.HTTPProvider('HTTP\_ENDPOINT')) \>>> from web3.middleware import SignAndSendRawMiddlewareBuilder \>>> from eth\_account import Account \>>> import os \>>> acct \= w3.eth.account.from\_key(os.environ.get('PRIVATE\_KEY')) \>>> w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(acct), layer\=0) \>>> w3.eth.default\_account \= acct.address \>>> \# use \`eth\_sendTransaction\` to automatically sign and send the raw transaction \>>> w3.eth.send\_transaction(tx\_dict) HexBytes('0x09511acf75918fd03de58141d2fd409af4fd6d3dce48eb3aa1656c8f3c2c5c21') Similarly, with AsyncWeb3: \>>> from web3 import AsyncWeb3 \>>> async\_w3 \= AsyncWeb3(AsyncHTTPProvider('HTTP\_ENDPOINT')) \>>> from web3.middleware import SignAndSendRawMiddlewareBuilder \>>> 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 \>>> \# use \`eth\_sendTransaction\` to automatically sign and send the raw transaction \>>> await async\_w3.eth.send\_transaction(tx\_dict) HexBytes('0x09511acf75918fd03de58141d2fd409af4fd6d3dce48eb3aa1656c8f3c2c5c21') Now you can send a transaction from acct.address without having to build and sign each raw transaction. When making use of this signing middleware, when sending dynamic fee transactions (recommended over legacy transactions), the transaction `type` of `2` (or `'0x2'`) is necessary. This is because transaction signing is validated based on the transaction `type` parameter. This value defaults to `'0x2'` when `maxFeePerGas` and / or `maxPriorityFeePerGas` are present as parameters in the transaction as these params imply a dynamic fee transaction. Since these values effectively replace the legacy `gasPrice` value, do not set a `gasPrice` for dynamic fee transactions. Doing so will lead to validation issues. \# dynamic fee transaction, introduced by EIP-1559: \>>> dynamic\_fee\_transaction \= { ... 'type': '0x2', \# optional - defaults to '0x2' when dynamic fee transaction params are present ... 'from': acct.address, \# optional if w3.eth.default\_account was set with acct.address ... 'to': receiving\_account\_address, ... 'value': 22, ... 'maxFeePerGas': 2000000000, \# required for dynamic fee transactions ... 'maxPriorityFeePerGas': 1000000000, \# required for dynamic fee transactions ... } \>>> w3.eth.send\_transaction(dynamic\_fee\_transaction) A legacy transaction still works in the same way as it did before EIP-1559 was introduced: \>>> legacy\_transaction \= { ... 'to': receiving\_account\_address, ... 'value': 22, ... 'gasPrice': 123456, \# optional - if not provided, gas\_price\_strategy (if exists) or eth\_gasPrice is used ... } \>>> w3.eth.send\_transaction(legacy\_transaction) Creating Custom Middleware[](#creating-custom-middleware "Link to this heading") ---------------------------------------------------------------------------------- To write your own middleware, create a class and extend from the base `Web3Middleware` class, then override only the parts of the middleware that make sense for your use case. Note The Middleware API borrows from the Django middleware API introduced in version 1.10.0. If all you need is to modify the params before a request is made, you can override the `request_processor` method, make the necessary tweaks to the params, and pass the arguments to the next element in the middleware stack. Need to do some processing on the response? Override the `response_processor` method and return the modified response. The pattern: from web3.middleware import Web3Middleware class CustomMiddleware(Web3Middleware): def request\_processor(self, method, params): \# Pre-request processing goes here before passing to the next middleware. return (method, params) def response\_processor(self, method, response): \# Response processing goes here before passing to the next middleware. return response \# If your provider is asynchronous, override the async methods instead: async def async\_request\_processor(self, method, params): \# Pre-request processing goes here before passing to the next middleware. return (method, params) async def async\_response\_processor(self, method, response): \# Response processing goes here before passing to the next middleware. return response If you wish to prevent making a call under certain conditions, you can override the `wrap_make_request` method. This allows for defining pre-request processing, skipping or making the request under certain conditions, as well as response processing before passing it to the next middleware. from web3.middleware import Web3Middleware class CustomMiddleware(Web3Middleware): def wrap\_make\_request(self, make\_request): def middleware(method, params): \# pre-request processing goes here response \= make\_request(method, params) \# make the request \# response processing goes here return response return middleware \# If your provider is asynchronous, override the async method instead: async def async\_wrap\_make\_request(self, make\_request): async def middleware(method, params): \# pre-request processing goes here response \= await make\_request(method, params) \# response processing goes here return response return middleware Custom middleware can be added to the stack via the class itself, using the [Middleware Stack API](#middleware-stack-api) . The `name` kwarg is optional. For example: from web3 import Web3 from my\_module import ( CustomMiddleware, ) w3 \= Web3(HTTPProvider(endpoint\_uri\="...")) \# add the middleware to the stack as the class w3.middleware\_onion.add(CustomMiddleware, name\="custom\_middleware") --- # Troubleshooting — web3.py 7.6.1 documentation * [](index.html) * Troubleshooting * [View page source](_sources/troubleshooting.rst.txt) * * * Troubleshooting[](#troubleshooting "Link to this heading") ============================================================ Set up a clean environment[](#set-up-a-clean-environment "Link to this heading") ---------------------------------------------------------------------------------- Many things can cause a broken environment. You might be on an unsupported version of Python. Another package might be installed that has a name or version conflict. Often, the best way to guarantee a correct environment is with `virtualenv`, like: \# 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 Note Remember that each new terminal session requires you to reactivate your virtualenv, like: `$ source ~/.venv-py3/bin/activate` Why can’t I use a particular function?[](#why-can-t-i-use-a-particular-function "Link to this heading") --------------------------------------------------------------------------------------------------------- Note that a web3.py instance must be configured before you can use most of its capabilities. One symptom of not configuring the instance first is an error that looks something like this: `AttributeError: type object 'Web3' has no attribute 'eth'`. To properly configure your web3.py instance, specify which provider you’re using to connect to the Ethereum network. An example configuration, if you’re connecting to a locally run node, might be: \>>> 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(...) Refer to the [Providers](providers.html#providers) documentation for further help with configuration. Why isn’t my web3 instance connecting to the network?[](#why-isn-t-my-web3-instance-connecting-to-the-network "Link to this heading") --------------------------------------------------------------------------------------------------------------------------------------- You can check that your instance is connected via the `is_connected` method: \>>> w3.is\_connected() False There are a variety of explanations for why you may see `False` here. To help you diagnose the problem, `is_connected` has an optional `show_traceback` argument: \>>> w3.is\_connected(show\_traceback\=True) \# this is an example, your error may differ \# ProviderConnectionError: Problem connecting to provider with error: : cannot connect to IPC socket at path: None If you’re running a local node, such as Geth, double-check that you’ve indeed started the binary and that you’ve started it from the intended directory - particularly if you’ve specified a relative path to its ipc file. If that does not address your issue, it’s probable that you still have a Provider configuration issue. There are several options for configuring a Provider, detailed [here](providers.html#providers) . How do I get ether for my test network?[](#how-do-i-get-ether-for-my-test-network "Link to this heading") ----------------------------------------------------------------------------------------------------------- Test networks usually have something called a “faucet” to help get test ether to people who want to use it. The faucet simply sends you test ether when you visit a web page, or ping a chat bot, etc. Each test network has its own version of test ether, so each one must maintain its own faucet. Faucet mechanisms tend to come and go, so a web search for “ethereum testnet faucet” should give you the most up-to-date options. How do I use my MetaMask accounts from web3.py?[](#how-do-i-use-my-metamask-accounts-from-web3-py "Link to this heading") --------------------------------------------------------------------------------------------------------------------------- Export your private key from MetaMask, and use the local private key tools in web3.py to sign and send transactions. See [how to export your private key](https://ethereum.stackexchange.com/questions/33053/what-is-a-private-key-in-an-ethereum-wallet-like-metamask-and-how-do-i-find-it) and [Accounts](web3.eth.account.html#eth-account) . How do I create an account?[](#how-do-i-create-an-account "Link to this heading") ----------------------------------------------------------------------------------- In general, your options for accounts are: * Import a keystore file for an account and [extract the private key](web3.eth.account.html#extract-geth-pk) . * Create an account via the [eth-account](web3.eth.account.html#eth-account) API, e.g., `new_acct = w3.eth.account.create()`. * Use an external service (e.g. Metamask) to generate a new account, then securely import its private key. Warning Don’t store real value in an account until you are familiar with security best practices. If you lose your private key, you lose your account! Why doesn’t my transaction work on another network?[](#why-doesn-t-my-transaction-work-on-another-network "Link to this heading") ----------------------------------------------------------------------------------------------------------------------------------- web3.py is an Ethereum-specific library, which defaults to [“type 2” EIP-1559 transactions](https://ethereum.org/en/developers/docs/transactions/#typed-transaction-envelope) as of the London network upgrade. Some chains (including Ethereum L2s) do not support the same transaction types. If your chain doesn’t support this transaction type, you likely need to create a “legacy” transaction, i.e., include `gasPrice`, but not `type`, `maxFeePerGas`, or `maxPriorityFeePerGas` in your transaction body. If that doesn’t resolve your issue, open a GitHub issue or reach out for help in the community [Discord](https://discord.gg/GHryRvPB84) server if you’re having trouble with an Ethereum-ecosystem chain. If you’re debugging in an alternative ecosystem, please find another appropriate forum to raise your question. How do I conform to ABI types?[](#how-do-i-conform-to-abi-types "Link to this heading") ----------------------------------------------------------------------------------------- The web3 library follows the following conventions: ### Bytes vs Text[](#bytes-vs-text "Link to this heading") * The term _bytes_ is used to refer to the binary representation of a string. * The term _text_ is used to refer to unicode representations of strings. ### Hexadecimal Representations[](#hexadecimal-representations "Link to this heading") * All hexadecimal values will be returned as text. * All hexadecimal values will be `0x` prefixed. ### Ethereum Addresses[](#ethereum-addresses "Link to this heading") All addresses must be supplied in one of three ways: * A 20-byte hexadecimal that is checksummed using the [EIP-55](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md) spec. * A 20-byte binary address (python bytes type). * While connected to an Ethereum Name Service (ENS) supported chain, an ENS name (often in the form `myname.eth`). ### Disabling Strict Bytes Type Checking[](#disabling-strict-bytes-type-checking "Link to this heading") There is a boolean flag on the `Web3` class and the `ENS` class that will disable strict bytes type checking. This allows bytes values of Python strings and allows byte strings less than the specified byte size, appropriately padding values that need padding. To disable stricter checks, set the `w3.strict_bytes_type_checking` (or `ns.strict_bytes_type_checking`) flag to `False`. This will no longer cause the `Web3` / `ENS` instance to raise an error if a Python string is passed in without a “0x” prefix. It will also render valid byte strings or hex strings that are below the exact number of bytes specified by the ABI type by padding the value appropriately, according to the ABI type. See the [Disabling Strict Checks for Bytes Types](web3.contract.html#disable-strict-byte-check) section for an example on using the flag and more details. Note If a standalone `ENS` instance is instantiated from a `Web3` instance, i.e. `ns = ENS.from_web3(w3)`, it will inherit the value of the `w3.strict_bytes_type_checking` flag from the `Web3` instance at the time of instantiation. Also of note, all modules on the `Web3` class will inherit the value of this flag, since all modules use the parent `w3` object reference under the hood. This means that `w3.eth.w3.strict_bytes_type_checking` will always have the same value as `w3.strict_bytes_type_checking`. For more details on the ABI specification, refer to the [Solidity ABI Spec](https://docs.soliditylang.org/en/latest/abi-spec.html) . ### Types by Example[](#types-by-example "Link to this heading") Let’s use a contrived contract to demonstrate input types in web3.py: contract ManyTypes { // booleans bool public b; // unsigned ints uint8 public u8; uint256 public u256; uint256\[\] public u256s; // signed ints int8 public i8; // addresses address public addr; address\[\] public addrs; // bytes bytes1 public b1; // structs struct S { address sa; bytes32 sb; } mapping(address => S) addrStructs; function updateBool(bool x) public { b = x; } function updateUint8(uint8 x) public { u8 = x; } function updateUint256(uint256 x) public { u256 = x; } function updateUintArray(uint256\[\] memory x) public { u256s = x; } function updateInt8(int8 x) public { i8 = x; } function updateAddr(address x) public { addr = x; } function updateBytes1(bytes1 x) public { b1 = x; } function updateMapping(S memory x) public { addrStructs\[x.sa\] = x; } } #### Booleans[](#booleans "Link to this heading") contract\_instance.functions.updateBool(True).transact() #### Unsigned Integers[](#unsigned-integers "Link to this heading") contract\_instance.functions.updateUint8(255).transact() contract\_instance.functions.updateUint256(2\*\*256 \- 1).transact() contract\_instance.functions.updateUintArray(\[1, 2, 3\]).transact() #### Signed Integers[](#signed-integers "Link to this heading") contract\_instance.functions.updateInt8(\-128).transact() #### Addresses[](#addresses "Link to this heading") contract\_instance.functions.updateAddr("0x0000000000000000000000000000000000000000").transact() #### Bytes[](#bytes "Link to this heading") contract\_instance.functions.updateBytes1(HexBytes(255)).transact() #### Structs[](#structs "Link to this heading") contract\_instance.functions.updateMapping({"sa": "0x0000000000000000000000000000000000000000", "sb": HexBytes(123)}).transact() How can I optimize Ethereum JSON-RPC API access?[](#how-can-i-optimize-ethereum-json-rpc-api-access "Link to this heading") ----------------------------------------------------------------------------------------------------------------------------- Your Ethereum node JSON-RPC API might be slow when fetching multiple and large requests, especially when running batch jobs. Here are some tips for how to speed up your web3.py application. * Run your client locally, e.g., [Go Ethereum](https://github.com/ethereum/go-ethereum) or [TurboGeth](https://github.com/ledgerwatch/turbo-geth) . The network latency and speed are the major limiting factors for fast API access. * Use IPC communication instead of HTTP/WebSockets. See [Choosing a Provider](providers.html#choosing-provider) . * Use an optimised JSON decoder. A future iteration of web3.py may change the default decoder or provide an API to configure one, but for now, you may patch the provider class to use [ujson](https://pypi.org/project/ujson/) . """JSON-RPC decoding optimised for web3.py""" from typing import cast import ujson from web3.providers import JSONBaseProvider from web3.types import RPCResponse def \_fast\_decode\_rpc\_response(raw\_response: bytes) \-> RPCResponse: decoded \= ujson.loads(raw\_response) return cast(RPCResponse, decoded) def patch\_provider(provider: JSONBaseProvider): """Monkey-patch web3.py provider for faster JSON decoding. Call this on your provider after construction. This greatly improves JSON-RPC API access speeds, when fetching multiple and large responses. """ provider.decode\_rpc\_response \= \_fast\_decode\_rpc\_response Why am I getting Visual C++ or Cython not installed error?[](#why-am-i-getting-visual-c-or-cython-not-installed-error "Link to this heading") ----------------------------------------------------------------------------------------------------------------------------------------------- Some Windows users that do not have Microsoft Visual C++ version 14.0 or greater installed may see an error message when installing web3.py as shown below: error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ To fix this error, download and install Microsoft Visual C++ from here : [Microsoft Visual C++ Redistributable for Visual Studio](https://visualstudio.microsoft.com/downloads/#microsoft-visual-c-redistributable-for-visual-studio-2019) * [x64 Visual C++](https://aka.ms/vs/16/release/VC_redist.x64.exe) * [x86 Visual C++](https://aka.ms/vs/16/release/VC_redist.x86.exe) * [ARM64 Visual C++](https://aka.ms/vs/16/release/VC_redist.arm64.exe) How do I convert currency denominations?[](#how-do-i-convert-currency-denominations "Link to this heading") ------------------------------------------------------------------------------------------------------------- The following denominations are supported: | | | | --- | --- | | denomination | amount in wei | | wei | 1 | | kwei | 1000 | | babbage | 1000 | | femtoether | 1000 | | mwei | 1000000 | | lovelace | 1000000 | | picoether | 1000000 | | gwei | 1000000000 | | shannon | 1000000000 | | nanoether | 1000000000 | | nano | 1000000000 | | szabo | 1000000000000 | | microether | 1000000000000 | | micro | 1000000000000 | | finney | 1000000000000000 | | milliether | 1000000000000000 | | milli | 1000000000000000 | | ether | 1000000000000000000 | | kether | 1000000000000000000000 | | grand | 1000000000000000000000 | | mether | 1000000000000000000000000 | | gether | 1000000000000000000000000000 | | tether | 1000000000000000000000000000000 | You can use the `from_wei()` method to convert a balance to ether (or another denomination). \>>> web3.from\_wei(3841357360894980500000001, 'ether') Decimal('3841357.360894980500000001') To convert back to wei, you can use the inverse function, `to_wei()`. Note that Python’s default floating point precision is insufficient for this use case, so it’s necessary to cast the value to a [Decimal](https://docs.python.org/3/library/decimal.html) if it isn’t already. \>>> from decimal import Decimal \>>> web3.to\_wei(Decimal('3841357.360894980500000001'), 'ether') 3841357360894980500000001 Best practice: If you need to work with multiple currency denominations, default to wei. A typical workflow may require a conversion from some denomination to wei, then from wei to whatever you need. \>>> web3.to\_wei(Decimal('0.000000005'), 'ether') 5000000000 \>>> web3.from\_wei(5000000000, 'gwei') Decimal('5') How do I adjust the log levels?[](#how-do-i-adjust-the-log-levels "Link to this heading") ------------------------------------------------------------------------------------------- web3.py internally uses [Python logging subsystem](https://docs.python.org/3/library/logging.html) . If you want to run your application logging in debug mode, below is an example of how to make some JSON-RPC traffic quieter. import logging import coloredlogs def setup\_logging(log\_level\=logging.DEBUG): """Setup root logger and quiet some levels.""" logger \= logging.getLogger() \# Set log format to display the logger name to hunt down verbose logging modules fmt \= "%(name)-25s %(levelname)-8s %(message)s" \# Use colored logging output for console with the coloredlogs package \# https://pypi.org/project/coloredlogs/ coloredlogs.install(level\=log\_level, fmt\=fmt, logger\=logger) \# Disable logging of JSON-RPC requests and replies logging.getLogger("web3.RequestManager").setLevel(logging.WARNING) logging.getLogger("web3.providers.HTTPProvider").setLevel(logging.WARNING) \# logging.getLogger("web3.RequestManager").propagate = False \# Disable all internal debug logging of requests and urllib3 \# E.g. HTTP traffic logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) return logger --- # Web3 Internals — web3.py 7.6.1 documentation * [](index.html) * Web3 Internals * [View page source](_sources/internals.rst.txt) * * * Web3 Internals[](#web3-internals "Link to this heading") ========================================================== Warning This section of the documentation is for advanced users. You should probably stay away from these APIs if you don’t know what you are doing. The Web3 library has multiple layers of abstraction between the public api exposed by the web3 object and the backend or node that web3 is connecting to. * **Providers** are responsible for the actual communication with the blockchain such as sending JSON-RPC requests over HTTP or an IPC socket. * **Middleware** provide hooks for monitoring and modifying requests and responses to and from the provider. * **Managers** provide thread safety and primitives to allow for asynchronous usage of web3. Here are some common things you might want to do with these APIs. * Redirect certain RPC requests to different providers such as sending all _read_ operations to a provider backed by a remote node and all _write_ operations to a local node that you control. * Transparently intercept transactions sent over `eth_sendTransaction`, sign them locally, and then send them through `eth_sendRawTransaction`. * Modify the response from an RPC request so that it is returned in different format such as converting all integer values to their hexadecimal representation. * Validate the inputs to RPC requests Request Lifecycle[](#request-lifecycle "Link to this heading") ---------------------------------------------------------------- Each web3 RPC call passes through these layers in the following manner. \*\*\*\*\*\*\*\*\*\*\* \*\*\*\*\*\*\*\*\*\*\*\* | Request | | Response | \*\*\*\*\*\*\*\*\*\*\* \*\*\*\*\*\*\*\*\*\*\*\* | ^ v | +-----------------------------+ | Manager | +-----------------------------+ | ^ v | +-----------------------------+ | Middleware | +-----------------------------+ | ^ v | +-----------------------------+ | Provider | +-----------------------------+ You can visualize this relationship like an onion, with the Provider at the center. The request originates from the `Manager`, outside of the onion, passing down through each layer of the onion until it reaches the `Provider` at the center. The `Provider` then handles the request, producing a response which will then pass back out from the center of the onion, through each layer until it is finally returned by the `Manager`. Providers[](#providers "Link to this heading") ------------------------------------------------ A provider is responsible for all direct blockchain interactions. In most cases this means interacting with the JSON-RPC server for an ethereum node over HTTP or an IPC socket. There is however nothing which requires providers to be RPC based, allowing for providers designed for testing purposes which use an in-memory EVM to fulfill requests. ### Writing your own Provider[](#writing-your-own-provider "Link to this heading") Writing your own provider requires implementing two required methods as well as setting the middleware the provider should use. BaseProvider.make\_request(_method_, _params_)[](#BaseProvider.make_request "Link to this definition") Each provider class **must** implement this method. This method **should** return a JSON object with either a `'result'` key in the case of success, or an `'error'` key in the case of failure. * `method` This will be a string representing the JSON-RPC method that is being called such as `'eth_sendTransaction'`. * `params` This will be a list or other iterable of the parameters for the JSON-RPC method being called. BaseProvider.is\_connected(_show\_traceback\=False_)[](#BaseProvider.is_connected "Link to this definition") This function should return `True` or `False` depending on whether the provider should be considered _connected_. For example, an IPC socket based provider should return `True` if the socket is open and `False` if the socket is closed. If set to `True`, the optional `show_traceback` boolean will raise a `ProviderConnectionError` and provide information on why the provider should not be considered _connected_. BaseProvider.middleware[](#BaseProvider.middleware "Link to this definition") This should be an iterable of middleware. You can set a new list of middleware by assigning to `provider.middleware`, with the first middleware that processes the request at the beginning of the list. ### Provider Configurations[](#provider-configurations "Link to this heading") #### Request Caching[](#request-caching "Link to this heading") Important Familiarize yourself with the validation logic for request caching before enabling it. Since this feature often requires making additional requests under the hood to try to guarantee the validity of the data, it may create unnecessary overhead for your use case. Validation can be turned off by setting the `request_cache_validation_threshold` option to `None`, caching all allowed requests, or configured for adjusting performance to your needs. Request caching can be configured at the provider level via the following configuration options on the provider instance: * `cache_allowed_requests: bool = False` * `cacheable_requests: Optional[Set[RPCEndpoint]]` * `request_cache_validation_threshold: Optional[Union[RequestCacheValidationThreshold, int]]` For requests that don’t rely on block data (e.g., `eth_chainId`), enabling request caching by setting the `cache_allowed_requests` option to `True` will cache all responses. This is safe to do. However, for requests that rely on block data (e.g., `eth_getBlockByNumber`), it is not safe to always cache their responses because block data can change - during a chain reorganization or while finality has not been reached, for example. The `request_cache_validation_threshold` option allows configuring a safe threshold for caching responses that depend on block data. By default, this option is configured to internal values deemed “safe” for the chain id you are connected to. If you are connected to mainnet Ethereum, this value is set to the `finalized` block number. If you are connected to another chain, this value is set to a time interval in seconds, from the current time, that is deemed “safe” for that chain’s finality mechanism. **It’s important to understand that, in order to perform these validations, extra requests are sometimes made to the node to get the appropriate information. For a transaction request, for example, it is necessary to get the block information to validate the transaction is beyond the safe threshold. This can create overhead, especially for high-frequency requests. For this reason, it is important to understand when to turn on caching and how to configure the validation appropriately for your use case in order to avoid unnecessary overhead.** We keep a list of some reasonable values for bigger chains and use the time interval of 1 hour for everything else. Below is a list of the default values for internally configured chains: > * ETH: RequestCacheValidationThreshold.FINALIZED (“finalized” block) > > * ARB1: 7 days > > * ZKSYNC: 1 hour > > * OETH: 3 minutes > > * MATIC: 30 minutes > > * ZKEVM: 1 hour > > * BASE: 7 days > > * SCR: 1 hour > > * GNO: 5 minutes > > * AVAX: 2 minutes > > * BNB: 2 minutes > > * FTM: 1 minute > For Ethereum mainnet, for example, this means that a request’s response will be cached if the block number the request relies on is less than or equal to the `finalized` block number. If the block number exceeds the `finalized` block number, the response won’t be cached. For all others, the response will be cached if the block timestamp related to the data that is being requested is older than or equal to the time interval configured for that chain. For any chain not on this list, the default value is set to 1 hour (this includes all testnets). This behavior can be modified by setting the `request_cache_validation_threshold` option to `RequestCacheValidationThreshold.SAFE`, which uses the `safe` block as the threshold (Ethereum mainnet only), to your own time interval in seconds (for any chain, including mainnet Ethereum), or to `None`, which disables any validation and caches all requests (this is not recommended for non testnet chains). The `RequestCacheValidationThreshold` enum, for mainnet `finalized` and `safe` values, is imported from the `web3.utils` module. Note that the `cacheable_requests` option can be used to specify a set of RPC endpoints that are allowed to be cached. By default, this option is set to an internal list of deemed-safe-to-cache endpoints, excluding endpoints such as `eth_call`, whose responses can vary and are not safe to cache. The default list of cacheable requests is below, with requests validated by the `request_cache_validation_threshold` option in bold: > * eth\_chainId > > * web3\_clientVersion > > * net\_version > > * **eth\_getBlockByNumber** > > * **eth\_getRawTransactionByBlockNumberAndIndex** > > * **eth\_getBlockTransactionCountByNumber** > > * **eth\_getUncleByBlockNumberAndIndex** > > * **eth\_getUncleCountByBlockNumber** > > * **eth\_getBlockByHash** > > * **eth\_getTransactionByHash** > > * **eth\_getTransactionByBlockNumberAndIndex** > > * **eth\_getTransactionByBlockHashAndIndex** > > * **eth\_getBlockTransactionCountByHash** > > * **eth\_getRawTransactionByBlockHashAndIndex** > > * **eth\_getUncleByBlockHashAndIndex** > > * **eth\_getUncleCountByBlockHash** > from web3 import Web3, HTTPProvider from web3.utils import RequestCacheValidationThreshold w3 \= Web3(HTTPProvider( endpoint\_uri\="...", \# optional flag to turn on cached requests, defaults to \`\`False\`\` cache\_allowed\_requests\=True, \# optional, defaults to an internal list of deemed-safe-to-cache endpoints (see above) cacheable\_requests\={"eth\_chainId", "eth\_getBlockByNumber"}, \# optional, defaults to a value that is based on the chain id (see above) request\_cache\_validation\_threshold\=60 \* 60, \# 1 hour \# request\_cache\_validation\_threshold=RequestCacheValidationThreshold.SAFE, # Ethereum mainnet only )) #### Retry Requests for HTTP Providers[](#retry-requests-for-http-providers "Link to this heading") `HTTPProvider` and `AsyncHTTPProvider` instances retry certain requests by default on exceptions. This can be configured via the `exception_retry_configuration` property on the provider instance, which takes a [`ExceptionRetryConfiguration`](#web3.providers.rpc.utils.ExceptionRetryConfiguration "web3.providers.rpc.utils.ExceptionRetryConfiguration") class as its value. The retry mechanism employs an exponential backoff strategy, starting from the initial value determined by the `backoff_factor`, and doubling the delay with each attempt, up to the `retries` value. Below is an example showing the default options for the retry configuration and how to override them. _class_ web3.providers.rpc.utils.ExceptionRetryConfiguration[](#web3.providers.rpc.utils.ExceptionRetryConfiguration "Link to this definition") errors[](#web3.providers.rpc.utils.ExceptionRetryConfiguration.errors "Link to this definition") A tuple of exceptions that the provider should retry on. The default is `HTTPProvider`: `(ConnectionError, requests.HTTPError, requests.Timeout)` and `AsyncHTTPProvider`: `(aiohttp.ClientError, asyncio.TimeoutError)`. retries[](#web3.providers.rpc.utils.ExceptionRetryConfiguration.retries "Link to this definition") The number of retries to attempt. The default is 5. backoff\_factor[](#web3.providers.rpc.utils.ExceptionRetryConfiguration.backoff_factor "Link to this definition") The initial delay multiplier, which doubles with each retry attempt. The default is 0.125. method\_allowlist[](#web3.providers.rpc.utils.ExceptionRetryConfiguration.method_allowlist "Link to this definition") A list of retryable methods. The default is an in-house list of deemed-safe-to- retry methods. from web3 import Web3, HTTPProvider from web3.providers.rpc.utils import ( REQUEST\_RETRY\_ALLOWLIST, ExceptionRetryConfiguration, ) w3 \= Web3(HTTPProvider( endpoint\_uri\="...", exception\_retry\_configuration\=ExceptionRetryConfiguration( errors\=DEFAULT\_EXCEPTIONS, \# number of retries to attempt retries\=5, \# initial delay multiplier, doubles with each retry attempt backoff\_factor\=0.125, \# an in-house default list of retryable methods method\_allowlist\=REQUEST\_RETRY\_ALLOWLIST, ), )) For the different http providers, `DEFAULT_EXCEPTIONS` is defined as: * `HTTPProvider`: `(ConnectionError, requests.HTTPError, requests.Timeout)` * `AsyncHTTPProvider`: `(ConnectionError, aiohttp.ClientError, asyncio.TimeoutError)` Setting `retry_configuration` to `None` will disable retries on exceptions for the provider instance. from web3 import Web3, HTTPProvider w3 \= Web3(HTTPProvider(endpoint\_uri\="...", retry\_configuration\=None) Managers[](#managers "Link to this heading") ---------------------------------------------- The Manager acts as a gatekeeper for the request/response lifecycle. It is unlikely that you will need to change the Manager as most functionality can be implemented in the Middleware layer. Request Processing for Persistent Connection Providers[](#request-processing-for-persistent-connection-providers "Link to this heading") ------------------------------------------------------------------------------------------------------------------------------------------ _class_ web3.providers.persistent.request\_processor.RequestProcessor[](#web3.providers.persistent.request_processor.RequestProcessor "Link to this definition") The `RequestProcessor` class is responsible for the storing and syncing up of asynchronous requests to responses for a `PersistentConnectionProvider`. The [`WebSocketProvider`](providers.html#web3.providers.persistent.WebSocketProvider "web3.providers.persistent.WebSocketProvider") and the [`AsyncIPCProvider`](providers.html#web3.providers.persistent.AsyncIPCProvider "web3.providers.persistent.AsyncIPCProvider") are two persistent connection providers. In order to send a request and receive a response to that same request, `PersistentConnectionProvider` instances have to match request _id_ values to response _id_ values coming back from the socket connection. Any provider that does not adhere to the [JSON-RPC 2.0 specification](https://www.jsonrpc.org/specification) in this way will not work with `PersistentConnectionProvider` instances. The specifics of how the request processor handles this are outlined below. ### Listening for Responses[](#listening-for-responses "Link to this heading") Implementations of the `PersistentConnectionProvider` class have a message listener background task that is called when the socket connection is established. This task is responsible for listening for any and all messages coming in over the socket connection and storing them in the `RequestProcessor` instance internal to the `PersistentConnectionProvider` instance. The `RequestProcessor` instance is responsible for storing the messages in the correct cache, either the one-to-one cache or the one-to-many (subscriptions) queue, depending on whether the message has a JSON-RPC _id_ value or not. ### One-To-One Requests[](#one-to-one-requests "Link to this heading") One-to-one requests can be summarized as any request that expects only one response back. An example is using the `eth` module API to request the latest block number. \>>> 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()) With persistent socket connections, we have to call `send()` and asynchronously receive responses via another means, generally by calling `recv()` or by iterating on the socket connection for messages. As outlined above, the `PersistentConnectionProvider` class has a message listener background task that handles the receiving of messages. Due to this asynchronous nature of sending and receiving, in order to make one-to-one request-to-response calls work, we have to save the request information somewhere so that, when the response is received, we can match it to the original request that was made (i.e. the request with a matching _id_ to the response that was received). The stored request information is then used to process the response when it is received, piping it through the response formatters and middleware internal to the _web3.py_ library. In order to store the request information, the `RequestProcessor` class has an internal `RequestInformation` cache. The `RequestInformation` class saves important information about a request. _class_ web3.\_utils.caching.RequestInformation[](#web3._utils.caching.RequestInformation "Link to this definition") method[](#web3._utils.caching.RequestInformation.method "Link to this definition") The name of the method - e.g. “eth\_subscribe”. params[](#web3._utils.caching.RequestInformation.params "Link to this definition") The params used when the call was made - e.g. (“newPendingTransactions”, True). response\_formatters[](#web3._utils.caching.RequestInformation.response_formatters "Link to this definition") The formatters that will be used to process the response. middleware\_response\_processors[](#web3._utils.caching.RequestInformation.middleware_response_processors "Link to this definition") Any middleware that processes responses that is present on the instance at the time of the request is appended here, in order, so the response may be piped through that logic when it comes in. subscription\_id[](#web3._utils.caching.RequestInformation.subscription_id "Link to this definition") If the request is an `eth_subscribe` request, rather than popping this information from the cache when the response to the subscription call comes in (i.e. the subscription _id_), we save the subscription id with the request information so that we can correctly process all subscription messages that come in with that subscription _id_. For one-to-one request-to-response calls, this value is always `None`. One-to-one responses, those that include a JSON-RPC _id_ in the response object, are stored in an internal `SimpleCache` class, isolated from any one-to-many responses. When the `PersistentConnectionProvider` is looking for a response internally, it will expect the message listener task to store the response in this cache. Since the request _id_ is used in the cache key generation, it will then look for a cache key that matches the response _id_ with that of the request _id_. If the cache key is found, the response is processed and returned to the user. If the cache key is not found, the operation will time out and raise a `TimeExhausted` exception. This timeout can be configured by the user when instantiating the `PersistentConnectionProvider` instance via the `response_timeout` keyword argument. ### One-To-Many Requests[](#one-to-many-requests "Link to this heading") One-to-many requests can be summarized by any request that expects many responses as a result of the initial request. The only current example is the `eth_subscribe` request. The initial `eth_subscribe` request expects only one response, the subscription _id_ value, but it also expects to receive many `eth_subscription` messages if and when the request is successful. For this reason, the original request is considered a one-to-one request so that a subscription _id_ can be returned to the user on the same line, but the `process_subscriptions()` method on the `PersistentConnection` class, the public API for interacting with the active persistent socket connection, is set up to receive `eth_subscription` responses over an asynchronous interator pattern. \>>> 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()) One-to-many responses, those that do not include a JSON-RPC _id_ in the response object, are stored in an internal `asyncio.Queue` instance, isolated from any one-to-one responses. When the `PersistentConnectionProvider` is looking for one-to-many responses internally, it will expect the message listener task to store these messages in this queue. Since the order of the messages is important, the queue is a FIFO queue. The `process_subscriptions()` method on the `PersistentConnection` class is set up to pop messages from this queue as FIFO over an asynchronous iterator pattern. If the stream of messages from the socket is not being interrupted by any other tasks, the queue will generally be in sync with the messages coming in over the socket. That is, the message listener will put a message in the queue and the `process_subscriptions()` method will pop that message from the queue and yield control of the loop back to the listener. This will continue until the socket connection is closed or the user unsubscribes from the subscription. If the stream of messages lags a bit, or the provider is not consuming messages but has subscribed to a subscription, this internal queue may fill up with messages until it reaches its max size and then trigger a waiting `asyncio.Event` until the provider begins consuming messages from the queue again. For this reason, it’s important to begin consuming messages from the queue, via the `process_subscriptions()` method, as soon as a subscription is made. --- # Web3 API — web3.py 7.6.1 documentation * [](index.html) * Web3 API * [View page source](_sources/web3.main.rst.txt) * * * Web3 API[](#web3-api "Link to this heading") ============================================== _class_ web3.Web3(_provider_)[](#web3.Web3 "Link to this definition") Each `Web3` instance exposes the following APIs. [Providers](#id2) [](#providers "Link to this heading") --------------------------------------------------------- Web3.HTTPProvider[](#web3.Web3.HTTPProvider "Link to this definition") Convenience API to access [`web3.providers.rpc.HTTPProvider`](providers.html#web3.providers.rpc.HTTPProvider "web3.providers.rpc.HTTPProvider") Web3.IPCProvider[](#web3.Web3.IPCProvider "Link to this definition") Convenience API to access [`web3.providers.ipc.IPCProvider`](providers.html#web3.providers.ipc.IPCProvider "web3.providers.ipc.IPCProvider") [Attributes](#id3) [](#attributes "Link to this heading") ----------------------------------------------------------- Web3.api[](#web3.Web3.api "Link to this definition") Returns the current Web3 version. \>>> web3.api "4.7.0" Web3.client\_version[](#web3.Web3.client_version "Link to this definition") * Delegates to `web3_clientVersion` RPC Method Returns the current client version. \>>> web3.client\_version 'Geth/v1.4.11-stable-fed692f6/darwin/go1.7' [Batch Requests](#id4) [](#batch-requests "Link to this heading") ------------------------------------------------------------------- Web3.batch\_requests()[](#web3.Web3.batch_requests "Link to this definition") > The JSON-RPC API allows for batch requests, meaning you can send a single request that contains an array of request objects. Generally, this may be useful when you want to limit the number of requests you send to a node. > > You can choose to build a batch of requests within or outside of a context manager: > > with w3.batch\_requests() as batch: > batch.add(w3.eth.get\_block(6)) > batch.add(w3.eth.get\_block(4)) > batch.add(w3.eth.get\_block(2)) > > responses \= batch.execute() > assert len(responses) \== 3 > > Using the batch object directly: > > batch \= w3.batch\_requests() > batch.add(w3.eth.get\_block(1)) > batch.add(w3.eth.get\_block(2)) > responses \= batch.execute() > assert len(responses) \== 2 > > Contract interactions can be included in batch requests by omitting the `call()` method: > > batch.add(math\_contract.functions.multiply7(0)) > > Additionally, if you need to make multiple calls of the same function, you can add a mapping of the function to its arguments: > > batch \= w3.batch\_requests() > batch.add\_mapping( > { > math\_contract.functions.multiply7: \[1, 2\], > w3.eth.get\_block: \[3, 4\], > } > ) > responses \= batch.execute() > assert len(responses) \== 4 > > The `execute` method returns a list of responses in the order they were included in the batch. > > If you need to abandon or rebuild a batch request, utilize the `clear` method: > > batch \= w3.batch\_requests() > batch.add(w3.eth.get\_block(1)) > batch.add(w3.eth.get\_block(2)) > assert len(batch.\_requests\_info) \== 2 > > batch.clear() > assert batch.\_requests\_info \== \[\] > > Note > > Only read-only operations that exist within modules on the `Web3` class (e.g. `w3.eth`, `w3.net`) are supported by `batch_requests`. Unsupported methods include: > > * [`subscribe`](web3.eth.html#web3.eth.Eth.subscribe "web3.eth.Eth.subscribe") > > * [`unsubscribe`](web3.eth.html#web3.eth.Eth.unsubscribe "web3.eth.Eth.unsubscribe") > > * [`send_raw_transaction`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction") > > * [`send_transaction`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") > > * [`sign_transaction`](web3.eth.html#web3.eth.Eth.sign_transaction "web3.eth.Eth.sign_transaction") > > * [`sign`](web3.eth.html#web3.eth.Eth.sign "web3.eth.Eth.sign") > > * [`sign_typed_data`](web3.eth.html#web3.eth.Eth.sign_typed_data "web3.eth.Eth.sign_typed_data") > > * `w3.provider.make_request()`. > ### Async Batch Requests[](#async-batch-requests "Link to this heading") If using one of the asynchronous providers, you’ll need to make use of the `async_execute` method and the `async` and `await` keywords as appropriate. Note If performance is a concern, consider using `asyncio.gather()` with single concurrent requests instead of an asynchronous batch request. It will generally be the faster option due to the overhead of batching. \# context manager: async with w3.batch\_requests() as batch: batch.add(w3.eth.get\_block(6)) batch.add(w3.eth.get\_block(4)) batch.add(w3.eth.get\_block(2)) responses \= await batch.async\_execute() assert len(responses) \== 3 \# object: batch \= w3.batch\_requests() batch.add(w3.eth.get\_block(1)) batch.add(w3.eth.get\_block(2)) responses \= await batch.async\_execute() assert len(responses) \== 2 [Encoding and Decoding Helpers](#id5) [](#encoding-and-decoding-helpers "Link to this heading") ------------------------------------------------------------------------------------------------- Web3.to\_hex(_primitive\=None_, _hexstr\=None_, _text\=None_)[](#web3.Web3.to_hex "Link to this definition") Takes a variety of inputs and returns it in its hexadecimal representation. It follows the rules for converting to hex in the [JSON-RPC spec](https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding) \>>> Web3.to\_hex(0) '0x0' \>>> Web3.to\_hex(1) '0x1' \>>> Web3.to\_hex(0x0) '0x0' \>>> Web3.to\_hex(0x000F) '0xf' \>>> Web3.to\_hex(b'') '0x' \>>> Web3.to\_hex(b'\\x00\\x0F') '0x000f' \>>> Web3.to\_hex(False) '0x0' \>>> Web3.to\_hex(True) '0x1' \>>> Web3.to\_hex(hexstr\='0x000F') '0x000f' \>>> Web3.to\_hex(hexstr\='000F') '0x000f' \>>> Web3.to\_hex(text\='') '0x' \>>> Web3.to\_hex(text\='cowmö') '0x636f776dc3b6' Web3.to\_text(_primitive\=None_, _hexstr\=None_, _text\=None_)[](#web3.Web3.to_text "Link to this definition") Takes a variety of inputs and returns its string equivalent. Text gets decoded as UTF-8. \>>> Web3.to\_text(0x636f776dc3b6) 'cowmö' \>>> Web3.to\_text(b'cowm\\xc3\\xb6') 'cowmö' \>>> Web3.to\_text(hexstr\='0x636f776dc3b6') 'cowmö' \>>> Web3.to\_text(hexstr\='636f776dc3b6') 'cowmö' \>>> Web3.to\_text(text\='cowmö') 'cowmö' Web3.to\_bytes(_primitive\=None_, _hexstr\=None_, _text\=None_)[](#web3.Web3.to_bytes "Link to this definition") Takes a variety of inputs and returns its bytes equivalent. Text gets encoded as UTF-8. \>>> Web3.to\_bytes(0) b'\\x00' \>>> Web3.to\_bytes(0x000F) b'\\x0f' \>>> Web3.to\_bytes(b'') b'' \>>> Web3.to\_bytes(b'\\x00\\x0F') b'\\x00\\x0f' \>>> Web3.to\_bytes(False) b'\\x00' \>>> Web3.to\_bytes(True) b'\\x01' \>>> Web3.to\_bytes(hexstr\='0x000F') b'\\x00\\x0f' \>>> Web3.to\_bytes(hexstr\='000F') b'\\x00\\x0f' \>>> Web3.to\_bytes(text\='') b'' \>>> Web3.to\_bytes(text\='cowmö') b'cowm\\xc3\\xb6' Web3.to\_int(_primitive\=None_, _hexstr\=None_, _text\=None_)[](#web3.Web3.to_int "Link to this definition") Takes a variety of inputs and returns its integer equivalent. \>>> Web3.to\_int(0) 0 \>>> Web3.to\_int(0x000F) 15 \>>> Web3.to\_int(b'\\x00\\x0F') 15 \>>> Web3.to\_int(False) 0 \>>> Web3.to\_int(True) 1 \>>> Web3.to\_int(hexstr\='0x000F') 15 \>>> Web3.to\_int(hexstr\='000F') 15 Web3.to\_json(_obj_)[](#web3.Web3.to_json "Link to this definition") Takes a variety of inputs and returns its JSON equivalent. \>>> Web3.to\_json(3) '3' \>>> Web3.to\_json({'one': 1}) '{"one": 1}' [Currency Conversions](#id6) [](#currency-conversions "Link to this heading") ------------------------------------------------------------------------------- Web3.to\_wei(_value_, _currency_)[](#web3.Web3.to_wei "Link to this definition") Returns the value in the denomination specified by the `currency` argument converted to wei. \>>> Web3.to\_wei(1, 'ether') 1000000000000000000 Web3.from\_wei(_value_, _currency_)[](#web3.Web3.from_wei "Link to this definition") Returns the value in wei converted to the given currency. The value is returned as a `Decimal` to ensure precision down to the wei. \>>> Web3.from\_wei(1000000000000000000, 'ether') Decimal('1') [Addresses](#id7) [](#addresses "Link to this heading") --------------------------------------------------------- Web3.is\_address(_value_)[](#web3.Web3.is_address "Link to this definition") Returns `True` if the value is one of the recognized address formats. * Allows for both `0x` prefixed and non-prefixed values. * If the address contains mixed upper and lower cased characters this function also checks if the address checksum is valid according to [EIP55](https://github.com/ethereum/EIPs/issues/55) \>>> Web3.is\_address('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') True Web3.is\_checksum\_address(_value_)[](#web3.Web3.is_checksum_address "Link to this definition") Returns `True` if the value is a valid [EIP55](https://github.com/ethereum/EIPs/issues/55) checksummed address \>>> Web3.is\_checksum\_address('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') True \>>> Web3.is\_checksum\_address('0xd3cda913deb6f67967b99d67acdfa1712c293601') False Web3.to\_checksum\_address(_value_)[](#web3.Web3.to_checksum_address "Link to this definition") Returns the given address with an [EIP55](https://github.com/ethereum/EIPs/issues/55) checksum. \>>> Web3.to\_checksum\_address('0xd3cda913deb6f67967b99d67acdfa1712c293601') '0xd3CdA913deB6f67967B99D67aCDFa1712C293601' [Cryptographic Hashing](#id8) [](#cryptographic-hashing "Link to this heading") --------------------------------------------------------------------------------- _classmethod_ Web3.keccak(_primitive\=None_, _hexstr\=None_, _text\=None_)[](#web3.Web3.keccak "Link to this definition") Returns the Keccak-256 of the given value. Text is encoded to UTF-8 before computing the hash, just like Solidity. Any of the following are valid and equivalent: \>>> Web3.keccak(0x747874) \>>> Web3.keccak(b'\\x74\\x78\\x74') \>>> Web3.keccak(hexstr\='0x747874') \>>> Web3.keccak(hexstr\='747874') \>>> Web3.keccak(text\='txt') HexBytes('0xd7278090a36507640ea6b7a0034b69b0d240766fa3f98e3722be93c613b29d2e') _classmethod_ Web3.solidity\_keccak(_abi\_types_, _value_)[](#web3.Web3.solidity_keccak "Link to this definition") Returns the Keccak-256 as it would be computed by the solidity `keccak` function on a _packed_ ABI encoding of the `value` list contents. The `abi_types` argument should be a list of solidity type strings which correspond to each of the provided values. \>>> Web3.solidity\_keccak(\['bool'\], \[True\]) HexBytes("0x5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2") \>>> Web3.solidity\_keccak(\['uint8', 'uint8', 'uint8'\], \[97, 98, 99\]) HexBytes("0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45") \>>> Web3.solidity\_keccak(\['uint8\[\]'\], \[\[97, 98, 99\]\]) HexBytes("0x233002c671295529bcc50b76a2ef2b0de2dac2d93945fca745255de1a9e4017e") \>>> Web3.solidity\_keccak(\['address'\], \["0x49EdDD3769c0712032808D86597B84ac5c2F5614"\]) HexBytes("0x2ff37b5607484cd4eecf6d13292e22bd6e5401eaffcc07e279583bc742c68882") \>>> Web3.solidity\_keccak(\['address'\], \["ethereumfoundation.eth"\]) HexBytes("0x913c99ea930c78868f1535d34cd705ab85929b2eaaf70fcd09677ecd6e5d75e9") Comparable solidity usage: bytes32 data1 \= keccak256(abi.encodePacked(true)); assert(data1 \== hex"5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2"); bytes32 data2 \= keccak256(abi.encodePacked(uint8(97), uint8(98), uint8(99))); assert(data2 \== hex"4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45"); [Check Encodability](#id9) [](#check-encodability "Link to this heading") --------------------------------------------------------------------------- w3.is\_encodable(_\_type_, _value_)[](#web3.w3.is_encodable "Link to this definition") Returns `True` if a value can be encoded as the given type. Otherwise returns `False`. > \>>> from web3.auto.gethdev import w3 > \>>> w3.is\_encodable('bytes2', b'12') > True > \>>> w3.is\_encodable('bytes2', '0x1234') > True > \>>> w3.is\_encodable('bytes2', '1234') \# not 0x-prefixed, no assumptions will be made > False > \>>> w3.is\_encodable('bytes2', b'1') \# does not match specified bytes size > False > \>>> w3.is\_encodable('bytes2', b'123') \# does not match specified bytes size > False w3.strict\_bytes\_type\_checking[](#web3.w3.strict_bytes_type_checking "Link to this definition") Disable the stricter bytes type checking that is loaded by default. For more examples, see [Disabling Strict Checks for Bytes Types](web3.contract.html#disable-strict-byte-check) \>>> from web3.auto.gethdev import w3 \>>> w3.is\_encodable('bytes2', b'12') True \>>> \# not of exact size bytes2 \>>> w3.is\_encodable('bytes2', b'1') False \>>> w3.strict\_bytes\_type\_checking \= False \>>> \# zero-padded, so encoded to: b'1\\x00' \>>> w3.is\_encodable('bytes2', b'1') True \>>> \# re-enable it \>>> w3.strict\_bytes\_type\_checking \= True \>>> w3.is\_encodable('bytes2', b'1') False [RPC API Modules](#id10) [](#rpc-api-modules "Link to this heading") ---------------------------------------------------------------------- Each `Web3` instance also exposes these namespaced API modules. Web3.eth[](#web3.Web3.eth "Link to this definition") See [web3.eth API](web3.eth.html) Web3.geth[](#web3.Web3.geth "Link to this definition") See [Geth API](web3.geth.html) These internal modules inherit from the `web3.module.Module` class which give them some configurations internal to the web3.py library. [Custom Methods](#id11) [](#custom-methods "Link to this heading") -------------------------------------------------------------------- You may add or overwrite methods within any module using the `attach_methods` function. To create a property instead, set `is_property` to `True`. \>>> w3.eth.attach\_methods({ ... 'example\_method': Method( ... 'eth\_example', ... mungers\=\[...\], ... request\_formatters\=\[...\], ... result\_formatters\=\[...\], ... is\_property\=False, ... ), ... }) \>>> w3.eth.example\_method() [External Modules](#id12) [](#external-modules "Link to this heading") ------------------------------------------------------------------------ External modules can be used to introduce custom or third-party APIs to your `Web3` instance. External modules are simply classes whose methods and properties can be made available within the `Web3` instance. Optionally, the external module may make use of the parent `Web3` instance by accepting it as the first argument within the `__init__` function: \>>> class ExampleModule: ... def \_\_init\_\_(self, w3): ... self.w3 \= w3 ... ... def print\_balance\_of\_shaq(self): ... print(self.w3.eth.get\_balance('shaq.eth')) Warning Given the flexibility of external modules, use caution and only import modules from trusted third parties and open source code you’ve vetted! Configuring external modules can occur either at instantiation of the `Web3` instance or by making use of the `attach_modules()` method. To instantiate the `Web3` instance with external modules use the `external_modules` keyword argument: \>>> from web3 import Web3, HTTPProvider \>>> from external\_module\_library import ( ... ModuleClass1, ... ModuleClass2, ... ModuleClass3, ... ModuleClass4, ... ModuleClass5, ... ) \>>> w3 \= Web3( ... HTTPProvider(provider\_uri), ... external\_modules\={ ... 'module1': ModuleClass1, ... 'module2': (ModuleClass2, { ... 'submodule1': ModuleClass3, ... 'submodule2': (ModuleClass4, { ... 'submodule2a': ModuleClass5, \# submodule children may be nested further if necessary ... }) ... }) ... } ... ) \# \`return\_zero\`, in this case, is an example attribute of the \`ModuleClass1\` object \>>> w3.module1.return\_zero() 0 \>>> w3.module2.submodule1.return\_one() 1 \>>> w3.module2.submodule2.submodule2a.return\_two() 2 w3.attach\_modules(_modules_)[](#web3.w3.attach_modules "Link to this definition") The `attach_modules()` method can be used to attach external modules after the `Web3` instance has been instantiated. Modules are attached via a dict with module names as the keys. The values can either be the module classes themselves, if there are no submodules, or two-item tuples with the module class as the 0th index and a similarly built dict containing the submodule information as the 1st index. This pattern may be repeated as necessary. \>>> from web3 import Web3, HTTPProvider \>>> from external\_module\_library import ( ... ModuleClass1, ... ModuleClass2, ... ModuleClass3, ... ModuleClass4, ... ModuleClass5, ... ) \>>> w3 \= Web3(HTTPProvider(provider\_uri)) \>>> w3.attach\_modules({ ... 'module1': ModuleClass1, \# the module class itself may be used for a single module with no submodules ... 'module2': (ModuleClass2, { \# a tuple with module class and corresponding submodule dict may be used for modules with submodules ... 'submodule1': ModuleClass3, ... 'submodule2': (ModuleClass4, { \# this pattern may be repeated as necessary ... 'submodule2a': ModuleClass5, ... }) ... }) ... }) \>>> w3.module1.return\_zero() 0 \>>> w3.module2.submodule1.return\_one() 1 \>>> w3.module2.submodule2.submodule2a.return\_two() 2 --- # Release Notes — web3.py 7.6.1 documentation * [](index.html) * Release Notes * [View page source](_sources/release_notes.rst.txt) * * * Release Notes[](#release-notes "Link to this heading") ======================================================== v7 Breaking Changes Summary See the [v7 Migration Guide](migration.html#migrating-v6-to-v7) web3.py v7.6.1 (2024-12-18)[](#web3-py-v7-6-1-2024-12-18 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#bugfixes "Link to this heading") * Include an end-of-line delimiter when sending messages via IPC with the `IPCProvider` and `AsyncIPCProvider`. ([#3537](https://github.com/ethereum/web3.py/issues/3537) ) * Contract functions and events no longer initialize for each call. Retrieval of overloaded functions and events is now deterministic. Any ambiguity will result in an exception being raised. ([#3540](https://github.com/ethereum/web3.py/issues/3540) ) * Bump the eth-tester version to one that works in the tester dependency extras ([#3555](https://github.com/ethereum/web3.py/issues/3555) ) ### Improved Documentation[](#improved-documentation "Link to this heading") * Update ENS-related links ([#3563](https://github.com/ethereum/web3.py/issues/3563) ) ### Internal Changes - for web3.py Contributors[](#internal-changes-for-web3-py-contributors "Link to this heading") * Upgrade Geth Fixture to 1.14.12 ([#3533](https://github.com/ethereum/web3.py/issues/3533) ) * Delete `ARCHITECTURE.md` as unused ([#3547](https://github.com/ethereum/web3.py/issues/3547) ) ### Miscellaneous Changes[](#miscellaneous-changes "Link to this heading") * [#3525](https://github.com/ethereum/web3.py/issues/3525) web3.py v7.6.0 (2024-11-22)[](#web3-py-v7-6-0-2024-11-22 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id1 "Link to this heading") * Update the ContractEvents class to raise a NoABIFound exception if the Contract is initialized without an ABI and an attempt to access an event is made. This exception makes ContractEvents consistent with ContractFunctions. ([#3491](https://github.com/ethereum/web3.py/issues/3491) ) ### Features[](#features "Link to this heading") * Contracts with overloaded functions or events are now supported. The Contract initializes functions and events using an identifier to distinguish between them. The identifier is the function or event signature, which consists of the name and the parameter types. ([#3491](https://github.com/ethereum/web3.py/issues/3491) ) * * Support for `w3.eth.blob_base_fee` * Async support for `w3.eth.blob_base_fee` ([#3527](https://github.com/ethereum/web3.py/issues/3527) ) ### Internal Changes - for web3.py Contributors[](#id2 "Link to this heading") * Pin `websockets<14` due to breaking changes ([#3529](https://github.com/ethereum/web3.py/issues/3529) ) ### Miscellaneous Changes[](#id3 "Link to this heading") * [#3491](https://github.com/ethereum/web3.py/issues/3491) web3.py v7.5.0 (2024-11-06)[](#web3-py-v7-5-0-2024-11-06 "Link to this heading") ---------------------------------------------------------------------------------- ### Improved Documentation[](#id4 "Link to this heading") * Polish docs index page ([#3522](https://github.com/ethereum/web3.py/issues/3522) ) ### Features[](#id5 "Link to this heading") * Add support for Geth Debug traceTransaction. ([#3334](https://github.com/ethereum/web3.py/issues/3334) ) * New contract methods to obtain event elements from a contract ABI using a name, signature, selector, or topic. ([#3472](https://github.com/ethereum/web3.py/issues/3472) ) ### Internal Changes - for web3.py Contributors[](#id6 "Link to this heading") * Add python 3.13 support ([#3493](https://github.com/ethereum/web3.py/issues/3493) ) * Compile test contracts with newly released Solidity `v0.8.28` to ensure compatibility. ([#3515](https://github.com/ethereum/web3.py/issues/3515) ) web3.py v7.4.0 (2024-10-16)[](#web3-py-v7-4-0-2024-10-16 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id7 "Link to this heading") * Fix a bug where CCIP-Read expected a `{sender}` in the url for a POST request. If `{data}` is missing from the url, assume a POST request is being made regardless of whether `{sender}` is present. ([#3291](https://github.com/ethereum/web3.py/issues/3291) ) * Fix a bug where non-mainnet chains could not cache requests based on missing `finalized` block number. ([#3508](https://github.com/ethereum/web3.py/issues/3508) ) * Send `json`, not `data` with CCIP-Read POST requests. ([#3512](https://github.com/ethereum/web3.py/issues/3512) ) ### Improved Documentation[](#id8 "Link to this heading") * Update the request caching documentation to clarify on when to reach for request caching and how to configure the request validation threshold for certain endpoints. ([#3508](https://github.com/ethereum/web3.py/issues/3508) ) ### Features[](#id9 "Link to this heading") * Allow a time interval, in seconds, to be used as the `request_cache_validation_threshold` for request caching. Keep a list of internal default values based on the chain id for some of the bigger chains. ([#3508](https://github.com/ethereum/web3.py/issues/3508) ) web3.py v7.3.1 (2024-10-14)[](#web3-py-v7-3-1-2024-10-14 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id10 "Link to this heading") * Properly wrap `AsyncBeacon.request_timeout` float in a `aiohttp.ClientTimeout` when making requests. ([#3503](https://github.com/ethereum/web3.py/issues/3503) ) * Changes related to an eth-typing bugfix, input types for `ABIEvent`: `ABIComponent` -> `ABIComponentIndexed`. ([#3510](https://github.com/ethereum/web3.py/issues/3510) ) ### Improved Documentation[](#id11 "Link to this heading") * Fix `EthereumTesterProvider` signature in docs, added an `eth_tester` example. ([#3500](https://github.com/ethereum/web3.py/issues/3500) ) * Fix pip install -e “.\[dev\]” command in linux README. ([#3505](https://github.com/ethereum/web3.py/issues/3505) ) ### Internal Changes - for web3.py Contributors[](#id12 "Link to this heading") * Update the ENSIP-15 to the latest spec and update the test suite. ([#3501](https://github.com/ethereum/web3.py/issues/3501) ) web3.py v7.3.0 (2024-09-25)[](#web3-py-v7-3-0-2024-09-25 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id13 "Link to this heading") * Base default `maxFeePerGas` calculation off of existing `maxPriorityFeePerGas` key instead of separate RPC call ([#3052](https://github.com/ethereum/web3.py/issues/3052) ) * Add back dependency extra for ‘tester’. ([#3480](https://github.com/ethereum/web3.py/issues/3480) ) * Fix a bug where sensitive requests that make use of block data should not be cached until some validation threshold deems it is safe to do so, when request caching is turned on. ([#3483](https://github.com/ethereum/web3.py/issues/3483) ) ### Improved Documentation[](#id14 "Link to this heading") * Update `contract.encode_abi` signature in docs and migration guide ([#3473](https://github.com/ethereum/web3.py/issues/3473) ) * Update documentation around `SignAndSendRawMiddlewareBuilder` injection into the middleware onion. It should be injected lower in the stack than any middleware that modifies the transaction, in order to ensure those modified fields are signed. ([#3488](https://github.com/ethereum/web3.py/issues/3488) ) * Docs cleanups related to `test` vs `tester` install extras. ([#3496](https://github.com/ethereum/web3.py/issues/3496) ) ### Features[](#id15 "Link to this heading") * Add a configuration for request caching that sets a threshold for validating cached requests that make use of block data. This can be turned off altogether by setting the threshold to `None`. ([#3483](https://github.com/ethereum/web3.py/issues/3483) ) * Add a configuration option for the `read_buffer_limit` for `AsyncIPCProvider` in order to control the expected message size limit (defaults to 20MB). Add `ReadBufferLimitReached` for when the read limit is reached, extend from `PersistentConnectionError`. ([#3492](https://github.com/ethereum/web3.py/issues/3492) ) ### Internal Changes - for web3.py Contributors[](#id16 "Link to this heading") * Test warning cleanup ([#3468](https://github.com/ethereum/web3.py/issues/3468) ) * Re-compile test contracts with recently released Solidity `v0.8.27`. ([#3475](https://github.com/ethereum/web3.py/issues/3475) ) * Re-organize the install extras. Re-define the `test` extra to always include the `tester` extra since it’s needed for testing. ([#3495](https://github.com/ethereum/web3.py/issues/3495) ) ### Miscellaneous Changes[](#id17 "Link to this heading") * [#3490](https://github.com/ethereum/web3.py/issues/3490) ### Performance Improvements[](#performance-improvements "Link to this heading") * Improve logic for reading from the async IPC socket in order to properly handle and adjust the handling of large messages. This improves reading speeds in general. ([#3492](https://github.com/ethereum/web3.py/issues/3492) ) web3.py v7.2.0 (2024-08-29)[](#web3-py-v7-2-0-2024-08-29 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id18 "Link to this heading") * Fix a bug with newer `hexbytes` versions that yield non-0x-prefixed hex for `HexBytes`: `raw_transaction.hex()` -> `raw_transaction.to_0x_hex()`. ([#3471](https://github.com/ethereum/web3.py/issues/3471) ) ### Features[](#id19 "Link to this heading") * HTTPProvider and AsyncHTTPProvider’s get\_request\_headers is now available on both the class and the instance ([#3467](https://github.com/ethereum/web3.py/issues/3467) ) web3.py v7.1.0 (2024-08-28)[](#web3-py-v7-1-0-2024-08-28 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id20 "Link to this heading") * Specify a unique `__hash__()` for unhashable `Web3Middleware` types and use this hash as the middleware onion key when a name is not provided for the middleware. This fixes a bug where different middleware were given the same name and therefore raised errors. ([#3463](https://github.com/ethereum/web3.py/issues/3463) ) ### Improved Documentation[](#id21 "Link to this heading") * Fix bug in filters example code ([#3455](https://github.com/ethereum/web3.py/issues/3455) ) * Update `v6` -> `v7` migration guide with examples for importing and adding middleware, as well as examples on how to use the `MiddlewareBuilder` classes. ([#3462](https://github.com/ethereum/web3.py/issues/3462) ) ### Features[](#id22 "Link to this heading") * Add sync and async support for beacon `/eth/v1/beacon/blob_sidecars` endpoint. ([#3407](https://github.com/ethereum/web3.py/issues/3407) ) * Allow user to call ContractFunctions without parentheses ([#3444](https://github.com/ethereum/web3.py/issues/3444) ) ### Internal Changes - for web3.py Contributors[](#id23 "Link to this heading") * Refactor and DRY up CI run setup and reduce surface area for errors. Include pre-releases in CI runs for internally maintained libraries to try and catch any conflicts. ([#3452](https://github.com/ethereum/web3.py/issues/3452) ) * Bump py-geth to `>=5.0.0` from `>=5.0.0b1` now that stable has been released. This only matters for the `test` install extra (CI and dev purposes). ([#3458](https://github.com/ethereum/web3.py/issues/3458) ) web3.py v7.0.0 (2024-08-21)[](#web3-py-v7-0-0-2024-08-21 "Link to this heading") ---------------------------------------------------------------------------------- ### Breaking Changes[](#breaking-changes "Link to this heading") * Update eth-utils and eth-typing to latest major versions eth-utils v5 and eth-typing v5 ([#3450](https://github.com/ethereum/web3.py/issues/3450) ) ### Improved Documentation[](#id24 "Link to this heading") * Improve batch request documentation. ([#3448](https://github.com/ethereum/web3.py/issues/3448) ) ### Internal Changes - for web3.py Contributors[](#id25 "Link to this heading") * Fix Release Notes formatting ([#3454](https://github.com/ethereum/web3.py/issues/3454) ) web3.py v7.0.0-beta.9 (2024-08-01)[](#web3-py-v7-0-0-beta-9-2024-08-01 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Breaking Changes[](#id26 "Link to this heading") * Upgrades to use latest `ABI` utilities and typings from `eth-utils` and `eth-typing`. * Typings for `ABI` components are now available in the `eth-typing` package. `ABI` types previously in `web3.types` have been removed. * New versions of existing ABI functions were added to `eth-utils` and are now exposed in web3.py via `web3.utils.abi`. * ABI exceptions have been renamed in `web3.exceptions`. The `ABIEventFunctionNotFound` and `FallbackNotFound` exceptions have been removed. Use `ABIEventNotFound` and `ABIFallbackNotFound` instead. * `MismatchedABI` exceptions are raised instead of a `Web3ValidationError` for ABI related errors. * `encode_abi` arguments have been updated to use `abi_element_name` instead of `fn_name`. ([#3408](https://github.com/ethereum/web3.py/issues/3408) ) * Remove `Web3ValidationError` dependence / inheritance from eth-utils `ValidationError`. ([#3443](https://github.com/ethereum/web3.py/issues/3443) ) ### Improved Documentation[](#id27 "Link to this heading") * Use autodoc and update ABI functions with docstrings and doctests. ([#3408](https://github.com/ethereum/web3.py/issues/3408) ) ### Features[](#id28 "Link to this heading") * Utilities to extract function and event `ABI` attributes from a contract. Utilities in the `web3.utils.abi` module parse ABI elements and check encodability of provided arguments. ABI functions in `eth-utils` are exposed by the `web3.utils.abi` module. * `get_abi_element_info` returns an `ABIElementInfo` TypedDict with the `abi`, `selector`, and `arguments`. * `get_abi_element` returns the `ABI` of a function, event, or error given the name and arguments. * `check_if_arguments_can_be_encoded` returns true if the arguments can be encoded with the given ABI. * `get_event_abi` returns the `ABI` of an event given the name. * `get_event_log_topics` returns the log topics of an event given the name. * `log_topics_to_bytes` returns the log topics as bytes. ([#3408](https://github.com/ethereum/web3.py/issues/3408) ) * Add explicit stream kwarg to HTTPProvider so that timeout can be more finely tuned. ([#3428](https://github.com/ethereum/web3.py/issues/3428) ) * Implement a `RequestTimedOut` exception, extending from `Web3RPCError`, for when requests to the node time out. ([#3440](https://github.com/ethereum/web3.py/issues/3440) ) ### Internal Changes - for web3.py Contributors[](#id29 "Link to this heading") * Run `mypy` locally using `pre-commit` hook, instead of within `pre-commit` container ([#3414](https://github.com/ethereum/web3.py/issues/3414) ) * Mitigate inconsistently failing tests for CI runs with appropriate `flaky` or `pytest.mark.xfail()` decorators. ([#3440](https://github.com/ethereum/web3.py/issues/3440) ) ### Miscellaneous Changes[](#id30 "Link to this heading") * [#3408](https://github.com/ethereum/web3.py/issues/3408) , [#3445](https://github.com/ethereum/web3.py/issues/3445) web3.py v7.0.0-beta.8 (2024-07-24)[](#web3-py-v7-0-0-beta-8-2024-07-24 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Breaking Changes[](#id31 "Link to this heading") * Refactor the public `socket` api for persistent connection providers to properly define `send()`, `recv()`, and `make_request()` (send and wait for response) methods for interacting with the open socket. ([#3433](https://github.com/ethereum/web3.py/issues/3433) ) * Format entries in `accessList` `storageKeys` to be `HexStr` instead of `HexBytes` ([#3434](https://github.com/ethereum/web3.py/issues/3434) ) ### Bugfixes[](#id32 "Link to this heading") * Handle `ConnectionClosedOK` case for `WebSocketProvider`. If a persistent connection is closed gracefully, log and raise a silent `PersistentConnectionClosedOK` exception, triggering an end to the message listener task and breaking out of the `process_subscriptions()` iterator. ([#3432](https://github.com/ethereum/web3.py/issues/3432) ) ### Features[](#id33 "Link to this heading") * Add `popitem()` functionality to the `SimpleCache` class as well as an async utility method to wait for the next item, `async_await_and_popitem()`. ([#3433](https://github.com/ethereum/web3.py/issues/3433) ) ### Internal Changes - for web3.py Contributors[](#id34 "Link to this heading") * Refactor some common logic for persistent connection providers back into the base `PersistentConnectionProvider` class to reduce code duplication and improve maintainability. ([#3433](https://github.com/ethereum/web3.py/issues/3433) ) web3.py v7.0.0-beta.7 (2024-06-26)[](#web3-py-v7-0-0-beta-7-2024-06-26 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Bugfixes[](#id35 "Link to this heading") * Change the `exception_retry_configuration` typing on http providers to be an `Optional`, as setting this property to `None` effectively turns off retries on exceptions for requests. ([#3412](https://github.com/ethereum/web3.py/issues/3412) ) * A bugfix, pre-release, to update the `Beacon` APIs (sync and async) to properly use the new `HTTPSessionManager`. ([#3421](https://github.com/ethereum/web3.py/issues/3421) ) ### Improved Documentation[](#id36 "Link to this heading") * Add an `eth_subscribe` example to the events guide ([#3403](https://github.com/ethereum/web3.py/issues/3403) ) ### Features[](#id37 "Link to this heading") * Properly handle `InsufficientDataBytes` errors when processing receipts ([#3388](https://github.com/ethereum/web3.py/issues/3388) ) * Provide explicit `__all__` exports for providers in web3/providers/\_\_init\_\_.py; update web3/\_\_init\_\_.py to include all provider classes including base classes. ([#3409](https://github.com/ethereum/web3.py/issues/3409) ) ### Internal Changes - for web3.py Contributors[](#id38 "Link to this heading") * Re-compile test contracts with Solidity v0.8.25 to ensure compatibility. ([#3307](https://github.com/ethereum/web3.py/issues/3307) ) * Increase allowable range of eth-tester: 0.11.x and 0.12.x ([#3400](https://github.com/ethereum/web3.py/issues/3400) ) * Remove uses of signHash in tests, require eth-account >=0.13.0 in doctests ([#3404](https://github.com/ethereum/web3.py/issues/3404) ) * Use a `HTTPSessionManager` to manage sessions for http providers, rather than have them share a single session manager / cache. ([#3412](https://github.com/ethereum/web3.py/issues/3412) ) web3.py v7.0.0-beta.6 (2024-05-15)[](#web3-py-v7-0-0-beta-6-2024-05-15 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Bugfixes[](#id39 "Link to this heading") * Properly propagate exceptions from the message listener task to the main loop for persistent connection providers. ([#3378](https://github.com/ethereum/web3.py/issues/3378) ) ### Improved Documentation[](#id40 "Link to this heading") * Prunes the node onboarding text ([#3371](https://github.com/ethereum/web3.py/issues/3371) ) * Stale example cleanup ([#3374](https://github.com/ethereum/web3.py/issues/3374) ) * Merge migration guides into one page ([#3379](https://github.com/ethereum/web3.py/issues/3379) ) * Simplify titles of docs guides ([#3381](https://github.com/ethereum/web3.py/issues/3381) ) * Move ABI Types guide into the Troubleshooting page ([#3382](https://github.com/ethereum/web3.py/issues/3382) ) * Distribute examples into relevant guides and delete Example page ([#3383](https://github.com/ethereum/web3.py/issues/3383) ) * Add subscribe/unsubscribe API ([#3386](https://github.com/ethereum/web3.py/issues/3386) ) * Introduces batch request API ([#3393](https://github.com/ethereum/web3.py/issues/3393) ) ### Features[](#id41 "Link to this heading") * Add support for request batching via `w3.batch_requests()` context manager (sync and async). ([#3370](https://github.com/ethereum/web3.py/issues/3370) ) * Allow request cache configuration on provider `__init__()` for all provider classes. ([#3395](https://github.com/ethereum/web3.py/issues/3395) ) ### Internal Changes - for web3.py Contributors[](#id42 "Link to this heading") * Merge the python project template, notably adding python 3.12 support ([#3363](https://github.com/ethereum/web3.py/issues/3363) ) * Increase python-asyncio dependency to be >=0.21.2,<0.23 ([#3369](https://github.com/ethereum/web3.py/issues/3369) ) * Bump to `mypy==1.10.0` for `pre-commit` ([#3377](https://github.com/ethereum/web3.py/issues/3377) ) * Move signed.rawTransaction -> signed.raw\_transaction in eth module tests ([#3380](https://github.com/ethereum/web3.py/issues/3380) ) web3.py v7.0.0-beta.5 (2024-04-26)[](#web3-py-v7-0-0-beta-5-2024-04-26 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Breaking Changes[](#id43 "Link to this heading") * Snake-case remaining arguments `fromBlock`, `toBlock`, and `blockHash` in contract and filter methods where they are passed in as kwargs. ([#3353](https://github.com/ethereum/web3.py/issues/3353) ) * Employ an exponential backoff strategy using the `backoff_factor` in `ExceptionRetryConfiguration` for `HTTPProvider` and `AsyncHTTPProvider`. Reduce the default initial delay to `0.125` seconds. ([#3358](https://github.com/ethereum/web3.py/issues/3358) ) * Validate JSON-RPC responses more strictly against the JSON-RPC 2.0 specifications. `BlockNumberOutofRange` -> `BlockNumberOutOfRange`. ([#3359](https://github.com/ethereum/web3.py/issues/3359) ) ### Deprecations[](#deprecations "Link to this heading") * `messageHash` and `rawTransaction` from `eth-account` have been deprecated for snake\_case versions ([#3348](https://github.com/ethereum/web3.py/issues/3348) ) ### Features[](#id44 "Link to this heading") * Raise `Web3RPCError` on JSON-RPC errors rather than `Web3ValueError`. Raise `MethodNotSupported` exception when a method is not supported within _web3.py_; keep `MethodUnavailable` for when a method is not available on the current provider (JSON-RPC error). ([#3359](https://github.com/ethereum/web3.py/issues/3359) ) ### Internal Changes - for web3.py Contributors[](#id45 "Link to this heading") * Bump `eth-account` dependency to `>=0.12.2` ([#3348](https://github.com/ethereum/web3.py/issues/3348) ) ### Removals[](#removals "Link to this heading") * Remove the deprecated `personal` namespace and all references to it. ([#3350](https://github.com/ethereum/web3.py/issues/3350) ) web3.py v7.0.0-beta.4 (2024-04-11)[](#web3-py-v7-0-0-beta-4-2024-04-11 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Bugfixes[](#id46 "Link to this heading") * Fix misused call to endpoint\_uri for all cases of `PersistentConnectionProvider` by being able to retrieve either the `ipc_path` or the `endpoint_uri` from the base class with `endpoint_uri_or_ipc_path` property. ([#3319](https://github.com/ethereum/web3.py/issues/3319) ) ### Improved Documentation[](#id47 "Link to this heading") * Fix `eth_createAccessList` docs to reflect the correct behavior. ([#3327](https://github.com/ethereum/web3.py/issues/3327) ) ### Features[](#id48 "Link to this heading") * Use in-house exception wrappers for common Python exceptions, such as `ValueError`, `TypeError`, `AttributeError`, and `AssertionError`, for better control over exception handling. ([#3300](https://github.com/ethereum/web3.py/issues/3300) ) * Add request formatter for `maxFeePerBlobGas` when sending blob transactions. Add formatters for `blobGasPrice` and `blobGasUsed` for _eth\_getTransactionReceipt_. ([#3322](https://github.com/ethereum/web3.py/issues/3322) ) * Add formatters to ensure that the result of a `eth_createAccessList` response can be plugged directly into an `accessList` in a transaction. ([#3327](https://github.com/ethereum/web3.py/issues/3327) ) * Add Cancun support to `EthereumTesterProvider`; update Cancun-related fields in some internal types. ([#3332](https://github.com/ethereum/web3.py/issues/3332) ) ### Internal Changes - for web3.py Contributors[](#id49 "Link to this heading") * Use `pre-commit` for linting, run updated lint tools and fix errors ([#3297](https://github.com/ethereum/web3.py/issues/3297) ) * Dependency updates: `eth-abi>=5.0.1`, `eth-account>=0.12.0` `eth-typing>=4.0.0` and `hexbytes>=1.2.0` with relevant changes to support these. ([#3298](https://github.com/ethereum/web3.py/issues/3298) ) * Remove code conditionally necessary for `python<=3.7` ([#3317](https://github.com/ethereum/web3.py/issues/3317) ) web3.py v7.0.0-beta.3 (2024-03-28)[](#web3-py-v7-0-0-beta-3-2024-03-28 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Bugfixes[](#id50 "Link to this heading") * Fix `process_log()` when parsing logs for events with indexed and non-indexed inputs. `get_event_data()` now compares log topics and event ABIs as hex values. ([#3289](https://github.com/ethereum/web3.py/issues/3289) ) * Fix `process_log` for `HexStr` inputs. Explicit type coercion of entry `topics` and `data` values. ([#3293](https://github.com/ethereum/web3.py/issues/3293) ) * Fix typing for json data argument to `eth_signTypedData`. ([#3308](https://github.com/ethereum/web3.py/issues/3308) ) ### Improved Documentation[](#id51 "Link to this heading") * Add note about middlewares change to v7 migration guide. ([#3277](https://github.com/ethereum/web3.py/issues/3277) ) * Rearrange v7 migration guide and include upgrade path from WebsocketProviderV2 ([#3310](https://github.com/ethereum/web3.py/issues/3310) ) ### Features[](#id52 "Link to this heading") * Add support for `eth_getRawTransactionByHash` RPC method ([#3247](https://github.com/ethereum/web3.py/issues/3247) ) * Add `user_message` kwarg for human readable `Web3Exception` messages. ([#3263](https://github.com/ethereum/web3.py/issues/3263) ) * Add formatters for type 3 transaction fields `maxFeePerBlobGas` and `blobVersionedHashes`. ([#3314](https://github.com/ethereum/web3.py/issues/3314) ) ### Internal Changes - for web3.py Contributors[](#id53 "Link to this heading") * Add a daily CI run ([#3272](https://github.com/ethereum/web3.py/issues/3272) ) * Add linting for non-inclusive language with `blocklint`. ([#3275](https://github.com/ethereum/web3.py/issues/3275) ) ### Miscellaneous Changes[](#id54 "Link to this heading") * [#3304](https://github.com/ethereum/web3.py/issues/3304) ### Performance Improvements[](#id55 "Link to this heading") * Importing `ens._normalization` is deferred until the first call of `ens.utils.normalize_name` in order to speed up `import web3`. ([#3285](https://github.com/ethereum/web3.py/issues/3285) ) * Utilize `async` functionality when popping responses from request manager cache for persistent connection providers. ([#3306](https://github.com/ethereum/web3.py/issues/3306) ) ### Removals[](#id56 "Link to this heading") * Remove `Contract.encodeABI()` in favor of `Contract.encode_abi()` to follow standard conventions. ([#3281](https://github.com/ethereum/web3.py/issues/3281) ) web3.py v7.0.0-beta.2 (2024-03-11)[](#web3-py-v7-0-0-beta-2-2024-03-11 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Breaking Changes[](#id57 "Link to this heading") * Move `middlewares` -> `middleware` ([#3276](https://github.com/ethereum/web3.py/issues/3276) ) ### Bugfixes[](#id58 "Link to this heading") * Fix/update methods and decorators in `web3/_utils/abi.py` to address issues raised by `mypy` ([#3269](https://github.com/ethereum/web3.py/issues/3269) ) * Catch all types of `eth-abi` `DecodingError` in `EthereumTesterProvider->_make_request()` ([#3271](https://github.com/ethereum/web3.py/issues/3271) ) ### Improved Documentation[](#id59 "Link to this heading") * Remove annual user survey prompt from docs ([#3218](https://github.com/ethereum/web3.py/issues/3218) ) * Introduce feedback form banner prompt on docs ([#3253](https://github.com/ethereum/web3.py/issues/3253) ) * Refresh of the middleware docs ([#3266](https://github.com/ethereum/web3.py/issues/3266) ) ### Miscellaneous Changes[](#id60 "Link to this heading") * [#3259](https://github.com/ethereum/web3.py/issues/3259) , [#3262](https://github.com/ethereum/web3.py/issues/3262) ### Removals[](#id61 "Link to this heading") * Remove the `ethpm` module and related docs, tests, and dependencies ([#3261](https://github.com/ethereum/web3.py/issues/3261) ) web3.py v7.0.0-beta.1 (2024-02-28)[](#web3-py-v7-0-0-beta-1-2024-02-28 "Link to this heading") ------------------------------------------------------------------------------------------------ ### Breaking Changes[](#id62 "Link to this heading") * Refactor the middleware setup so that request processors and response processors are separated. This will allow for more flexibility in the future and aid in the implementation of features such as batched requests. This PR also closes out a few outstanding issues and will be the start of the breaking changes for web3.py `v7`. Review PR for a full list of changes. ([#3169](https://github.com/ethereum/web3.py/issues/3169) ) * Use a message listener background task for `WebsocketProviderV2` rather than relying on `ws.recv()` blocking. Some breaking changes to API, notably `listen_to_websocket` -> `process_subscriptions`. ([#3179](https://github.com/ethereum/web3.py/issues/3179) ) * Drop dependency on `lru-dict` library. ([#3196](https://github.com/ethereum/web3.py/issues/3196) ) * Drop support for python 3.7 ([#3198](https://github.com/ethereum/web3.py/issues/3198) ) * Return iterable of `ABIFunction``s from the ``BaseContractFunctions` iterator. ([#3200](https://github.com/ethereum/web3.py/issues/3200) ) * Name changes internal to the library related to `v7`: `WebsocketProvider` -> `LegacyWebSocketProvider`, `WebsocketProviderV2` -> `WebSocketProvider` ([#3225](https://github.com/ethereum/web3.py/issues/3225) ) * `CallOverride` type change to `StateOverride` to reflect better the type name for the state override. `eth_call` is also not the only method with this param, making the name more generic. ([#3227](https://github.com/ethereum/web3.py/issues/3227) ) * Rename beacon/main.py -> beacon/beacon.py ([#3233](https://github.com/ethereum/web3.py/issues/3233) ) * `EthereumTesterProvider` now returns `input` for eth\_getTransaction\* for better consistency with JSON-RPC spec. ([#3235](https://github.com/ethereum/web3.py/issues/3235) ) * Change the signature for the async version of `wait_for_transaction_receipt()` to use `Optional[float]` instead of `float`. ([#3237](https://github.com/ethereum/web3.py/issues/3237) ) * `get_default_ipc_path()` and `get_dev_ipc_path()` now return the path value without checking if the `geth.ipc` file exists. ([#3245](https://github.com/ethereum/web3.py/issues/3245) ) ### Bugfixes[](#id63 "Link to this heading") * Fix return type of `AsyncContract.constructor` ([#3192](https://github.com/ethereum/web3.py/issues/3192) ) * Handle new geth errors related to waiting for a transaction receipt while transactions are still being indexed. ([#3216](https://github.com/ethereum/web3.py/issues/3216) ) ### Improved Documentation[](#id64 "Link to this heading") * Documentation was updated to reflect early changes to `v7` from `v6`. A `v6` -> `v7` migration guide was also started and will be added to as `v7` breaking changes are introduced. ([#3211](https://github.com/ethereum/web3.py/issues/3211) ) * Remove ENS v6 breaking change warning from v7 ([#3254](https://github.com/ethereum/web3.py/issues/3254) ) ### Features[](#id65 "Link to this heading") * Add AsyncIPCProvider ([#2984](https://github.com/ethereum/web3.py/issues/2984) ) * Implement `state_override` parameter for `eth_estimateGas` method. ([#3164](https://github.com/ethereum/web3.py/issues/3164) ) * Upgrade eth-tester to `v0.10.0-b.1` and turn on `eth_feeHistory` support for `EthereumTesterProvider`. ([#3172](https://github.com/ethereum/web3.py/issues/3172) ) * Add formatters for new `Cancun` network upgrade block header fields: `blobGasUsed`, `excessBlobGas`, and `parentBeaconBlockRoot`. ([#3223](https://github.com/ethereum/web3.py/issues/3223) ) * Contract event `get_logs` results sorted by each `ContractEvent` `logIndex`. ([#3228](https://github.com/ethereum/web3.py/issues/3228) ) ### Internal Changes - for web3.py Contributors[](#id66 "Link to this heading") * Create test fixture for latest `geth` version. Run tests with `geth` in `--dev` mode. ([#3191](https://github.com/ethereum/web3.py/issues/3191) ) * Validate geth version used to generate the integration test fixture against the version in the binary that is used to run the tests. ([#3193](https://github.com/ethereum/web3.py/issues/3193) ) * Internal change to `WebsocketProviderV2` before release: raise exceptions in message listener task by default; opting to silence them via a flag. ([#3202](https://github.com/ethereum/web3.py/issues/3202) ) * Compile contracts with and test against new Solidity version `v0.8.24`. ([#3204](https://github.com/ethereum/web3.py/issues/3204) ) * Formatting updates for `black==24.1.0`. ([#3207](https://github.com/ethereum/web3.py/issues/3207) ) * Allow HTTP provider request retry configuration to be turned off appropriately. Internal change since `v7` has not yet been released. ([#3211](https://github.com/ethereum/web3.py/issues/3211) ) * Upgraded geth fixture version ([#3231](https://github.com/ethereum/web3.py/issues/3231) ) ### Miscellaneous Changes[](#id67 "Link to this heading") * [#2964](https://github.com/ethereum/web3.py/issues/2964) , [#3248](https://github.com/ethereum/web3.py/issues/3248) ### Performance Improvements[](#id68 "Link to this heading") * Remove call to `parse_block_identifier` when initializing `ContractCaller` functions. ([#3257](https://github.com/ethereum/web3.py/issues/3257) ) ### Removals[](#id69 "Link to this heading") * `normalize_request_parameters` middleware was in a stale state and not being used or tested. This middleware has been removed. ([#3211](https://github.com/ethereum/web3.py/issues/3211) ) * Remove deprecated `geth.miner` namespace and methods. ([#3236](https://github.com/ethereum/web3.py/issues/3236) ) web3.py v6.14.0 (2024-01-10)[](#web3-py-v6-14-0-2024-01-10 "Link to this heading") ------------------------------------------------------------------------------------ ### Bugfixes[](#id70 "Link to this heading") * Change `fee_history` default behavior. If `reward_percentiles` arg not included, pass it to the provider as an empty list instead of `None`. ([#3185](https://github.com/ethereum/web3.py/issues/3185) ) * Use `importlib.metadata` for version info if python>=3.8 ([#3187](https://github.com/ethereum/web3.py/issues/3187) ) ### Improved Documentation[](#id71 "Link to this heading") * Remove docs reference for removed `protocol_version` RPC method ([#3183](https://github.com/ethereum/web3.py/issues/3183) ) ### Internal Changes - for web3.py Contributors[](#id72 "Link to this heading") * Re-define how async vs sync core test suites are ran. ([#3180](https://github.com/ethereum/web3.py/issues/3180) ) * Add basic import and version tests for the `web3` module ([#3187](https://github.com/ethereum/web3.py/issues/3187) ) web3.py v6.13.0 (2023-12-20)[](#web3-py-v6-13-0-2023-12-20 "Link to this heading") ------------------------------------------------------------------------------------ ### Features[](#id73 "Link to this heading") * Implement async `eth_createAccessList` RPC method to create an EIP-2930 access list. ([#3167](https://github.com/ethereum/web3.py/issues/3167) ) ### Internal Changes - for web3.py Contributors[](#id74 "Link to this heading") * Add flaky async Geth integration tests to CI ([#3170](https://github.com/ethereum/web3.py/issues/3170) ) * Fix wrong test reference for `EthereumTesterProvider` integration test suite. ([#3171](https://github.com/ethereum/web3.py/issues/3171) ) * Small fix for integration tests for `tox` to recognize independent patterns for each test run. ([#3173](https://github.com/ethereum/web3.py/issues/3173) ) web3.py v6.12.0 (2023-12-11)[](#web3-py-v6-12-0-2023-12-11 "Link to this heading") ------------------------------------------------------------------------------------ ### Improved Documentation[](#id75 "Link to this heading") * Make downloadable versions of docs available in `pdf`, `htmlzip`, and `epub` formats ([#3153](https://github.com/ethereum/web3.py/issues/3153) ) * Add 2023 user survey fine art banner in the docs ([#3159](https://github.com/ethereum/web3.py/issues/3159) ) * Polish the community resources docs page ([#3162](https://github.com/ethereum/web3.py/issues/3162) ) ### Features[](#id76 "Link to this heading") * Implement `createAccessList` RPC endpoint to create an EIP-2930 access list. ([#2381](https://github.com/ethereum/web3.py/issues/2381) ) ### Internal Changes - for web3.py Contributors[](#id77 "Link to this heading") * Run flaky eth-tester tests on CI ([#3157](https://github.com/ethereum/web3.py/issues/3157) ) * Pin `pytest-asyncio` dependency to <0.23 ([#3160](https://github.com/ethereum/web3.py/issues/3160) ) web3.py v6.11.4 (2023-11-27)[](#web3-py-v6-11-4-2023-11-27 "Link to this heading") ------------------------------------------------------------------------------------ ### Bugfixes[](#id78 "Link to this heading") * Fix collision of `w3` variable when initializing contract with function of the same name ([#3147](https://github.com/ethereum/web3.py/issues/3147) ) ### Miscellaneous Changes[](#id79 "Link to this heading") * [#3148](https://github.com/ethereum/web3.py/issues/3148) web3.py v6.11.3 (2023-11-08)[](#web3-py-v6-11-3-2023-11-08 "Link to this heading") ------------------------------------------------------------------------------------ ### Bugfixes[](#id80 "Link to this heading") * When coming back through the middleware onion after a request is made, we have the response `id`. Use it to match to the cached request information and process the response accordingly. ([#3140](https://github.com/ethereum/web3.py/issues/3140) ) ### Improved Documentation[](#id81 "Link to this heading") * Adds Discord bot template repo to Resources page ([#3143](https://github.com/ethereum/web3.py/issues/3143) ) ### Internal Changes - for web3.py Contributors[](#id82 "Link to this heading") * Additional contract `abi` documentation to make it a clear requirement for contract instances. ([#2539](https://github.com/ethereum/web3.py/issues/2539) ) * Fix type annotations for `web3` constants. ([#3138](https://github.com/ethereum/web3.py/issues/3138) ) * Add upper pin to deprecated dependency `lru-dict` whose new minor version release introduced a typing issue with CI lint builds. ([#3144](https://github.com/ethereum/web3.py/issues/3144) ) * Recompile test contracts with new Solidity version `v0.8.23` to ensure compatibility. ([#3146](https://github.com/ethereum/web3.py/issues/3146) ) web3.py v6.11.2 (2023-10-30)[](#web3-py-v6-11-2-2023-10-30 "Link to this heading") ------------------------------------------------------------------------------------ ### Improved Documentation[](#id83 "Link to this heading") * Fix formatting in documentation for creating an account. ([#3128](https://github.com/ethereum/web3.py/issues/3128) ) * Fix broken links for Apeworx and Sepolia faucet ([#3130](https://github.com/ethereum/web3.py/issues/3130) ) ### Internal Changes - for web3.py Contributors[](#id84 "Link to this heading") * Speed up the core test suite by splitting up sync and async tests. This reduces the CI build times to ~8min from ~12min. ([#3111](https://github.com/ethereum/web3.py/issues/3111) ) * Re-compile test contracts with Solidity `v0.8.22` to ensure compatibility with this latest Solidity version. ([#3134](https://github.com/ethereum/web3.py/issues/3134) ) * Improvements on yielding to the event loop while searching in response caches and calling `recv()` on the websocket connection for `WebSocketProviderV2`. ([#3135](https://github.com/ethereum/web3.py/issues/3135) ) web3.py v6.11.1 (2023-10-18)[](#web3-py-v6-11-1-2023-10-18 "Link to this heading") ------------------------------------------------------------------------------------ ### Improved Documentation[](#id85 "Link to this heading") * Update `WebsocketProviderV2` documentation. Document a general overview of the `RequestProcessor` class and its internal caches. ([#3125](https://github.com/ethereum/web3.py/issues/3125) ) ### Features[](#id86 "Link to this heading") * Properly define an `__await__()` method on the `_PersistentConnectionWeb3` class so a persistent connection may be initialized using the `await` pattern. Integration tests added for initializing the persistent connection using the `await` pattern. ([#3125](https://github.com/ethereum/web3.py/issues/3125) ) ### Internal Changes - for web3.py Contributors[](#id87 "Link to this heading") * Updates and refactoring for the `WebsocketProviderV2` class and its internal supporting classes and logic. Separation of one-to-one and one-to-many request responses. Storing of one-to-many responses in a `deque` and one-to-one responses in a `SimpleCache` class. Provide an async lock around the websocket `recv()`. ([#3125](https://github.com/ethereum/web3.py/issues/3125) ) * Add upper pin to `hexbytes` dependency to due incoming breaking change ([#3127](https://github.com/ethereum/web3.py/issues/3127) ) ### Miscellaneous Changes[](#id88 "Link to this heading") * [#3114](https://github.com/ethereum/web3.py/issues/3114) , [#3129](https://github.com/ethereum/web3.py/issues/3129) web3.py v6.11.0 (2023-10-11)[](#web3-py-v6-11-0-2023-10-11 "Link to this heading") ------------------------------------------------------------------------------------ ### Breaking Changes (to Beta APIs)[](#breaking-changes-to-beta-apis "Link to this heading") * Refactor the async iterator pattern for message streams from the websocket connection for `WebsocketProviderV2` to a proper async iterator. This allows for a more natural usage of the iterator pattern and mimics the behavior of the underlying `websockets` library. ([#3116](https://github.com/ethereum/web3.py/issues/3116) ) ### Bugfixes[](#id89 "Link to this heading") * Use hashes to compare equality of two `AttributeDict` classes ([#3104](https://github.com/ethereum/web3.py/issues/3104) ) * Fix issues with formatting middleware, such as `async_geth_poa_middleware` and subscription responses for `WebsocketProviderV2`. ([#3116](https://github.com/ethereum/web3.py/issues/3116) ) ### Improved Documentation[](#id90 "Link to this heading") * Change `docker-compose` to `docker compose` in the Contributing docs examples. ([#3107](https://github.com/ethereum/web3.py/issues/3107) ) * Updates to the `WebsocketProviderV2` documentation async iterator example for iterating over a persistent stream of messages from the websocket connection via `async for`. ([#3116](https://github.com/ethereum/web3.py/issues/3116) ) * Update outdated node and private key management verbiage. ([#3117](https://github.com/ethereum/web3.py/issues/3117) ) ### Features[](#id91 "Link to this heading") * Allow passing in a `float` for a `request_timeout` for requests for the `Beacon` class. Update some Beacon API endpoints (sync and async). ([#3106](https://github.com/ethereum/web3.py/issues/3106) ) * Add `allow_list` kwarg for `exception_retry_middleware` to allow for a custom list of RPC endpoints. Add a sleep between retries and a customizable `backoff_factor` to control the sleep time between retry attempts. ([#3120](https://github.com/ethereum/web3.py/issues/3120) ) ### Internal Changes - for web3.py Contributors[](#id92 "Link to this heading") * Refactor logic for the `input_munger()` method on the `Method` class. ([#2987](https://github.com/ethereum/web3.py/issues/2987) ) * Pin mypy to v1.4.1, the last to support py37 ([#3122](https://github.com/ethereum/web3.py/issues/3122) ) web3.py v6.10.0 (2023-09-21)[](#web3-py-v6-10-0-2023-09-21 "Link to this heading") ------------------------------------------------------------------------------------ ### Breaking Changes (to Beta APIs)[](#id93 "Link to this heading") * Breaking change to the API for interacting with a persistent websocket connection via `AsyncWeb3` and `WebsocketProviderV2`. This change internalizes the `provider.ws` property and opts for a `w3.ws` API achieved via a new `WebsocketConnection` class. With these changes, `eth_subscription` messages now return the subscription id as the `subscription` param and the formatted message as the `result` param. ([#3096](https://github.com/ethereum/web3.py/issues/3096) ) ### Bugfixes[](#id94 "Link to this heading") * Return w3.eth.gas\_price when calculating time based gas price strategy for an empty chain. ([#1149](https://github.com/ethereum/web3.py/issues/1149) ) * Update LogReceipt and TxReceipt declarations. Remove LogReceipt’s payload and topic attributes. Refactor LogEntry to LogReceipt. ([#3043](https://github.com/ethereum/web3.py/issues/3043) ) * Fixes `AsyncEth.max_priority_fee_per_gas`. It wasn’t falling back to `eth_feeHistory` since the `MethodUnavailable` error was introduced. ([#3084](https://github.com/ethereum/web3.py/issues/3084) ) ### Improved Documentation[](#id95 "Link to this heading") * Update `WebsocketProviderV2` documentation to reflect the new public websocket API via the `WebsocketConnection` class. ([#3096](https://github.com/ethereum/web3.py/issues/3096) ) ### Features[](#id96 "Link to this heading") * Improved error messaging for exceptions from malformed JSON-RPC responses. ([#3053](https://github.com/ethereum/web3.py/issues/3053) ) * Enable filtering by non-indexed arguments for contract event `get_logs()`. ([#3078](https://github.com/ethereum/web3.py/issues/3078) ) * Add `eth_maxPriorityFeePerGas` to `exception_retry_middleware` whitelist ([#3090](https://github.com/ethereum/web3.py/issues/3090) ) * Sync responses for `WebsocketProviderV2` open connections with requests via matching RPC `id` values. ([#3096](https://github.com/ethereum/web3.py/issues/3096) ) * Properly JSON encode `AttributeDict`, `bytes`, and `HexBytes` when sending a JSON-RPC request by utilizing the in-house `Web3JsonEncoder` class. ([#3101](https://github.com/ethereum/web3.py/issues/3101) ) ### Internal Changes - for web3.py Contributors[](#id97 "Link to this heading") * Fix an issue with an IPC test present only on MacOSX. ([#929](https://github.com/ethereum/web3.py/issues/929) ) * Ignore flake8 rule F401 (unused import) in all `__init__.py` files ([#3097](https://github.com/ethereum/web3.py/issues/3097) ) web3.py v6.9.0 (2023-08-23)[](#web3-py-v6-9-0-2023-08-23 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id98 "Link to this heading") * Fix the type for `input` in `TxData` from `HexStr` -> `HexBytes`. ([#3074](https://github.com/ethereum/web3.py/issues/3074) ) * Fix an issue with `WebsocketProviderV2` when responses to a request aren’t found in the cache (`None` values). ([#3075](https://github.com/ethereum/web3.py/issues/3075) ) * Re-expose some websockets constants found in `web3.providers.websocket.websocket` via `web3.providers.websocket`. ([#3076](https://github.com/ethereum/web3.py/issues/3076) ) * Return `NotImplemented` constant, rather than raising `NotImplementedError` for `NamedElementOnion.__add__()`, based on Python standards. ([#3080](https://github.com/ethereum/web3.py/issues/3080) ) * Only release `async_lock` if it’s locked to begin with. ([#3083](https://github.com/ethereum/web3.py/issues/3083) ) ### Improved Documentation[](#id99 "Link to this heading") * Add MEV blocking tutorial to Resources docs page ([#3072](https://github.com/ethereum/web3.py/issues/3072) ) * Fix documentation around current state of `get_logs()` usage and arguments. ([#3073](https://github.com/ethereum/web3.py/issues/3073) ) * Add an Ape hackathon kit to Resources documenation page ([#3082](https://github.com/ethereum/web3.py/issues/3082) ) web3.py v6.8.0 (2023-08-02)[](#web3-py-v6-8-0-2023-08-02 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id100 "Link to this heading") * Fix the type for the optional param asking for “full transactions” when subscribing to `newPendingTransactions` via `eth_subscribe` to `bool`. ([#3067](https://github.com/ethereum/web3.py/issues/3067) ) ### Improved Documentation[](#id101 "Link to this heading") * Change docs to reflect AsyncHTTPProvider does accept ENS names now ([#3070](https://github.com/ethereum/web3.py/issues/3070) ) ### Features[](#id102 "Link to this heading") * Return structured JSON-RPC errors for missing or unimplemented eth-tester methods. ([#3061](https://github.com/ethereum/web3.py/issues/3061) ) * ENS name-to-address support for `eth_subscribe`. ([#3066](https://github.com/ethereum/web3.py/issues/3066) ) * Asynchronous iterator support for `AsyncWeb3` with `WebsocketProviderV2` using `async for` syntax. ([#3067](https://github.com/ethereum/web3.py/issues/3067) ) ### Internal Changes - for web3.py Contributors[](#id103 "Link to this heading") * Minor fixes to type hinting in the core tests setup fixtures. ([#3069](https://github.com/ethereum/web3.py/issues/3069) ) web3.py v6.7.0 (2023-07-26)[](#web3-py-v6-7-0-2023-07-26 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id104 "Link to this heading") * Test wheel build in separate directory and virtualenv ([#3046](https://github.com/ethereum/web3.py/issues/3046) ) * Handle case where data gets returned as `None` in a JSON-RPC error response ([#3054](https://github.com/ethereum/web3.py/issues/3054) ) * Fixed default windows IPC provider path to work with python 3.11 ([#3058](https://github.com/ethereum/web3.py/issues/3058) ) * Fix return type for `rpc_gas_price_strategy` to `int` but also only convert the `strategy_based_gas_price` to `hex` if it is an `int` in the `gas_price_strategy_middleware`. ([#3065](https://github.com/ethereum/web3.py/issues/3065) ) ### Improved Documentation[](#id105 "Link to this heading") * Add note to Release Notes about v5 end-of-life and v6.6.0 yank ([#3045](https://github.com/ethereum/web3.py/issues/3045) ) * Add documentation for `WebsocketProviderV2` (beta). ([#3048](https://github.com/ethereum/web3.py/issues/3048) ) ### Features[](#id106 "Link to this heading") * Add ENSIP-9 (Multichain Address Resolution) support for `address()` and `setup_address()` for `ENS` and `AsyncENS` classes. ([#3030](https://github.com/ethereum/web3.py/issues/3030) ) * Support for `eth_subscribe` and `eth_unsubscribe` methods has been added with the introduction of a new websocket provider, `WebsocketProviderV2`. ([#3048](https://github.com/ethereum/web3.py/issues/3048) ) ### Internal Changes - for web3.py Contributors[](#id107 "Link to this heading") * Added recursive typing to `ABIFunctionComponents` type ([#3063](https://github.com/ethereum/web3.py/issues/3063) ) * Upgrade eth-tester requirement to v0.9.0-b.1 ([#3064](https://github.com/ethereum/web3.py/issues/3064) ) web3.py v6.6.1 (2023-07-12)[](#web3-py-v6-6-1-2023-07-12 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id108 "Link to this heading") * Add `ens/specs` to MANIFEST.in ([#3039](https://github.com/ethereum/web3.py/issues/3039) ) web3.py v6.6.0 (2023-07-12)[](#web3-py-v6-6-0-2023-07-12 "Link to this heading") ---------------------------------------------------------------------------------- **Note: This release was missing the required \`\`ens/specs\`\` directory, so it was yanked from Pypi in favor of v6.6.1** ### Breaking Changes[](#id109 "Link to this heading") * ENS name normalization now uses ENSIP-15 by default. This is technically a breaking change introduced by ENS but, according to ENSIP-15, 99% of existing names should be unaffected. ([#3024](https://github.com/ethereum/web3.py/issues/3024) ) ### Bugfixes[](#id110 "Link to this heading") * Handle `None` in the formatting middleware ([#2546](https://github.com/ethereum/web3.py/issues/2546) ) * Fix for a possible bug in `construct_sign_and_send_raw_middleware` where the signed transaction was sent as bytes and expected to be converted to hex by formatting later on. It is now explicitly sent as the hex string hash within the middleware. ([#2936](https://github.com/ethereum/web3.py/issues/2936) ) * Fixes `max_priority_fee_per_gas`. It wasn’t falling back to `eth_feeHistory` since the `MethodUnavailable` error was introduced. ([#3002](https://github.com/ethereum/web3.py/issues/3002) ) * Properly initialize logger in `AsyncHTTPProvider`. ([#3026](https://github.com/ethereum/web3.py/issues/3026) ) * Fix `AsyncWeb3.solidity_keccak` to match `Web3.solidity_keccak`. ([#3034](https://github.com/ethereum/web3.py/issues/3034) ) ### Improved Documentation[](#id111 "Link to this heading") * Replaced transaction examples with unused account addresses. ([#2011](https://github.com/ethereum/web3.py/issues/2011) ) * Removed obsolete docs for camelCase miner methods and `deploy` ([#2039](https://github.com/ethereum/web3.py/issues/2039) ) * Update documentation relating to ENS only being available on mainnet. ENS is available on all networks where the ENS contracts are deployed. ([#3012](https://github.com/ethereum/web3.py/issues/3012) ) * Add first steps section and tidy up learning resources ([#3013](https://github.com/ethereum/web3.py/issues/3013) ) * Replace references to `jasoncarver.eth` with `ens.eth`. ([#3020](https://github.com/ethereum/web3.py/issues/3020) ) * Adds “Hackathon Helpers” section to Resources page ([#3035](https://github.com/ethereum/web3.py/issues/3035) ) ### Features[](#id112 "Link to this heading") * Update ENS Resolver ABI ([#1839](https://github.com/ethereum/web3.py/issues/1839) ) * `async_http_retry_request_middleware`, an async http request retry middleware for `AsyncHTTPProvider`. ([#3009](https://github.com/ethereum/web3.py/issues/3009) ) * Add `eth_getStorageAt()` support for `EthereumTesterProvider`. ([#3011](https://github.com/ethereum/web3.py/issues/3011) ) * Add async support for ENS name-to-address resolution via `async_name_to_address_middleware`. ([#3012](https://github.com/ethereum/web3.py/issues/3012) ) * Add async support for the sign-and-send raw transaction middleware via `construct_async_sign_and_send_raw_middleware()`. ([#3025](https://github.com/ethereum/web3.py/issues/3025) ) ### Internal Changes - for web3.py Contributors[](#id113 "Link to this heading") * Remove some warnings from test output ([#2991](https://github.com/ethereum/web3.py/issues/2991) ) * Introduced the logic for ENSIP-15 ENS name normalization. Originally this was done via a flag in this PR but changed to the default behavior in #3024 before release. ([#3000](https://github.com/ethereum/web3.py/issues/3000) ) ### Miscellaneous Changes[](#id114 "Link to this heading") * [#2997](https://github.com/ethereum/web3.py/issues/2997) , [#3011](https://github.com/ethereum/web3.py/issues/3011) , [#3023](https://github.com/ethereum/web3.py/issues/3023) , [#3037](https://github.com/ethereum/web3.py/issues/3037) ### Removals[](#id115 "Link to this heading") * Removed references to deprecated middlewares with new tests to check default middlewares ([#2972](https://github.com/ethereum/web3.py/issues/2972) ) web3.py v6.5.0 (2023-06-15)[](#web3-py-v6-5-0-2023-06-15 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id116 "Link to this heading") * Properly create a fresh cache for each instance of `simple_cache_middleware` if no cache is provided. Fixes a bug when using this middleware with multiple instances of `Web3`. ([#2979](https://github.com/ethereum/web3.py/issues/2979) ) * Fix potential race condition when writing cache entries in `simple_cache_middleware` ([#2981](https://github.com/ethereum/web3.py/issues/2981) ) * Catch `UnicodeDecodeError` for contract revert messages that cannot be decoded and issue a warning instead, raising a `ContractLogicError` with the raw `data` from the response. ([#2989](https://github.com/ethereum/web3.py/issues/2989) ) ### Improved Documentation[](#id117 "Link to this heading") * Introduces resources page to documentation ([#2957](https://github.com/ethereum/web3.py/issues/2957) ) * Completed docstrings for `ContractFunction` and `AsyncContractFunction` classes ([#2960](https://github.com/ethereum/web3.py/issues/2960) ) * Added ‘unsupported by any current clients’ note to the `Eth.sign_typed_data` docs ([#2961](https://github.com/ethereum/web3.py/issues/2961) ) * Removed list of `AsyncHTTPProvider`\-supported methods, it supports them all now ([#2962](https://github.com/ethereum/web3.py/issues/2962) ) * Modernize the filtering guide, emphasizing `get_logs` ([#2968](https://github.com/ethereum/web3.py/issues/2968) ) * Removed references to defunct providers in `IPCProvider` docs ([#2971](https://github.com/ethereum/web3.py/issues/2971) ) * Update Matomo analytics script to move to cloud services ([#2978](https://github.com/ethereum/web3.py/issues/2978) ) ### Features[](#id118 "Link to this heading") * Add the `sign_typed_data` method to the `AsyncEth` class ([#2920](https://github.com/ethereum/web3.py/issues/2920) ) * Add support for Solidity `Panic` errors, available since Solidity 0.8.0. Raises `ContractPanicError` with appropriate messaging based on the known panic error codes. ([#2986](https://github.com/ethereum/web3.py/issues/2986) ) ### Internal Changes - for web3.py Contributors[](#id119 "Link to this heading") * `lint-roll` - dropped `isort` `--recursive` flag, not needed as of their `v5`, added black ([#2930](https://github.com/ethereum/web3.py/issues/2930) ) * Moved `ethpm` deprecation warning to only show when the module is explicitly enabled ([#2983](https://github.com/ethereum/web3.py/issues/2983) ) * Update make release to check remote upstream is pointing to ethereum/web3.py. ([#2988](https://github.com/ethereum/web3.py/issues/2988) ) * Removed pluggy from dev requirements ([#2992](https://github.com/ethereum/web3.py/issues/2992) ) ### Miscellaneous Changes[](#id120 "Link to this heading") * [#2960](https://github.com/ethereum/web3.py/issues/2960) , [#2965](https://github.com/ethereum/web3.py/issues/2965) web3.py v6.4.0 (2023-05-15)[](#web3-py-v6-4-0-2023-05-15 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id121 "Link to this heading") * fix AttributeDicts unhashable if they contain lists recursively tupleizing them ([#2908](https://github.com/ethereum/web3.py/issues/2908) ) ### Deprecations[](#id122 "Link to this heading") * add deprecation notice for the ethPM module ([#2953](https://github.com/ethereum/web3.py/issues/2953) ) ### Improved Documentation[](#id123 "Link to this heading") * remove reference to the ability to specify a list of providers - you can’t anymore ([#2949](https://github.com/ethereum/web3.py/issues/2949) ) * add deprecation notice for the ethPM module ([#2953](https://github.com/ethereum/web3.py/issues/2953) ) ### Features[](#id124 "Link to this heading") * Update `eth-tester` to pull in Shanghai changes and make additional changes to fully support Shanghai with `eth-tester`. ([#2958](https://github.com/ethereum/web3.py/issues/2958) ) ### Internal Changes - for web3.py Contributors[](#id125 "Link to this heading") * bump sphinx and readthedocs py versions ([#2945](https://github.com/ethereum/web3.py/issues/2945) ) * re-compile test contracts with Solidity `v0.8.20` ([#2951](https://github.com/ethereum/web3.py/issues/2951) ) * Set towncrier settings in pyproject.toml to match the python project template and change newfragment type “doc” to “docs” ([#2959](https://github.com/ethereum/web3.py/issues/2959) ) v6.3.0 (2023-05-03)[](#v6-3-0-2023-05-03 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id126 "Link to this heading") * Add support for custom revert errors ([#2795](https://github.com/ethereum/web3.py/issues/2795) ) * Add the `modify_transaction` method to the `AsyncEth` class ([#2825](https://github.com/ethereum/web3.py/issues/2825) ) * add show\_traceback flag to is\_connected to allow user to see connection error reason ([#2912](https://github.com/ethereum/web3.py/issues/2912) ) * Add a `data` attribute on the `ContractLogicError` class that returns raw data returned by the node. ([#2922](https://github.com/ethereum/web3.py/issues/2922) ) * Add support via result formatters for `reward` type trace actions on tracing calls. ([#2929](https://github.com/ethereum/web3.py/issues/2929) ) ### Bugfixes[](#id127 "Link to this heading") * Typing was being ignored for the `get_ipc_path` and `get_dev_ipc_path` functions because of a missing `None` return. Those two methods now explicitly return `None` and have an `Optional` in their type definition. ([#2917](https://github.com/ethereum/web3.py/issues/2917) ) * fix AsyncEventFilterBuilder looking for Web3 instead of AsyncWeb3 ([#2931](https://github.com/ethereum/web3.py/issues/2931) ) * Add check for null withdrawal field on get\_block response ([#2941](https://github.com/ethereum/web3.py/issues/2941) ) ### Improved Documentation[](#id128 "Link to this heading") * Add a decision tree guide for sending transactions ([#2919](https://github.com/ethereum/web3.py/issues/2919) ) * Update references to master branch ([#2933](https://github.com/ethereum/web3.py/issues/2933) ) * Cleanup Quickstart guide and next steps ([#2935](https://github.com/ethereum/web3.py/issues/2935) ) * Cleanup Overview page links and context ([#2938](https://github.com/ethereum/web3.py/issues/2938) ) ### Internal Changes - for web3.py Contributors[](#id129 "Link to this heading") * Added `build` to towncrier commands in Makefile ([#2915](https://github.com/ethereum/web3.py/issues/2915) ) * Update win wheel CI builds to use `python -m tox -r` instead of specifying the `tox` executable directly. ([#2923](https://github.com/ethereum/web3.py/issues/2923) ) * update pip and tox install on CI containers ([#2927](https://github.com/ethereum/web3.py/issues/2927) ) v6.2.0 (2023-04-12)[](#v6-2-0-2023-04-12 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id130 "Link to this heading") * Adds async version of eth\_getUncleCount methods ([#2822](https://github.com/ethereum/web3.py/issues/2822) ) * Add the `sign_transaction` method to the `AsyncEth` class ([#2827](https://github.com/ethereum/web3.py/issues/2827) ) * Add the `replace_transaction` method to the `AsyncEth` class ([#2847](https://github.com/ethereum/web3.py/issues/2847) ) ### Bugfixes[](#id131 "Link to this heading") * Use `TraceFilterParams` instead of `FilterParams` for `trace_filter` typing ([#2913](https://github.com/ethereum/web3.py/issues/2913) ) ### Improved Documentation[](#id132 "Link to this heading") * Add welcome banner for Ethereum newcomers ([#2905](https://github.com/ethereum/web3.py/issues/2905) ) * Added breaking changes from pr2448 to v6 migration guide ([#2907](https://github.com/ethereum/web3.py/issues/2907) ) v6.1.0 (2023-04-05)[](#v6-1-0-2023-04-05 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id133 "Link to this heading") * Add tracing functionality back in via the `tracing` module, add formatters for human-readable input and output, and attach this module to `Web3` on init / make it a default module. ([#2851](https://github.com/ethereum/web3.py/issues/2851) ) * Add result formatters for `withdrawals_root` and `withdrawals` as part of `Shanghai` hard fork support. ([#2868](https://github.com/ethereum/web3.py/issues/2868) ) * add eth\_chainId to exception\_retry\_middleware whitelist ([#2892](https://github.com/ethereum/web3.py/issues/2892) ) ### Bugfixes[](#id134 "Link to this heading") * Mark test\_async\_eth\_sign with @pytest.mark.asyncio ([#2858](https://github.com/ethereum/web3.py/issues/2858) ) * fix readthedocs broken version selector ([#2883](https://github.com/ethereum/web3.py/issues/2883) ) ### Improved Documentation[](#id135 "Link to this heading") * remove camelCased method deprecation notices from web3.eth docs ([#2882](https://github.com/ethereum/web3.py/issues/2882) ) * Add doc blurb about multiple HTTPProviders with the same URL ([#2889](https://github.com/ethereum/web3.py/issues/2889) ) * fix styling and external link formatting ([#2897](https://github.com/ethereum/web3.py/issues/2897) ) ### Internal Changes - for web3.py Contributors[](#id136 "Link to this heading") * Bump pytest from 6.2.5 to 7+ because of CI `DeprecationWarning` ([#2863](https://github.com/ethereum/web3.py/issues/2863) ) * Require eth-abi v4 stable ([#2886](https://github.com/ethereum/web3.py/issues/2886) ) * remove unused docs dependencies and bump version of remaining ([#2890](https://github.com/ethereum/web3.py/issues/2890) ) * Update go-ethereum integration test fixture to use the latest version of geth - `v1.11.5`. ([#2896](https://github.com/ethereum/web3.py/issues/2896) ) * Update `geth_steps` in CircleCI builds to pip install the proper version of `py-geth`. ([#2898](https://github.com/ethereum/web3.py/issues/2898) ) * Update CircleCI windows orb path since it now uses python 3.11. ([#2899](https://github.com/ethereum/web3.py/issues/2899) ) * Bump go version used in CI jobs that install and run go-ethereum and parameterize the version in circleci config file for ease of configuration. ([#2900](https://github.com/ethereum/web3.py/issues/2900) ) ### Miscellaneous changes[](#id137 "Link to this heading") * [#2887](https://github.com/ethereum/web3.py/issues/2887) v6.0.0 (2023-03-14)[](#v6-0-0-2023-03-14 "Link to this heading") ------------------------------------------------------------------ ### Bugfixes[](#id138 "Link to this heading") * fix dict\_to\_namedtuple unable to handle empty dict as input ([#2867](https://github.com/ethereum/web3.py/issues/2867) ) v6.0.0-beta.11 (2023-02-24)[](#v6-0-0-beta-11-2023-02-24 "Link to this heading") ---------------------------------------------------------------------------------- ### Features[](#id139 "Link to this heading") * Add the `sign` method to the `AsyncEth` class ([#2833](https://github.com/ethereum/web3.py/issues/2833) ) ### Bugfixes[](#id140 "Link to this heading") * More accurately define the `eth_call` return type as `HexBytes` since the response is converted to `HexBytes` in the pythonic formatters and there are differences between `HexBytes` and `bytes` types. ([#2842](https://github.com/ethereum/web3.py/issues/2842) ) * Set default block\_identifier in ContractFunction.call() to None ([#2846](https://github.com/ethereum/web3.py/issues/2846) ) ### Improved Documentation[](#id141 "Link to this heading") * Remove unused module lines to instantiate the AsyncHTTPProvider ([#2789](https://github.com/ethereum/web3.py/issues/2789) ) * Typos fix in docs ([#2817](https://github.com/ethereum/web3.py/issues/2817) ) * Add/cleanup docs for the `AsyncHTTPProvider` in light of the new `AsyncWeb3` class ([#2821](https://github.com/ethereum/web3.py/issues/2821) ) * Remove user survey banner following close of survey ([#2831](https://github.com/ethereum/web3.py/issues/2831) ) ### Internal Changes - for web3.py Contributors[](#id142 "Link to this heading") * Do not invoke `setup.py` directly; use `python -m build` where appropriate. ([#2714](https://github.com/ethereum/web3.py/issues/2714) ) * clean up ignored unused imports ([#2838](https://github.com/ethereum/web3.py/issues/2838) ) * Recompile test contracts with the new Solidity version `0.8.19`. ([#2840](https://github.com/ethereum/web3.py/issues/2840) ) * Update `py-geth` version and re-generate integration test fixture with geth `v1.11.2`. ([#2841](https://github.com/ethereum/web3.py/issues/2841) ) ### Breaking changes[](#id143 "Link to this heading") * Use `AsyncWeb3` class and preserve typing for the async api calls. ([#2819](https://github.com/ethereum/web3.py/issues/2819) ) * Fix typing for `CallOverrideParams` and add proper request formatters for call state overrides. ([#2843](https://github.com/ethereum/web3.py/issues/2843) ) * Remove python warning and doc notes related to unstable async providers. ([#2845](https://github.com/ethereum/web3.py/issues/2845) ) v6.0.0-beta.10 (2023-02-15)[](#v6-0-0-beta-10-2023-02-15 "Link to this heading") ---------------------------------------------------------------------------------- ### Features[](#id144 "Link to this heading") * add decode\_tuples option to contract instantiation ([#2799](https://github.com/ethereum/web3.py/issues/2799) ) ### Bugfixes[](#id145 "Link to this heading") * Fix `ethpm` import issues after making `ipfshttpclient` optional. ([#2775](https://github.com/ethereum/web3.py/issues/2775) ) * Fix for recently-broken `eth-tester` exception message parsing for some exception cases. ([#2783](https://github.com/ethereum/web3.py/issues/2783) ) ### Improved Documentation[](#id146 "Link to this heading") * Added a v6 Migraion Guide ([#2778](https://github.com/ethereum/web3.py/issues/2778) ) * Rebrand the library to lowercase “web3.py” ([#2804](https://github.com/ethereum/web3.py/issues/2804) ) * remove references to Rinkeby or replace with Goerli ([#2815](https://github.com/ethereum/web3.py/issues/2815) ) ### Internal Changes - for web3.py Contributors[](#id147 "Link to this heading") * Organize the `eth` module into separate files for better readability. ([#2753](https://github.com/ethereum/web3.py/issues/2753) ) * Rename the newly-split `eth` module files to match convention. ([#2772](https://github.com/ethereum/web3.py/issues/2772) ) * Re-compile all test contracts with latest Solidity version. Refactor test fixtures. Adds a script that compiles all test contracts to the same directory with selected Solidity version. ([#2797](https://github.com/ethereum/web3.py/issues/2797) ) * Updates to `isort` and `black` required some formatting changes and isort config refactoring. ([#2802](https://github.com/ethereum/web3.py/issues/2802) ) * Compile test contracts using newly-released Solidity version `0.8.18`. ([#2803](https://github.com/ethereum/web3.py/issues/2803) ) ### Breaking changes[](#id148 "Link to this heading") * All exceptions inherit from a custom class. EthPM exceptions inherit from EthPMException, ENS exceptions inherit from ENSException, and all other web3.py exceptions inherit from Web3Exception ([#1478](https://github.com/ethereum/web3.py/issues/1478) ) * Reorganized contract to contract.py, async\_contract.py, base\_contract.py and utils.py. In this change there was a small breaking change where the constructor of BaseContractCaller contract\_function\_class was defaulting to a ContractFunction now there is no default. This was done to separate the base class from the implementation. ([#2567](https://github.com/ethereum/web3.py/issues/2567) ) * When calling a contract, use `w3.eth.default_block` if no block\_identifier is specified instead of `latest`. ([#2777](https://github.com/ethereum/web3.py/issues/2777) ) * Strict bytes type checking is now default for `web3.py`. This change also adds a boolean flag on the `Web3` class for turning this feature on and off, as well as a flag on the `ENS` class for control over a standalone `ENS` instance. ([#2788](https://github.com/ethereum/web3.py/issues/2788) ) * When a method is not supported by a node provider, raise a MethodUnavailable error instead of the generic ValueError. ([#2796](https://github.com/ethereum/web3.py/issues/2796) ) * `dict` to `AttributeDict` conversion is no longer a default result formatter. This conversion is now done via a default middleware that may be removed. ([#2805](https://github.com/ethereum/web3.py/issues/2805) ) * Removed deprecated `manager.request_async` and associated methods. ([#2810](https://github.com/ethereum/web3.py/issues/2810) ) * removed Rinkeby from list of allowed chains in EthPM ([#2815](https://github.com/ethereum/web3.py/issues/2815) ) v6.0.0-beta.9 (2023-01-03)[](#v6-0-0-beta-9-2023-01-03 "Link to this heading") -------------------------------------------------------------------------------- ### Features[](#id149 "Link to this heading") * Add async `w3.eth.get_block_transaction_count` ([#2687](https://github.com/ethereum/web3.py/issues/2687) ) * Support Python 3.11 ([#2699](https://github.com/ethereum/web3.py/issues/2699) ) * Load the `AsyncHTTPProvider` with default async middleware and default async modules, just as the `HTTPProvider`. ([#2736](https://github.com/ethereum/web3.py/issues/2736) ) * Add support for Nethermind/Gnosis revert reason formatting ([#2739](https://github.com/ethereum/web3.py/issues/2739) ) * Added async functionality to filter ([#2744](https://github.com/ethereum/web3.py/issues/2744) ) * Get contract address from `CREATE` and `CREATE2` opcodes ([#2762](https://github.com/ethereum/web3.py/issues/2762) ) ### Bugfixes[](#id150 "Link to this heading") * Fixing abi encoding for multidimensional arrays. ([#2764](https://github.com/ethereum/web3.py/issues/2764) ) ### Performance improvements[](#id151 "Link to this heading") * Some minor performance improvements to the `SimpleCache` class and simple cache middlewares (sync and async). ([#2719](https://github.com/ethereum/web3.py/issues/2719) ) * Remove unnecessary `await` for `generate_gas_price()` method as it does not need to be awaited. Move this method to `BaseEth` to be used directly by both `Eth` and `AsyncEth` modules. ([#2735](https://github.com/ethereum/web3.py/issues/2735) ) ### Improved Documentation[](#id152 "Link to this heading") * Add user survey to docs banner ([#2720](https://github.com/ethereum/web3.py/issues/2720) ) * Document improvements for private key info and account funding. ([#2722](https://github.com/ethereum/web3.py/issues/2722) ) * Include eth-tester install note in quickstart ([#2755](https://github.com/ethereum/web3.py/issues/2755) ) ### Deprecations and Removals[](#deprecations-and-removals "Link to this heading") * Removal of Infura auto provider support. ([#2706](https://github.com/ethereum/web3.py/issues/2706) ) * Removal of `version` module. ([#2729](https://github.com/ethereum/web3.py/issues/2729) ) * Remove already-deprecated `start_rpc` and `stop_rpc` from the `w3.geth.admin` module. ([#2731](https://github.com/ethereum/web3.py/issues/2731) ) ### Internal Changes - for web3.py Contributors[](#id153 "Link to this heading") * Use regex pattern for `black` command for `tox` / `make lint` linting commands. ([#2727](https://github.com/ethereum/web3.py/issues/2727) ) * Use regex pattern for `mypy` command for `tox` / `make lint` linting commands. ([#2734](https://github.com/ethereum/web3.py/issues/2734) ) * Remove internal method `apply_formatter_to_array` and use the method with the same name from the `eth-utils` library. ([#2737](https://github.com/ethereum/web3.py/issues/2737) ) ### Miscellaneous changes[](#id154 "Link to this heading") * [#2751](https://github.com/ethereum/web3.py/issues/2751) ### Breaking changes[](#id155 "Link to this heading") * Snakecase the processReceipt, processLog, createFilter, and getLogs methods ([#2709](https://github.com/ethereum/web3.py/issues/2709) ) * Remove Parity module and references. ([#2718](https://github.com/ethereum/web3.py/issues/2718) ) * Make the `ipfshttpclient` library opt-in via a web3 install extra. This only affects the `ethpm` `ipfs` backends, which rely on the library. ([#2730](https://github.com/ethereum/web3.py/issues/2730) ) v6.0.0-beta.8 (2022-11-14)[](#v6-0-0-beta-8-2022-11-14 "Link to this heading") -------------------------------------------------------------------------------- ### Features[](#id156 "Link to this heading") * Async support for caching certain methods via `async_simple_cache_middleware` as well as constructing custom async caching middleware via `async_construct_simple_cache_middleware`. `SimpleCache` class was also added to the public `utils` module. ([#2579](https://github.com/ethereum/web3.py/issues/2579) ) * Remove upper pins on dependencies ([#2648](https://github.com/ethereum/web3.py/issues/2648) ) * Async support for beacon api. ([#2689](https://github.com/ethereum/web3.py/issues/2689) ) * If the loop for a cached async session is closed, or the session itself was closed, create a new session at that cache key and properly close and evict the stale session. ([#2713](https://github.com/ethereum/web3.py/issues/2713) ) ### Bugfixes[](#id157 "Link to this heading") * bump sphinx\_rtd\_theme version to fix missing unordered list bullets ([#2688](https://github.com/ethereum/web3.py/issues/2688) ) * Fix bug to generate unique cache keys when multi-threading & with unique event loops for async. ([#2690](https://github.com/ethereum/web3.py/issues/2690) ) * Properly release `async_lock` for session requests if an exception is raised during a task. ([#2695](https://github.com/ethereum/web3.py/issues/2695) ) ### Internal Changes - for web3.py Contributors[](#id158 "Link to this heading") * move definition of RTD install requirements file from their dashboard into .readthedocs.yml, and remove unused sphinx-better-theme from requirements ([#2688](https://github.com/ethereum/web3.py/issues/2688) ) ### Miscellaneous changes[](#id159 "Link to this heading") * [#2690](https://github.com/ethereum/web3.py/issues/2690) , [#2694](https://github.com/ethereum/web3.py/issues/2694) ### Breaking changes[](#id160 "Link to this heading") * Remove support for dictionary-based caches, for simple-cache-middleware, in favor of the internal `SimpleCache` class. ([#2579](https://github.com/ethereum/web3.py/issues/2579) ) * Snakecase the clientVersion method ([#2686](https://github.com/ethereum/web3.py/issues/2686) ) * change instances of createFilter to create\_filter ([#2692](https://github.com/ethereum/web3.py/issues/2692) ) * Remove `SolidityError` in favor of `ContractLogicError` ([#2697](https://github.com/ethereum/web3.py/issues/2697) ) * Snakecase the solidityKeccak method ([#2702](https://github.com/ethereum/web3.py/issues/2702) ) * Snakecase the fromWeb3 method ([#2703](https://github.com/ethereum/web3.py/issues/2703) ) * Snakecase the toBytes, toHex, toInt, toJSON, and toText methods ([#2707](https://github.com/ethereum/web3.py/issues/2707) ) * Snakecase the toAddress, isChecksumAddress, and toChecksumAddress methods ([#2708](https://github.com/ethereum/web3.py/issues/2708) ) v6.0.0-beta.7 (2022-10-19)[](#v6-0-0-beta-7-2022-10-19 "Link to this heading") -------------------------------------------------------------------------------- ### Bugfixes[](#id161 "Link to this heading") * Protobuf dependency had a DoS-able bug. It was fixed in v4.21.6. See: [https://nvd.nist.gov/vuln/detail/CVE-2022-1941](https://nvd.nist.gov/vuln/detail/CVE-2022-1941) ([#2666](https://github.com/ethereum/web3.py/issues/2666) ) ### Improved Documentation[](#id162 "Link to this heading") * Added Chainstack link to quickstart docs. ([#2677](https://github.com/ethereum/web3.py/issues/2677) ) ### Deprecations and Removals[](#id163 "Link to this heading") * Remove Ropsten auto provider and the relevant references to Ropsten across the repo ([#2672](https://github.com/ethereum/web3.py/issues/2672) ) ### Internal Changes - for web3.py Contributors[](#id164 "Link to this heading") * Clean up remaining uses of deprecated `eth_abi` methods. ([#2668](https://github.com/ethereum/web3.py/issues/2668) ) ### Miscellaneous changes[](#id165 "Link to this heading") * [#2671](https://github.com/ethereum/web3.py/issues/2671) , [#2682](https://github.com/ethereum/web3.py/issues/2682) v6.0.0-beta.6 (2022-09-26)[](#v6-0-0-beta-6-2022-09-26 "Link to this heading") -------------------------------------------------------------------------------- ### Bugfixes[](#id166 "Link to this heading") * Protobuf dependency breaks at version `3.20.2` and above; pin to `3.20.1` for now. ([#2657](https://github.com/ethereum/web3.py/issues/2657) ) ### Features[](#id167 "Link to this heading") * Add new predefined block identifiers `safe` and `finalized`. ([#2652](https://github.com/ethereum/web3.py/issues/2652) ) v6.0.0-beta.5 (2022-09-19)[](#v6-0-0-beta-5-2022-09-19 "Link to this heading") -------------------------------------------------------------------------------- ### Breaking Changes[](#id168 "Link to this heading") * Removed IBAN since it was an unused feature ([#2537](https://github.com/ethereum/web3.py/issues/2537) ) * Update eth-tester dependency to v0.7.0-beta.1; Update eth-account version to >=0.7.0,<0.8.0 ([#2623](https://github.com/ethereum/web3.py/issues/2623) ) * Remove `WEB3_INFURA_API_KEY` environment variable in favor of `WEB3_INFURA_PROJECT_ID`. Change `InfuraKeyNotFound` exception to `InfuraProjectIdNotFound` ([#2634](https://github.com/ethereum/web3.py/issues/2634) ) * Remove Kovan auto provider ([#2635](https://github.com/ethereum/web3.py/issues/2635) ) * Snakecase the isConnected method ([#2643](https://github.com/ethereum/web3.py/issues/2643) ) * Snakecase the `toWei` and `fromWei` methods ([#2647](https://github.com/ethereum/web3.py/issues/2647) ) ### Bugfixes[](#id169 "Link to this heading") * Fix `eth-tester` key remapping for `logsBloom` and `receiptsRoot` ([#1630](https://github.com/ethereum/web3.py/issues/1630) ) * Improve upon issues with session caching - better support for multithreading and make sure session eviction from cache does not happen prematurely. ([#2409](https://github.com/ethereum/web3.py/issues/2409) ) * Allow classes to inherit from the `Web3` class by attaching modules appropriately. ([#2592](https://github.com/ethereum/web3.py/issues/2592) ) * fixed bug in how async\_eth\_tester\_middleware fills default fields ([#2600](https://github.com/ethereum/web3.py/issues/2600) ) * Allow hex for `value` field when validating via `validate_payable()` contracts method ([#2602](https://github.com/ethereum/web3.py/issues/2602) ) * Update Beacon API to v2.3.0 ([#2616](https://github.com/ethereum/web3.py/issues/2616) ) * Move `flaky` option to top-level conftest.py ([#2642](https://github.com/ethereum/web3.py/issues/2642) ) ### Documentation Updates[](#documentation-updates "Link to this heading") * Update Proof of Authority middleware (geth\_poa\_middleware) documentation for better clarity. ([#2538](https://github.com/ethereum/web3.py/issues/2538) ) * Add some missing supported async middlewares to docs. ([#2574](https://github.com/ethereum/web3.py/issues/2574) ) * Introduce AsyncENS and availability on w3 instance in ENS guide. ([#2585](https://github.com/ethereum/web3.py/issues/2585) ) * Fix typo in eth.call docs ([#2613](https://github.com/ethereum/web3.py/issues/2613) ) * remove section for deleted account.recoverHash method ([#2615](https://github.com/ethereum/web3.py/issues/2615) ) * examples docs gave incorrect return type for eth.get\_transaction, fixed ([#2617](https://github.com/ethereum/web3.py/issues/2617) ) * minor typo fix in contracts overview ([#2628](https://github.com/ethereum/web3.py/issues/2628) ) * fix bug in Deploying new contracts example ([#2646](https://github.com/ethereum/web3.py/issues/2646) ) ### Features[](#id170 "Link to this heading") * Support for `Account` class access in `AsyncEth` via `async_w3.eth.account` ([#2580](https://github.com/ethereum/web3.py/issues/2580) ) * Expose public abi utility methods: `get_abi_output_names()` and `get_abi_input_names()` ([#2596](https://github.com/ethereum/web3.py/issues/2596) ) * update all references to deprecated eth\_abi.encode\_abi to eth\_abi.encode ([#2621](https://github.com/ethereum/web3.py/issues/2621) ) * update all references to deprecated eth\_abi.decode\_abi to eth\_abi.decode ([#2636](https://github.com/ethereum/web3.py/issues/2636) ) * Add Sepolia auto provider ([#2639](https://github.com/ethereum/web3.py/issues/2639) ) ### Misc[](#misc "Link to this heading") * [#2603](https://github.com/ethereum/web3.py/issues/2603) , [#2622](https://github.com/ethereum/web3.py/issues/2622) , [#2630](https://github.com/ethereum/web3.py/issues/2630) , [#2638](https://github.com/ethereum/web3.py/issues/2638) v6.0.0-beta.4 (2022-07-13)[](#v6-0-0-beta-4-2022-07-13 "Link to this heading") -------------------------------------------------------------------------------- ### Breaking Changes[](#id171 "Link to this heading") * sha3 and soliditySha3 were previously deprecated and now removed ([#2479](https://github.com/ethereum/web3.py/issues/2479) ) * Remove deprecated methods from Geth, Parity and Net modules ([#2480](https://github.com/ethereum/web3.py/issues/2480) ) * Provide better messaging to wrong arguments for contract functions, especially for `tuple` argument types. ([#2556](https://github.com/ethereum/web3.py/issues/2556) ) ### Bugfixes[](#id172 "Link to this heading") * Properly format `block_number` for `eth_getTransactionCount` when using `EthereumTesterProvider` ([#1801](https://github.com/ethereum/web3.py/issues/1801) ) * removed Optional type hints for passphrase arguments that aren’t actually optional ([#2511](https://github.com/ethereum/web3.py/issues/2511) ) * Fix is\_dynamic\_fee\_transaction and TRANSACTION\_DEFAULTS when gas\_price\_strategy returns zero ([#2562](https://github.com/ethereum/web3.py/issues/2562) ) ### Documentation Updates[](#id173 "Link to this heading") * Remove deprecated methods from Geth, Parity, and Net modules ([#2480](https://github.com/ethereum/web3.py/issues/2480) ) * replace double- with single-quotes to make f-string valid ([#2504](https://github.com/ethereum/web3.py/issues/2504) ) * added geth personal\_sign and personal\_ec\_recover documentation ([#2511](https://github.com/ethereum/web3.py/issues/2511) ) ### Features[](#id174 "Link to this heading") * Add transaction result formatters for type and chainId to convert values to `int` if `hexadecimal` if the field is not null ([#2491](https://github.com/ethereum/web3.py/issues/2491) ) * Add a global flag on the provider for enabling / disabling CCIP Read for calls: `global_ccip_read_enabled` (defaults to `True`). ([#2499](https://github.com/ethereum/web3.py/issues/2499) ) * Deprecate Geth Admin StartRPC and StopRPC for StartHTTP and StopHTTP ([#2507](https://github.com/ethereum/web3.py/issues/2507) ) * Added Async support for ENS ([#2547](https://github.com/ethereum/web3.py/issues/2547) ) * support multi-dimensional arrays for ABI tuples types ([#2555](https://github.com/ethereum/web3.py/issues/2555) ) ### Misc[](#id175 "Link to this heading") * [#2345](https://github.com/ethereum/web3.py/issues/2345) , [#2483](https://github.com/ethereum/web3.py/issues/2483) , [#2505](https://github.com/ethereum/web3.py/issues/2505) , [#2513](https://github.com/ethereum/web3.py/issues/2513) , [#2514](https://github.com/ethereum/web3.py/issues/2514) , [#2515](https://github.com/ethereum/web3.py/issues/2515) , [#2516](https://github.com/ethereum/web3.py/issues/2516) , [#2518](https://github.com/ethereum/web3.py/issues/2518) , [#2520](https://github.com/ethereum/web3.py/issues/2520) , [#2521](https://github.com/ethereum/web3.py/issues/2521) , [#2522](https://github.com/ethereum/web3.py/issues/2522) , [#2523](https://github.com/ethereum/web3.py/issues/2523) , [#2524](https://github.com/ethereum/web3.py/issues/2524) , [#2525](https://github.com/ethereum/web3.py/issues/2525) , [#2527](https://github.com/ethereum/web3.py/issues/2527) , [#2530](https://github.com/ethereum/web3.py/issues/2530) , [#2531](https://github.com/ethereum/web3.py/issues/2531) , [#2534](https://github.com/ethereum/web3.py/issues/2534) , [#2542](https://github.com/ethereum/web3.py/issues/2542) , [#2544](https://github.com/ethereum/web3.py/issues/2544) , [#2550](https://github.com/ethereum/web3.py/issues/2550) , [#2551](https://github.com/ethereum/web3.py/issues/2551) , [#2559](https://github.com/ethereum/web3.py/issues/2559) v6.0.0-beta.3 (2022-06-01)[](#v6-0-0-beta-3-2022-06-01 "Link to this heading") -------------------------------------------------------------------------------- ### Breaking Changes[](#id176 "Link to this heading") * Removed deprecated methods from eth and geth ([#1416](https://github.com/ethereum/web3.py/issues/1416) ) ### Bugfixes[](#id177 "Link to this heading") * Fix bug in \_is\_latest\_block\_number\_request in cache middleware ([#2185](https://github.com/ethereum/web3.py/issues/2185) ) * Increase cache size to allow for 20 entries. ([#2477](https://github.com/ethereum/web3.py/issues/2477) ) * format receipt.type to int and log.data to HexBytes ([#2482](https://github.com/ethereum/web3.py/issues/2482) ) * Only thread lock for methods attempting to access the cache for caching middleware. ([#2496](https://github.com/ethereum/web3.py/issues/2496) ) ### Documentation Updates[](#id178 "Link to this heading") * Fix typo in simple\_cache\_middleware example ([#2449](https://github.com/ethereum/web3.py/issues/2449) ) * Fix dict type hints in EventScanner example ([#2469](https://github.com/ethereum/web3.py/issues/2469) ) * Add clarification around ValueError and Local Signing middleware ([#2474](https://github.com/ethereum/web3.py/issues/2474) ) ### Features[](#id179 "Link to this heading") * Add async version of contract functionality ([#2270](https://github.com/ethereum/web3.py/issues/2270) ) * ENSIP-10 / wildcard resolution support for ENS module ([#2411](https://github.com/ethereum/web3.py/issues/2411) ) * CCIP Read support and finalize implementation of and add tests for ENS offchain resolution support ([#2457](https://github.com/ethereum/web3.py/issues/2457) ) ### Misc[](#id180 "Link to this heading") * [#2454](https://github.com/ethereum/web3.py/issues/2454) , [#2450](https://github.com/ethereum/web3.py/issues/2450) , [#2462](https://github.com/ethereum/web3.py/issues/2462) , [#2471](https://github.com/ethereum/web3.py/issues/2471) , [#2478](https://github.com/ethereum/web3.py/issues/2478) v6.0.0-beta.2 (2022-04-27)[](#v6-0-0-beta-2-2022-04-27 "Link to this heading") -------------------------------------------------------------------------------- ### Breaking Changes[](#id181 "Link to this heading") * Audit `.rst` and `.py` files and convert all Web3 instance variable names to `w3` to avoid confusion with the `web3` module. ([#1183](https://github.com/ethereum/web3.py/issues/1183) ) * Update dependency requirements: - eth-utils - eth-abi - eth-tester - eth-account - eth-typing ([#2342](https://github.com/ethereum/web3.py/issues/2342) ) * Add `attach_methods()` to `Module` class to facilitate attaching methods to modules. ([#2383](https://github.com/ethereum/web3.py/issues/2383) ) * Move IOError -> OSError ([#2434](https://github.com/ethereum/web3.py/issues/2434) ) ### Documentation Updates[](#id182 "Link to this heading") * Clarify info about Infura filters over HTTP ([#2322](https://github.com/ethereum/web3.py/issues/2322) ) * Document reading private keys from environment variables ([#2380](https://github.com/ethereum/web3.py/issues/2380) ) * Add example for the `construct_sign_and_send_raw_middleware` when connected to a hosted node ([#2410](https://github.com/ethereum/web3.py/issues/2410) ) * Doc fix: Pending transaction filter returns a `TransactionFilter` not a `BlockFilter` ([#2444](https://github.com/ethereum/web3.py/issues/2444) ) ### Features[](#id183 "Link to this heading") * Add ‘get\_text’ method to look up ENS text record values ([#2286](https://github.com/ethereum/web3.py/issues/2286) ) * For `ENS.name()`, validate that the forward resolution returns the same address as provided by the user as per the ENS documentation recommendation for Reverse Resolution. ([#2420](https://github.com/ethereum/web3.py/issues/2420) ) * Add sync chain\_id to `simple_middleware_cache` ([#2425](https://github.com/ethereum/web3.py/issues/2425) ) ### Misc[](#id184 "Link to this heading") * [#2369](https://github.com/ethereum/web3.py/issues/2369) , [#2372](https://github.com/ethereum/web3.py/issues/2372) , [#2418](https://github.com/ethereum/web3.py/issues/2418) v6.0.0-beta.1 (2022-02-28)[](#v6-0-0-beta-1-2022-02-28 "Link to this heading") -------------------------------------------------------------------------------- ### Breaking Changes[](#id185 "Link to this heading") * Update `websockets` dependency to v10+ ([#2324](https://github.com/ethereum/web3.py/issues/2324) ) * Remove support for the unsupported Python 3.6 Also removes outdated Parity tests ([#2343](https://github.com/ethereum/web3.py/issues/2343) ) * Update Sphinx requirement to `>=4.2.0,<5` ([#2362](https://github.com/ethereum/web3.py/issues/2362) ) ### Bugfixes[](#id186 "Link to this heading") * Fix types for `gas`, and `gasLimit`: `Wei -> int`. Also fix types for `effectiveGasPrice`: (`int -> Wei`) ([#2330](https://github.com/ethereum/web3.py/issues/2330) ) ### Features[](#id187 "Link to this heading") * Added session caching to the AsyncHTTPProvider ([#2016](https://github.com/ethereum/web3.py/issues/2016) ) * Add support for Python 3.10 ([#2175](https://github.com/ethereum/web3.py/issues/2175) ) * Added ‘Breaking Changes’ and ‘Deprecations’ categories to our release notes ([#2340](https://github.com/ethereum/web3.py/issues/2340) ) * Add async eth.get\_storage\_at method ([#2350](https://github.com/ethereum/web3.py/issues/2350) ) * Upgrade `jsonschema` version to `>=4.0.0<5` ([#2361](https://github.com/ethereum/web3.py/issues/2361) ) ### Misc[](#id188 "Link to this heading") * [#2353](https://github.com/ethereum/web3.py/issues/2353) , [#2365](https://github.com/ethereum/web3.py/issues/2365) v5.28.0 (2022-02-09)[](#v5-28-0-2022-02-09 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id189 "Link to this heading") * Added Async functions for Geth Personal and Admin modules ([#1413](https://github.com/ethereum/web3.py/issues/1413) ) * async support for formatting, validation, and geth poa middlewares ([#2098](https://github.com/ethereum/web3.py/issues/2098) ) * Calculate a default `maxPriorityFeePerGas` using `eth_feeHistory` when `eth_maxPriorityFeePerGas` is not available, since the latter is not a part of the Ethereum JSON-RPC specs and only supported by certain clients. ([#2259](https://github.com/ethereum/web3.py/issues/2259) ) * Allow NamedTuples in ABI inputs ([#2312](https://github.com/ethereum/web3.py/issues/2312) ) * Add async eth.syncing method ([#2331](https://github.com/ethereum/web3.py/issues/2331) ) ### Bugfixes[](#id190 "Link to this heading") * remove ens.utils.dict\_copy decorator ([#1423](https://github.com/ethereum/web3.py/issues/1423) ) * The exception retry middleware whitelist was missing a comma between `txpool` and `testing` ([#2327](https://github.com/ethereum/web3.py/issues/2327) ) * Properly initialize external modules that do not inherit from the `web3.module.Module` class ([#2328](https://github.com/ethereum/web3.py/issues/2328) ) v5.27.0 (2022-01-31)[](#v5-27-0-2022-01-31 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id191 "Link to this heading") * Added Async functions for Geth TxPool ([#1413](https://github.com/ethereum/web3.py/issues/1413) ) * external modules are no longer required to inherit from the `web3.module.Module` class ([#2304](https://github.com/ethereum/web3.py/issues/2304) ) * Add async eth.get\_logs method ([#2310](https://github.com/ethereum/web3.py/issues/2310) ) * add Async access to default\_account and default\_block ([#2315](https://github.com/ethereum/web3.py/issues/2315) ) * Update eth-tester and eth-account dependencies to pull in bugfix from eth-keys ([#2320](https://github.com/ethereum/web3.py/issues/2320) ) ### Bugfixes[](#id192 "Link to this heading") * Fixed issues with parsing tuples and nested tuples in event logs ([#2211](https://github.com/ethereum/web3.py/issues/2211) ) * In ENS the contract function to resolve an ENS address was being called twice in error. One of those calls was removed. ([#2318](https://github.com/ethereum/web3.py/issues/2318) ) * `to_hexbytes` block formatters no longer throw when value is `None` ([#2321](https://github.com/ethereum/web3.py/issues/2321) ) ### Improved Documentation[](#id193 "Link to this heading") * fix typo in eth.account docs ([#2111](https://github.com/ethereum/web3.py/issues/2111) ) * explicitly add output\_values to contracts example ([#2293](https://github.com/ethereum/web3.py/issues/2293) ) * update imports for AsyncHTTPProvider sample code ([#2302](https://github.com/ethereum/web3.py/issues/2302) ) * fixed broken link to filter schema ([#2303](https://github.com/ethereum/web3.py/issues/2303) ) * add github link to the main docs landing page ([#2313](https://github.com/ethereum/web3.py/issues/2313) ) * fix typos and update referenced geth version ([#2326](https://github.com/ethereum/web3.py/issues/2326) ) ### Misc[](#id194 "Link to this heading") * [#2217](https://github.com/ethereum/web3.py/issues/2217) v5.26.0 (2022-01-06)[](#v5-26-0-2022-01-06 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id195 "Link to this heading") * Add `middlewares` property to `NamedElementOnion` / `web3.middleware_onion`. Returns current middlewares in proper order for importing into a new `Web3` instance ([#2239](https://github.com/ethereum/web3.py/issues/2239) ) * Add async `eth.hashrate` method ([#2243](https://github.com/ethereum/web3.py/issues/2243) ) * Add async `eth.chain_id` method ([#2251](https://github.com/ethereum/web3.py/issues/2251) ) * Add async `eth.mining` method ([#2252](https://github.com/ethereum/web3.py/issues/2252) ) * Add async `eth.get_transaction_receipt` and `eth.wait_for_transaction_receipt` methods ([#2265](https://github.com/ethereum/web3.py/issues/2265) ) * Add async eth.accounts method ([#2284](https://github.com/ethereum/web3.py/issues/2284) ) * Support for attaching external modules to the `Web3` instance when instantiating the `Web3` instance, via the `external_modules` argument, or via the new `attach_modules()` method ([#2288](https://github.com/ethereum/web3.py/issues/2288) ) ### Bugfixes[](#id196 "Link to this heading") * Fixed doctest that wasn’t running in `docs/contracts.rst` ([#2213](https://github.com/ethereum/web3.py/issues/2213) ) * Key mapping fix to eth-tester middleware for access list storage keys ([#2224](https://github.com/ethereum/web3.py/issues/2224) ) * Inherit `Web3` instance middlewares when instantiating `ENS` with `ENS.fromWeb3()` method ([#2239](https://github.com/ethereum/web3.py/issues/2239) ) ### Improved Documentation[](#id197 "Link to this heading") * Fix example docs to show a TransactionNotFound error, instead of None ([#2199](https://github.com/ethereum/web3.py/issues/2199) ) * fix typo in ethpm.rst ([#2277](https://github.com/ethereum/web3.py/issues/2277) ) * Clarify provider usage in Quickstart docs ([#2287](https://github.com/ethereum/web3.py/issues/2287) ) * Address common BSC usage question ([#2289](https://github.com/ethereum/web3.py/issues/2289) ) ### Misc[](#id198 "Link to this heading") * [#1729](https://github.com/ethereum/web3.py/issues/1729) , [#2233](https://github.com/ethereum/web3.py/issues/2233) , [#2242](https://github.com/ethereum/web3.py/issues/2242) , [#2260](https://github.com/ethereum/web3.py/issues/2260) , [#2261](https://github.com/ethereum/web3.py/issues/2261) , [#2283](https://github.com/ethereum/web3.py/issues/2283) v5.25.0 (2021-11-19)[](#v5-25-0-2021-11-19 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id199 "Link to this heading") * Support for `w3.eth.get_raw_transaction_by_block`, and async support for `w3.eth.get_raw_transaction_by_block` ([#2209](https://github.com/ethereum/web3.py/issues/2209) ) ### Bugfixes[](#id200 "Link to this heading") * BadResponseFormat error thrown instead of KeyError when a response gets sent back without a `result` key. ([#2188](https://github.com/ethereum/web3.py/issues/2188) ) ### Improved Documentation[](#id201 "Link to this heading") * Correct link to Websocket library documentation ([#2173](https://github.com/ethereum/web3.py/issues/2173) ) * Doc update to make it clearer that enable\_unstable\_package\_management() method is on the web3 instance ([#2208](https://github.com/ethereum/web3.py/issues/2208) ) ### Misc[](#id202 "Link to this heading") * [#2102](https://github.com/ethereum/web3.py/issues/2102) , [#2179](https://github.com/ethereum/web3.py/issues/2179) , [#2191](https://github.com/ethereum/web3.py/issues/2191) , [#2201](https://github.com/ethereum/web3.py/issues/2201) , [#2205](https://github.com/ethereum/web3.py/issues/2205) , [#2212](https://github.com/ethereum/web3.py/issues/2212) v5.24.0 (2021-09-27)[](#v5-24-0-2021-09-27 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id203 "Link to this heading") * Add async `eth.send_raw_transaction` method ([#2135](https://github.com/ethereum/web3.py/issues/2135) ) * Updated eth-account version to v0.5.6 - adds support for signing typed transactions without needing to explicitly set the transaction type and now accepts correct JSON-RPC structure for accessList for typed transactions ([#2157](https://github.com/ethereum/web3.py/issues/2157) ) ### Bugfixes[](#id204 "Link to this heading") * Encode block\_count as hex before making eth\_feeHistory RPC call ([#2117](https://github.com/ethereum/web3.py/issues/2117) ) ### Improved Documentation[](#id205 "Link to this heading") * Fix typo in AsyncHTTPProvider docs ([#2131](https://github.com/ethereum/web3.py/issues/2131) ) * Update AsyncHTTPProvider doc Supported Methods to include `web3.eth.send_raw_transaction()`. ([#2135](https://github.com/ethereum/web3.py/issues/2135) ) * Improve messaging around usage and implementation questions, directing users to the appropriate channel ([#2138](https://github.com/ethereum/web3.py/issues/2138) ) * Clarify some contract `ValueError` error messages. ([#2146](https://github.com/ethereum/web3.py/issues/2146) ) * Updated docs for w3.eth.account.sign\_transaction to reflect that transaction type is no longer needed to successfully sign typed transactions and to illustrate how to structure an optional accessList parameter in a typed transaction ([#2157](https://github.com/ethereum/web3.py/issues/2157) ) ### Misc[](#id206 "Link to this heading") * [#2105](https://github.com/ethereum/web3.py/issues/2105) v5.23.1 (2021-08-27)[](#v5-23-1-2021-08-27 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id207 "Link to this heading") * Add constants for the zero address, zero hash, max int, and wei per ether. ([#2109](https://github.com/ethereum/web3.py/issues/2109) ) ### Improved Documentation[](#id208 "Link to this heading") * Renamed “1559 transaction” to “dynamic fee transaction” where appropriate to keep consistency among the general code base for 1559 transaction (type=2) naming ([#2118](https://github.com/ethereum/web3.py/issues/2118) ) * Update AsyncHTTPProvider doc example to include modules and middlewares keyword arguments ([#2123](https://github.com/ethereum/web3.py/issues/2123) ) ### Misc[](#id209 "Link to this heading") * [#2110](https://github.com/ethereum/web3.py/issues/2110) , [#2118](https://github.com/ethereum/web3.py/issues/2118) , [#2122](https://github.com/ethereum/web3.py/issues/2122) v5.23.0 (2021-08-12)[](#v5-23-0-2021-08-12 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id210 "Link to this heading") * Add support for eth\_feeHistory RPC method ([#2038](https://github.com/ethereum/web3.py/issues/2038) ) * Add support for eth\_maxPriorityFeePerGas RPC method ([#2100](https://github.com/ethereum/web3.py/issues/2100) ) ### Bugfixes[](#id211 "Link to this heading") * Hot fix for string interpolation issue with contract function call decoding exception to facilitate extracting a meaningful message from the eth\_call response ([#2096](https://github.com/ethereum/web3.py/issues/2096) ) * Bypass adding a `gasPrice` via the gas price strategy, if one is set, when EIP-1559 transaction params are used for `send_transaction` ([#2099](https://github.com/ethereum/web3.py/issues/2099) ) ### Improved Documentation[](#id212 "Link to this heading") * Update feeHistory docs ([#2104](https://github.com/ethereum/web3.py/issues/2104) ) v5.22.0 (2021-08-02)[](#v5-22-0-2021-08-02 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id213 "Link to this heading") * Add support for eth\_getRawTransactionByHash RPC method ([#2039](https://github.com/ethereum/web3.py/issues/2039) ) * Add AsyncNet module ([#2044](https://github.com/ethereum/web3.py/issues/2044) ) * Add async `eth.get_balance`, `eth.get_code`, `eth.get_transaction_count` methods. ([#2056](https://github.com/ethereum/web3.py/issues/2056) ) * eth\_signTransaction support for eip-1559 params ‘maxFeePerGas’ and ‘maxPriorityFeePerGas’ ([#2082](https://github.com/ethereum/web3.py/issues/2082) ) * Add support for async `w3.eth.call`. ([#2083](https://github.com/ethereum/web3.py/issues/2083) ) ### Bugfixes[](#id214 "Link to this heading") * If a transaction hash was passed as a string rather than a HexByte to `w3.eth.wait_for_transaction_receipt`, and the time was exhausted before the transaction is in the chain, the error being raised was a TypeError instead of the correct TimeExhausted error. This is because the `to_hex` method in the TimeExhausted error message expects a primitive as the first argument, and a string doesn’t qualify as a primitive. Fixed by converting the transaction\_hash to HexBytes instead. ([#2068](https://github.com/ethereum/web3.py/issues/2068) ) * Hot fix for a string interpolation issue in message when BadFunctionCallOutput is raised for call\_contract\_function() ([#2069](https://github.com/ethereum/web3.py/issues/2069) ) * `fill_transaction_defaults()` no longer sets a default `gasPrice` if 1559 fees are present in the transaction parameters. This fixes sign-and-send middleware issues with 1559 fees. ([#2092](https://github.com/ethereum/web3.py/issues/2092) ) ### Improved Documentation[](#id215 "Link to this heading") * Clarify that `send_transaction`, `modify_transaction`, and `replace_transaction` return HexByte objects instead of strings. ([#2058](https://github.com/ethereum/web3.py/issues/2058) ) * Added troubleshooting section for Microsoft Visual C++ error on Windows machines ([#2077](https://github.com/ethereum/web3.py/issues/2077) ) * Updated the sign-and-send middleware docs to include EIP-1559 as well as legacy transaction examples ([#2092](https://github.com/ethereum/web3.py/issues/2092) ) ### Misc[](#id216 "Link to this heading") * [#2073](https://github.com/ethereum/web3.py/issues/2073) , [#2080](https://github.com/ethereum/web3.py/issues/2080) , [#2085](https://github.com/ethereum/web3.py/issues/2085) v5.21.0 (2021-07-12)[](#v5-21-0-2021-07-12 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id217 "Link to this heading") * Adds support for EIP 1559 transaction keys: maxFeePerGas and maxPriorityFeePerGas ([#2060](https://github.com/ethereum/web3.py/issues/2060) ) ### Bugfixes[](#id218 "Link to this heading") * Bugfix where an error response got passed to a function expecting a block identifier. Split out null result formatters from the error formatters and added some tests. ([#2022](https://github.com/ethereum/web3.py/issues/2022) ) * Fix broken tests and use the new 1559 params for most of our test transactions. ([#2053](https://github.com/ethereum/web3.py/issues/2053) ) * Set a default maxFeePerGas value consistent with Geth ([#2055](https://github.com/ethereum/web3.py/issues/2055) ) * Fix bug in geth PoA middleware where a `None` response should throw a `BlockNotFound` error, but was instead throwing an `AttributeError` ([#2064](https://github.com/ethereum/web3.py/issues/2064) ) ### Improved Documentation[](#id219 "Link to this heading") * Added general documentation on unit and integration testing and how to contribute to our test suite. ([#2053](https://github.com/ethereum/web3.py/issues/2053) ) v5.20.1 (2021-07-01)[](#v5-20-1-2021-07-01 "Link to this heading") -------------------------------------------------------------------- ### Bugfixes[](#id220 "Link to this heading") * Have the geth dev IPC auto connection check for the `WEB3_PROVIDER_URI` environment variable. ([#2023](https://github.com/ethereum/web3.py/issues/2023) ) ### Improved Documentation[](#id221 "Link to this heading") * Remove reference to allowing multiple providers in docs ([#2018](https://github.com/ethereum/web3.py/issues/2018) ) * Update “Contract Deployment Example” docs to use `py-solc-x` as `solc` is no longer maintained. ([#2020](https://github.com/ethereum/web3.py/issues/2020) ) * Detail using unreleased Geth builds in CI ([#2037](https://github.com/ethereum/web3.py/issues/2037) ) * Clarify that a missing trie node error could occur when using `block_identifier` with `.call()` on a node that isn’t running in archive mode ([#2048](https://github.com/ethereum/web3.py/issues/2048) ) ### Misc[](#id222 "Link to this heading") * [#1938](https://github.com/ethereum/web3.py/issues/1938) , [#2015](https://github.com/ethereum/web3.py/issues/2015) , [#2021](https://github.com/ethereum/web3.py/issues/2021) , [#2025](https://github.com/ethereum/web3.py/issues/2025) , [#2028](https://github.com/ethereum/web3.py/issues/2028) , [#2029](https://github.com/ethereum/web3.py/issues/2029) , [#2035](https://github.com/ethereum/web3.py/issues/2035) v5.20.0 (2021-06-09)[](#v5-20-0-2021-06-09 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id223 "Link to this heading") * Add new AsyncHTTPProvider. No middleware or session caching support yet. Also adds async `w3.eth.gas_price`, and async `w3.isConnected()` methods. ([#1978](https://github.com/ethereum/web3.py/issues/1978) ) * Add ability for AsyncHTTPProvider to accept middleware Also adds async gas\_price\_strategy middleware, and moves gas estimate to middleware. AsyncEthereumTesterProvider now inherits from AsyncBase ([#1999](https://github.com/ethereum/web3.py/issues/1999) ) * Support state\_override in contract function call. ([#2005](https://github.com/ethereum/web3.py/issues/2005) ) ### Bugfixes[](#id224 "Link to this heading") * Test ethpm caching + bump Sphinx version. ([#1977](https://github.com/ethereum/web3.py/issues/1977) ) ### Improved Documentation[](#id225 "Link to this heading") * Clarify solidityKeccak documentation. ([#1971](https://github.com/ethereum/web3.py/issues/1971) ) * Improve contributor documentation context and ordering. ([#2008](https://github.com/ethereum/web3.py/issues/2008) ) * Add docs for unstable AsyncHTTPProvider ([#2017](https://github.com/ethereum/web3.py/issues/2017) ) ### Misc[](#id226 "Link to this heading") * [#1979](https://github.com/ethereum/web3.py/issues/1979) , [#1980](https://github.com/ethereum/web3.py/issues/1980) , [#1993](https://github.com/ethereum/web3.py/issues/1993) , [#2002](https://github.com/ethereum/web3.py/issues/2002) v5.19.0 (2021-04-28)[](#v5-19-0-2021-04-28 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id227 "Link to this heading") * Handle optional `eth_call` state override param. ([#1921](https://github.com/ethereum/web3.py/issues/1921) ) * Add list\_storage\_keys deprecate listStorageKeys ([#1944](https://github.com/ethereum/web3.py/issues/1944) ) * Add net\_peers deprecate netPeers ([#1946](https://github.com/ethereum/web3.py/issues/1946) ) * Add trace\_replay\_transaction deprecate traceReplayTransaction ([#1949](https://github.com/ethereum/web3.py/issues/1949) ) * Add add\_reserved\_peer deprecate addReservedPeer ([#1951](https://github.com/ethereum/web3.py/issues/1951) ) * Add `parity.set_mode`, deprecate `parity.setMode` ([#1954](https://github.com/ethereum/web3.py/issues/1954) ) * Add `parity.trace_raw_transaction`, deprecate `parity.traceRawTransaction` ([#1955](https://github.com/ethereum/web3.py/issues/1955) ) * Add `parity.trace_call`, deprecate `parity.traceCall` ([#1957](https://github.com/ethereum/web3.py/issues/1957) ) * Add trace\_filter deprecate traceFilter ([#1960](https://github.com/ethereum/web3.py/issues/1960) ) * Add trace\_block, deprecate traceBlock ([#1961](https://github.com/ethereum/web3.py/issues/1961) ) * Add trace\_replay\_block\_transactions, deprecate traceReplayBlockTransactions ([#1962](https://github.com/ethereum/web3.py/issues/1962) ) * Add `parity.trace_transaction`, deprecate `parity.traceTransaction` ([#1963](https://github.com/ethereum/web3.py/issues/1963) ) ### Improved Documentation[](#id228 "Link to this heading") * Document `eth_call` state overrides. ([#1965](https://github.com/ethereum/web3.py/issues/1965) ) ### Misc[](#id229 "Link to this heading") * [#1774](https://github.com/ethereum/web3.py/issues/1774) , [#1805](https://github.com/ethereum/web3.py/issues/1805) , [#1945](https://github.com/ethereum/web3.py/issues/1945) , [#1964](https://github.com/ethereum/web3.py/issues/1964) v5.18.0 (2021-04-08)[](#v5-18-0-2021-04-08 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id230 "Link to this heading") * Add `w3.eth.modify_transaction` deprecate `w3.eth.modifyTransaction` ([#1886](https://github.com/ethereum/web3.py/issues/1886) ) * Add `w3.eth.get_transaction_receipt`, deprecate `w3.eth.getTransactionReceipt` ([#1893](https://github.com/ethereum/web3.py/issues/1893) ) * Add `w3.eth.wait_for_transaction_receipt` deprecate `w3.eth.waitForTransactionReceipt` ([#1896](https://github.com/ethereum/web3.py/issues/1896) ) * Add `w3.eth.set_contract_factory` deprecate `w3.eth.setContractFactory` ([#1900](https://github.com/ethereum/web3.py/issues/1900) ) * Add `w3.eth.generate_gas_price` deprecate `w3.eth.generateGasPrice` ([#1905](https://github.com/ethereum/web3.py/issues/1905) ) * Add `w3.eth.set_gas_price_strategy` deprecate `w3.eth.setGasPriceStrategy` ([#1906](https://github.com/ethereum/web3.py/issues/1906) ) * Add `w3.eth.estimate_gas` deprecate `w3.eth.estimateGas` ([#1913](https://github.com/ethereum/web3.py/issues/1913) ) * Add `w3.eth.sign_typed_data` deprecate `w3.eth.signTypedData` ([#1915](https://github.com/ethereum/web3.py/issues/1915) ) * Add `w3.eth.get_filter_changes` deprecate `w3.eth.getFilterChanges` ([#1916](https://github.com/ethereum/web3.py/issues/1916) ) * Add `eth.get_filter_logs`, deprecate `eth.getFilterLogs` ([#1919](https://github.com/ethereum/web3.py/issues/1919) ) * Add `eth.uninstall_filter`, deprecate `eth.uninstallFilter` ([#1920](https://github.com/ethereum/web3.py/issues/1920) ) * Add `w3.eth.get_logs` deprecate `w3.eth.getLogs` ([#1925](https://github.com/ethereum/web3.py/issues/1925) ) * Add `w3.eth.submit_hashrate` deprecate `w3.eth.submitHashrate` ([#1926](https://github.com/ethereum/web3.py/issues/1926) ) * Add `w3.eth.submit_work` deprecate `w3.eth.submitWork` ([#1927](https://github.com/ethereum/web3.py/issues/1927) ) * Add `w3.eth.get_work`, deprecate `w3.eth.getWork` ([#1934](https://github.com/ethereum/web3.py/issues/1934) ) * Adds public get\_block\_number method. ([#1937](https://github.com/ethereum/web3.py/issues/1937) ) ### Improved Documentation[](#id231 "Link to this heading") * Add ABI type examples to docs ([#1890](https://github.com/ethereum/web3.py/issues/1890) ) * Promote the new Ethereum Python Discord server on the README. ([#1898](https://github.com/ethereum/web3.py/issues/1898) ) * Escape reserved characters in install script of Contributing docs. ([#1909](https://github.com/ethereum/web3.py/issues/1909) ) * Add detailed event filtering examples. ([#1910](https://github.com/ethereum/web3.py/issues/1910) ) * Add docs example for tuning log levels. ([#1928](https://github.com/ethereum/web3.py/issues/1928) ) * Add some performance tips in troubleshooting docs. ([#1929](https://github.com/ethereum/web3.py/issues/1929) ) * Add existing contract interaction to docs examples. ([#1933](https://github.com/ethereum/web3.py/issues/1933) ) * Replace Gitter links with the Python Discord server. ([#1936](https://github.com/ethereum/web3.py/issues/1936) ) ### Misc[](#id232 "Link to this heading") * [#1887](https://github.com/ethereum/web3.py/issues/1887) , [#1907](https://github.com/ethereum/web3.py/issues/1907) , [#1917](https://github.com/ethereum/web3.py/issues/1917) , [#1930](https://github.com/ethereum/web3.py/issues/1930) , [#1935](https://github.com/ethereum/web3.py/issues/1935) v5.17.0 (2021-02-24)[](#v5-17-0-2021-02-24 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id233 "Link to this heading") * Added `get_transaction_count`, and deprecated `getTransactionCount` ([#1844](https://github.com/ethereum/web3.py/issues/1844) ) * Add `w3.eth.send_transaction`, deprecate `w3.eth.sendTransaction` ([#1878](https://github.com/ethereum/web3.py/issues/1878) ) * Add `web3.eth.sign_transaction`, deprecate `web3.eth.signTransaction` ([#1879](https://github.com/ethereum/web3.py/issues/1879) ) * Add `w3.eth.send_raw_transaction`, deprecate `w3.eth.sendRawTransaction` ([#1880](https://github.com/ethereum/web3.py/issues/1880) ) * Add `w3.eth.replace_transaction` deprecate `w3.eth.replaceTransaction` ([#1882](https://github.com/ethereum/web3.py/issues/1882) ) ### Improved Documentation[](#id234 "Link to this heading") * Fix return type of `send_transaction` in docs. ([#686](https://github.com/ethereum/web3.py/issues/686) ) v5.16.0 (2021-02-04)[](#v5-16-0-2021-02-04 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id235 "Link to this heading") * Added `get_block_transaction_count`, and deprecated `getBlockTransactionCount` ([#1841](https://github.com/ethereum/web3.py/issues/1841) ) * Move `defaultAccount` to `default_account`. Deprecate `defaultAccount`. ([#1848](https://github.com/ethereum/web3.py/issues/1848) ) * Add `eth.default_block`, deprecate `eth.defaultBlock`. Also adds `parity.default_block`, and deprecates `parity.defaultBlock`. ([#1849](https://github.com/ethereum/web3.py/issues/1849) ) * Add `eth.gas_price`, deprecate `eth.gasPrice` ([#1850](https://github.com/ethereum/web3.py/issues/1850) ) * Added `eth.block_number` property. Deprecated `eth.blockNumber` ([#1851](https://github.com/ethereum/web3.py/issues/1851) ) * Add `eth.chain_id`, deprecate `eth.chainId` ([#1852](https://github.com/ethereum/web3.py/issues/1852) ) * Add `eth.protocol_version`, deprecate `eth.protocolVersion` ([#1853](https://github.com/ethereum/web3.py/issues/1853) ) * Add `eth.get_code`, deprecate `eth.getCode` ([#1856](https://github.com/ethereum/web3.py/issues/1856) ) * Deprecate `eth.getProof`, add `eth.get_proof` ([#1857](https://github.com/ethereum/web3.py/issues/1857) ) * Add `eth.get_transaction`, deprecate `eth.getTransaction` ([#1858](https://github.com/ethereum/web3.py/issues/1858) ) * Add `eth.get_transaction_by_block`, deprecate `eth.getTransactionByBlock` ([#1859](https://github.com/ethereum/web3.py/issues/1859) ) * Add get\_uncle\_by\_block, deprecate getUncleByBlock ([#1862](https://github.com/ethereum/web3.py/issues/1862) ) * Add get\_uncle\_count, deprecate getUncleCount ([#1863](https://github.com/ethereum/web3.py/issues/1863) ) ### Bugfixes[](#id236 "Link to this heading") * Fix event filter creation if the event ABI contains a `values` key. ([#1807](https://github.com/ethereum/web3.py/issues/1807) ) ### Improved Documentation[](#id237 "Link to this heading") * Remove v5 breaking changes link from the top of the release notes. ([#1837](https://github.com/ethereum/web3.py/issues/1837) ) * Add account creation troubleshooting docs. ([#1855](https://github.com/ethereum/web3.py/issues/1855) ) * Document passing a struct into a contract function. ([#1860](https://github.com/ethereum/web3.py/issues/1860) ) * Add instance configuration troubleshooting docs. ([#1865](https://github.com/ethereum/web3.py/issues/1865) ) * Clarify nonce lookup in sendRawTransaction docs. ([#1866](https://github.com/ethereum/web3.py/issues/1866) ) * Updated docs for web3.eth methods: eth.getTransactionReceipt and eth.waitForTransactionReceipt ([#1868](https://github.com/ethereum/web3.py/issues/1868) ) v5.15.0 (2021-01-15)[](#v5-15-0-2021-01-15 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id238 "Link to this heading") * Add `get_storage_at` method and deprecate `getStorageAt`. ([#1828](https://github.com/ethereum/web3.py/issues/1828) ) * Add `eth.get_block` method and deprecate `eth.getBlock`. ([#1829](https://github.com/ethereum/web3.py/issues/1829) ) ### Bugfixes[](#id239 "Link to this heading") * PR #1585 changed the error that was coming back from eth-tester when the Revert opcode was called, which broke some tests in downstream libraries. This PR reverts back to raising the original error. ([#1813](https://github.com/ethereum/web3.py/issues/1813) ) * Added a new `ContractLogicError` for when a contract reverts a transaction. `ContractLogicError` will replace `SolidityError`, in v6. ([#1814](https://github.com/ethereum/web3.py/issues/1814) ) ### Improved Documentation[](#id240 "Link to this heading") * Introduce Beacon API documentation ([#1836](https://github.com/ethereum/web3.py/issues/1836) ) ### Misc[](#id241 "Link to this heading") * [#1602](https://github.com/ethereum/web3.py/issues/1602) , [#1827](https://github.com/ethereum/web3.py/issues/1827) , [#1831](https://github.com/ethereum/web3.py/issues/1831) , [#1833](https://github.com/ethereum/web3.py/issues/1833) , [#1834](https://github.com/ethereum/web3.py/issues/1834) v5.14.0 (2021-01-05)[](#v5-14-0-2021-01-05 "Link to this heading") -------------------------------------------------------------------- ### Bugfixes[](#id242 "Link to this heading") * Remove docs/web3.\* from the gitignore to allow for the beacon docs to be added to git, and add `beacon` to the default web3 modules that get loaded. ([#1824](https://github.com/ethereum/web3.py/issues/1824) ) * Remove auto-documenting from the Beacon API ([#1825](https://github.com/ethereum/web3.py/issues/1825) ) ### Features[](#id243 "Link to this heading") * Introduce experimental Ethereum 2.0 beacon node API ([#1758](https://github.com/ethereum/web3.py/issues/1758) ) * Add new get\_balance method on Eth class. Deprecated getBalance. ([#1806](https://github.com/ethereum/web3.py/issues/1806) ) ### Misc[](#id244 "Link to this heading") * [#1815](https://github.com/ethereum/web3.py/issues/1815) , [#1816](https://github.com/ethereum/web3.py/issues/1816) v5.13.1 (2020-12-03)[](#v5-13-1-2020-12-03 "Link to this heading") -------------------------------------------------------------------- ### Bugfixes[](#id245 "Link to this heading") * Handle revert reason parsing for Ganache ([#1794](https://github.com/ethereum/web3.py/issues/1794) ) ### Improved Documentation[](#id246 "Link to this heading") * Document Geth and Parity/OpenEthereum fixture generation ([#1787](https://github.com/ethereum/web3.py/issues/1787) ) ### Misc[](#id247 "Link to this heading") * [#1778](https://github.com/ethereum/web3.py/issues/1778) , [#1780](https://github.com/ethereum/web3.py/issues/1780) , [#1790](https://github.com/ethereum/web3.py/issues/1790) , [#1791](https://github.com/ethereum/web3.py/issues/1791) , [#1796](https://github.com/ethereum/web3.py/issues/1796) v5.13.0 (2020-10-29)[](#v5-13-0-2020-10-29 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id248 "Link to this heading") * Raise SolidityError exceptions that contain the revert reason when a call fails. ([#941](https://github.com/ethereum/web3.py/issues/941) ) ### Bugfixes[](#id249 "Link to this heading") * Update eth-tester dependency to fix tester environment install version conflict. ([#1782](https://github.com/ethereum/web3.py/issues/1782) ) ### Misc[](#id250 "Link to this heading") * [#1757](https://github.com/ethereum/web3.py/issues/1757) , [#1767](https://github.com/ethereum/web3.py/issues/1767) v5.12.3 (2020-10-21)[](#v5-12-3-2020-10-21 "Link to this heading") -------------------------------------------------------------------- ### Misc[](#id251 "Link to this heading") * [#1752](https://github.com/ethereum/web3.py/issues/1752) , [#1759](https://github.com/ethereum/web3.py/issues/1759) , [#1773](https://github.com/ethereum/web3.py/issues/1773) , [#1775](https://github.com/ethereum/web3.py/issues/1775) v5.12.2 (2020-10-12)[](#v5-12-2-2020-10-12 "Link to this heading") -------------------------------------------------------------------- ### Bugfixes[](#id252 "Link to this heading") * Address the use of multiple providers in the docs ([#1701](https://github.com/ethereum/web3.py/issues/1701) ) * Remove stale connection errors from docs ([#1737](https://github.com/ethereum/web3.py/issues/1737) ) * Allow ENS name resolution for methods that use the `Method` class ([#1749](https://github.com/ethereum/web3.py/issues/1749) ) ### Misc[](#id253 "Link to this heading") * [#1727](https://github.com/ethereum/web3.py/issues/1727) , [#1728](https://github.com/ethereum/web3.py/issues/1728) , [#1733](https://github.com/ethereum/web3.py/issues/1733) , [#1735](https://github.com/ethereum/web3.py/issues/1735) , [#1741](https://github.com/ethereum/web3.py/issues/1741) , [#1746](https://github.com/ethereum/web3.py/issues/1746) , [#1748](https://github.com/ethereum/web3.py/issues/1748) , [#1753](https://github.com/ethereum/web3.py/issues/1753) , [#1768](https://github.com/ethereum/web3.py/issues/1768) v5.12.1 (2020-09-02)[](#v5-12-1-2020-09-02 "Link to this heading") -------------------------------------------------------------------- ### Misc[](#id254 "Link to this heading") * [#1708](https://github.com/ethereum/web3.py/issues/1708) , [#1709](https://github.com/ethereum/web3.py/issues/1709) , [#1715](https://github.com/ethereum/web3.py/issues/1715) , [#1722](https://github.com/ethereum/web3.py/issues/1722) , [#1724](https://github.com/ethereum/web3.py/issues/1724) v5.12.0 (2020-07-16)[](#v5-12-0-2020-07-16 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id255 "Link to this heading") * Update web3.pm and ethpm module to EthPM v3 specification. ([#1652](https://github.com/ethereum/web3.py/issues/1652) ) * Allow consumer to initialize HttpProvider with their own requests.Session. This allows the HttpAdapter connection pool to be tuned as desired. ([#1469](https://github.com/ethereum/web3.py/issues/1469) ) ### Improved Documentation[](#id256 "Link to this heading") * Use ethpm v3 packages in examples documentation. ([#1683](https://github.com/ethereum/web3.py/issues/1683) ) * Modernize the deploy contract example. ([#1679](https://github.com/ethereum/web3.py/issues/1679) ) * Add contribution guidelines and a code of conduct. ([#1691](https://github.com/ethereum/web3.py/issues/1691) ) ### Misc[](#id257 "Link to this heading") * [#1687](https://github.com/ethereum/web3.py/issues/1687) * [#1690](https://github.com/ethereum/web3.py/issues/1690) v5.12.0-beta.3 (2020-07-15)[](#v5-12-0-beta-3-2020-07-15 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id258 "Link to this heading") * Include ethpm-spec solidity examples in distribution. ([#1686](https://github.com/ethereum/web3.py/issues/1686) ) v5.12.0-beta.2 (2020-07-14)[](#v5-12-0-beta-2-2020-07-14 "Link to this heading") ---------------------------------------------------------------------------------- ### Bugfixes[](#id259 "Link to this heading") * Support ethpm-spec submodule in distributions. ([#1682](https://github.com/ethereum/web3.py/issues/1682) ) ### Improved Documentation[](#id260 "Link to this heading") * Modernize the deploy contract example. ([#1679](https://github.com/ethereum/web3.py/issues/1679) ) * Use ethpm v3 packages in examples documentation. ([#1683](https://github.com/ethereum/web3.py/issues/1683) ) v5.12.0-beta.1 (2020-07-09)[](#v5-12-0-beta-1-2020-07-09 "Link to this heading") ---------------------------------------------------------------------------------- ### Features[](#id261 "Link to this heading") * Allow consumer to initialize HttpProvider with their own requests.Session. This allows the HttpAdapter connection pool to be tuned as desired. ([#1469](https://github.com/ethereum/web3.py/issues/1469) ) * Update web3.pm and ethpm module to EthPM v3 specification. ([#1652](https://github.com/ethereum/web3.py/issues/1652) ) ### Bugfixes[](#id262 "Link to this heading") * Update outdated reference url in ethpm docs and tests. ([#1680](https://github.com/ethereum/web3.py/issues/1680) ) ### Improved Documentation[](#id263 "Link to this heading") * Add a `getBalance()` example and provide more context for using the fromWei and toWei utility methods. ([#1676](https://github.com/ethereum/web3.py/issues/1676) ) * Overhaul the Overview documentation to provide a tour of major features. ([#1681](https://github.com/ethereum/web3.py/issues/1681) ) v5.11.1 (2020-06-17)[](#v5-11-1-2020-06-17 "Link to this heading") -------------------------------------------------------------------- ### Bugfixes[](#id264 "Link to this heading") * Added formatter rules for eth\_tester middleware to allow `getBalance()` by using integer block numbers ([#1660](https://github.com/ethereum/web3.py/issues/1660) ) * Fix type annotations within the `eth.py` module. Several arguments that defaulted to `None` were not declared `Optional`. ([#1668](https://github.com/ethereum/web3.py/issues/1668) ) * Fix type annotation warning when using string URI to instantiate an HTTP or WebsocketProvider. ([#1669](https://github.com/ethereum/web3.py/issues/1669) ) * Fix type annotations within the `web3` modules. Several arguments that defaulted to `None` were not declared `Optional`. ([#1670](https://github.com/ethereum/web3.py/issues/1670) ) ### Improved Documentation[](#id265 "Link to this heading") * Breaks up links into three categories (Intro, Guides, and API) and adds content to the index page: a lib introduction and some “Getting Started” links. ([#1671](https://github.com/ethereum/web3.py/issues/1671) ) * Fills in some gaps in the Quickstart guide and adds provider connection details for local nodes. ([#1673](https://github.com/ethereum/web3.py/issues/1673) ) v5.11.0 (2020-06-03)[](#v5-11-0-2020-06-03 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id266 "Link to this heading") * Accept a block identifier in the `Contract.estimateGas` method. Includes a related upgrade of eth-tester to v0.5.0-beta.1. ([#1639](https://github.com/ethereum/web3.py/issues/1639) ) * Introduce a more specific validation error, `ExtraDataLengthError`. This enables tools to detect when someone may be connected to a POA network, for example, and provide a smoother developer experience. ([#1666](https://github.com/ethereum/web3.py/issues/1666) ) ### Bugfixes[](#id267 "Link to this heading") * Correct the type annotations of FilterParams.address ([#1664](https://github.com/ethereum/web3.py/issues/1664) ) ### Improved Documentation[](#id268 "Link to this heading") * Corrects the return value of `getTransactionReceipt`, description of caching middleware, and deprecated method names. ([#1663](https://github.com/ethereum/web3.py/issues/1663) ) * Corrects documentation of websocket timeout configuration. ([#1665](https://github.com/ethereum/web3.py/issues/1665) ) v5.10.0 (2020-05-18)[](#v5-10-0-2020-05-18 "Link to this heading") -------------------------------------------------------------------- ### Features[](#id269 "Link to this heading") * An update of `eth-tester` includes a change of the default fork from Constantinople to Muir Glacier. [#1636](https://github.com/ethereum/web3.py/issues/1636) ### Bugfixes[](#id270 "Link to this heading") * `my_contract.events.MyEvent` was incorrectly annotated so that `MyEvent` was marked as a `ContractEvent` instance. Fixed to be a class type, i.e., `Type[ContractEvent]`. ([#1646](https://github.com/ethereum/web3.py/issues/1646) ) * IPCProvider correctly handled `pathlib.Path` input, but warned against its type. Fixed to permit Path objects in addition to strings. ([#1647](https://github.com/ethereum/web3.py/issues/1647) ) ### Misc[](#id271 "Link to this heading") * [#1636](https://github.com/ethereum/web3.py/issues/1636) v5.9.0 (2020-04-30)[](#v5-9-0-2020-04-30 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id272 "Link to this heading") * Upgrade eth-account to use v0.5.2+. eth-account 0.5.2 adds support for hd accounts Also had to pin eth-keys to get dependencies to resolve. ([#1622](https://github.com/ethereum/web3.py/issues/1622) ) ### Bugfixes[](#id273 "Link to this heading") * Fix local\_filter\_middleware new entries bug ([#1514](https://github.com/ethereum/web3.py/issues/1514) ) * ENS `name` and ENS `address` can return `None`. Fixes return types. ([#1633](https://github.com/ethereum/web3.py/issues/1633) ) v5.8.0 (2020-04-23)[](#v5-8-0-2020-04-23 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id274 "Link to this heading") * Introduced `list_wallets` method to the `GethPersonal` class. ([#1516](https://github.com/ethereum/web3.py/issues/1516) ) * Added block\_identifier parameter to ContractConstructor.estimateGas method. ([#1588](https://github.com/ethereum/web3.py/issues/1588) ) * Add snake\_case methods to Geth and Parity Personal Modules. Deprecate camelCase methods. ([#1589](https://github.com/ethereum/web3.py/issues/1589) ) * Added new weighted keyword argument to the time based gas price strategy. If `True`, it will more give more weight to more recent block times. ([#1614](https://github.com/ethereum/web3.py/issues/1614) ) * Adds support for Solidity’s new(ish) receive function. Adds a new contract API that mirrors the existing fallback API: `contract.receive` ([#1623](https://github.com/ethereum/web3.py/issues/1623) ) ### Bugfixes[](#id275 "Link to this heading") * Fixed hasattr overloader method in the web3.ContractEvent, web3.ContractFunction, and web3.ContractCaller classes by implementing a try/except handler that returns False if an exception is raised in the \_\_getattr\_\_ overloader method (since \_\_getattr\_\_ HAS to be called in every \_\_hasattr\_\_ call). Created two new Exception classes, ‘ABIEventFunctionNotFound’ and ‘ABIFunctionNotFound’, which inherit from both AttributeError and MismatchedABI, and replaced the MismatchedABI raises in ContractEvent, ContractFunction, and ContractCaller with a raise to the created class in the \_\_getattr\_\_ overloader method of the object. ([#1594](https://github.com/ethereum/web3.py/issues/1594) ) * Change return type of rpc\_gas\_price\_strategy from int to Wei ([#1612](https://github.com/ethereum/web3.py/issues/1612) ) ### Improved Documentation[](#id276 "Link to this heading") * Fix typo in “Internals” docs. Changed asyncronous –> asynchronous ([#1607](https://github.com/ethereum/web3.py/issues/1607) ) * Improve documentation that introduces and troubleshoots Providers. ([#1609](https://github.com/ethereum/web3.py/issues/1609) ) * Add documentation for when to use each transaction method. ([#1610](https://github.com/ethereum/web3.py/issues/1610) ) * Remove incorrect web3 for w3 in doc example ([#1615](https://github.com/ethereum/web3.py/issues/1615) ) * Add examples for using web3.contract via the ethpm module. ([#1617](https://github.com/ethereum/web3.py/issues/1617) ) * Add dark mode to documentation. Also fixes a bunch of formatting issues in docs. ([#1626](https://github.com/ethereum/web3.py/issues/1626) ) ### Misc[](#id277 "Link to this heading") * [#1545](https://github.com/ethereum/web3.py/issues/1545) v5.7.0 (2020-03-16)[](#v5-7-0-2020-03-16 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id278 "Link to this heading") * Add snake\_case methods for the net module Also moved net module to use ModuleV2 instead of Module ([#1592](https://github.com/ethereum/web3.py/issues/1592) ) ### Bugfixes[](#id279 "Link to this heading") * Fix return type of eth\_getCode. Changed from Hexstr to HexBytes. ([#1601](https://github.com/ethereum/web3.py/issues/1601) ) ### Misc[](#id280 "Link to this heading") * [#1590](https://github.com/ethereum/web3.py/issues/1590) v5.6.0 (2020-02-26)[](#v5-6-0-2020-02-26 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id281 "Link to this heading") * Add snake\_case methods to Geth Miner class, deprecate camelCase methods ([#1579](https://github.com/ethereum/web3.py/issues/1579) ) * Add snake\_case methods for the net module, deprecate camelCase methods ([#1581](https://github.com/ethereum/web3.py/issues/1581) ) * Add PEP561 type marker ([#1583](https://github.com/ethereum/web3.py/issues/1583) ) ### Bugfixes[](#id282 "Link to this heading") * Increase replacement tx minimum gas price bump Parity/OpenEthereum requires a replacement transaction’s gas to be a minimum of 12.5% higher than the original (vs. Geth’s 10%). ([#1570](https://github.com/ethereum/web3.py/issues/1570) ) v5.5.1 (2020-02-10)[](#v5-5-1-2020-02-10 "Link to this heading") ------------------------------------------------------------------ ### Improved Documentation[](#id283 "Link to this heading") * Documents the getUncleCount method. ([#1534](https://github.com/ethereum/web3.py/issues/1534) ) ### Misc[](#id284 "Link to this heading") * [#1576](https://github.com/ethereum/web3.py/issues/1576) v5.5.0 (2020-02-03)[](#v5-5-0-2020-02-03 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id285 "Link to this heading") * ENS had to release a new registry to push a bugfix. See [this article](https://medium.com/the-ethereum-name-service/ens-registry-migration-bug-fix-new-features-64379193a5a) for background information. web3.py uses the new registry for all default ENS interactions, now. ([#1573](https://github.com/ethereum/web3.py/issues/1573) ) ### Bugfixes[](#id286 "Link to this heading") * Minor bugfix in how ContractCaller looks up abi functions. ([#1552](https://github.com/ethereum/web3.py/issues/1552) ) * Update modules to use compatible typing-extensions import. ([#1554](https://github.com/ethereum/web3.py/issues/1554) ) * Make ‘from’ and ‘to’ fields checksum addresses in returned transaction receipts ([#1562](https://github.com/ethereum/web3.py/issues/1562) ) * Use local Trinity’s IPC socket if it is available, for newer versions of Trinity. ([#1563](https://github.com/ethereum/web3.py/issues/1563) ) ### Improved Documentation[](#id287 "Link to this heading") * Add Matomo Tracking to Docs site. Matomo is an Open Source web analytics platform that allows us to get better insights and optimize for our audience without the negative consequences of other compareable platforms. Read more: [https://matomo.org/why-matomo/](https://matomo.org/why-matomo/) ([#1541](https://github.com/ethereum/web3.py/issues/1541) ) * Fix web3 typo in docs ([#1559](https://github.com/ethereum/web3.py/issues/1559) ) ### Misc[](#id288 "Link to this heading") * [#1521](https://github.com/ethereum/web3.py/issues/1521) , [#1546](https://github.com/ethereum/web3.py/issues/1546) , [#1571](https://github.com/ethereum/web3.py/issues/1571) v5.4.0 (2019-12-06)[](#v5-4-0-2019-12-06 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id289 "Link to this heading") * Add \_\_str\_\_ to IPCProvider ([#1536](https://github.com/ethereum/web3.py/issues/1536) ) ### Bugfixes[](#id290 "Link to this heading") * Add required typing-extensions library to setup.py ([#1544](https://github.com/ethereum/web3.py/issues/1544) ) v5.3.1 (2019-12-05)[](#v5-3-1-2019-12-05 "Link to this heading") ------------------------------------------------------------------ ### Bugfixes[](#id291 "Link to this heading") * Only apply hexbytes formatting to r and s values in transaction if present ([#1531](https://github.com/ethereum/web3.py/issues/1531) ) * Update eth-utils dependency which contains mypy bugfix. ([#1537](https://github.com/ethereum/web3.py/issues/1537) ) ### Improved Documentation[](#id292 "Link to this heading") * Update Contract Event documentation to show correct example ([#1515](https://github.com/ethereum/web3.py/issues/1515) ) * Add documentation to methods that raise an error in v5 instead of returning `None` ([#1527](https://github.com/ethereum/web3.py/issues/1527) ) ### Misc[](#id293 "Link to this heading") * [#1518](https://github.com/ethereum/web3.py/issues/1518) , [#1532](https://github.com/ethereum/web3.py/issues/1532) v5.3.0 (2019-11-14)[](#v5-3-0-2019-11-14 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id294 "Link to this heading") * Support handling ENS domains in ERC1319 URIs. ([#1489](https://github.com/ethereum/web3.py/issues/1489) ) ### Bugfixes[](#id295 "Link to this heading") * Make local block filter return empty list when when no blocks mined ([#1255](https://github.com/ethereum/web3.py/issues/1255) ) * Google protobuf dependency was updated to 3.10.0 ([#1493](https://github.com/ethereum/web3.py/issues/1493) ) * Infura websocket provider works when no secret key is present ([#1501](https://github.com/ethereum/web3.py/issues/1501) ) ### Improved Documentation[](#id296 "Link to this heading") * Update Quickstart instructions to use the auto Infura module instead of the more complicated web3 auto module ([#1482](https://github.com/ethereum/web3.py/issues/1482) ) * Remove outdated py.test command from readme ([#1483](https://github.com/ethereum/web3.py/issues/1483) ) ### Misc[](#id297 "Link to this heading") * [#1461](https://github.com/ethereum/web3.py/issues/1461) , [#1471](https://github.com/ethereum/web3.py/issues/1471) , [#1475](https://github.com/ethereum/web3.py/issues/1475) , [#1476](https://github.com/ethereum/web3.py/issues/1476) , [#1479](https://github.com/ethereum/web3.py/issues/1479) , [#1488](https://github.com/ethereum/web3.py/issues/1488) , [#1492](https://github.com/ethereum/web3.py/issues/1492) , [#1498](https://github.com/ethereum/web3.py/issues/1498) v5.2.2 (2019-10-21)[](#v5-2-2-2019-10-21 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id298 "Link to this heading") * Add poll\_latency to waitForTransactionReceipt ([#1453](https://github.com/ethereum/web3.py/issues/1453) ) ### Bugfixes[](#id299 "Link to this heading") * Fix flaky Parity whisper module test ([#1473](https://github.com/ethereum/web3.py/issues/1473) ) ### Misc[](#id300 "Link to this heading") * [#1472](https://github.com/ethereum/web3.py/issues/1472) , [#1474](https://github.com/ethereum/web3.py/issues/1474) v5.2.1 (2019-10-17)[](#v5-2-1-2019-10-17 "Link to this heading") ------------------------------------------------------------------ ### Improved Documentation[](#id301 "Link to this heading") * Update documentation for unlock account duration ([#1464](https://github.com/ethereum/web3.py/issues/1464) ) * Clarify module installation command for OSX>=10.15 ([#1467](https://github.com/ethereum/web3.py/issues/1467) ) ### Misc[](#id302 "Link to this heading") * [#1468](https://github.com/ethereum/web3.py/issues/1468) v5.2.0 (2019-09-26)[](#v5-2-0-2019-09-26 "Link to this heading") ------------------------------------------------------------------ ### Features[](#id303 "Link to this heading") * Add `enable_strict_bytes_type_checking` flag to web3 instance ([#1419](https://github.com/ethereum/web3.py/issues/1419) ) * Move Geth Whisper methods to snake case and deprecate camel case methods ([#1433](https://github.com/ethereum/web3.py/issues/1433) ) ### Bugfixes[](#id304 "Link to this heading") * Add null check to logsbloom formatter ([#1445](https://github.com/ethereum/web3.py/issues/1445) ) ### Improved Documentation[](#id305 "Link to this heading") * Reformat autogenerated towncrier release notes ([#1460](https://github.com/ethereum/web3.py/issues/1460) ) Web3 5.1.0 (2019-09-18)[](#web3-5-1-0-2019-09-18 "Link to this heading") -------------------------------------------------------------------------- ### Features[](#id306 "Link to this heading") * Add `contract_types` property to `Package` class. ([#1440](https://github.com/ethereum/web3.py/issues/1440) ) ### Bugfixes[](#id307 "Link to this heading") * Fix flaky parity integration test in the whisper module ([#1147](https://github.com/ethereum/web3.py/issues/1147) ) ### Improved Documentation[](#id308 "Link to this heading") * Remove whitespace, move `topics` key -> `topic` in Geth docs ([#1425](https://github.com/ethereum/web3.py/issues/1425) ) * Enforce stricter doc checking, turning warnings into errors to fail CI builds to catch issues quickly. Add missing `web3.tools.rst` to the table of contents and fix incorrectly formatted JSON example. ([#1437](https://github.com/ethereum/web3.py/issues/1437) ) * Add example using Geth POA Middleware with Infura Rinkeby Node ([#1444](https://github.com/ethereum/web3.py/issues/1444) ) ### Misc[](#id309 "Link to this heading") * [#1446](https://github.com/ethereum/web3.py/issues/1446) , [#1451](https://github.com/ethereum/web3.py/issues/1451) v5.0.2[](#v5-0-2 "Link to this heading") ------------------------------------------ Released August 22, 2019 * Bugfixes * \[ethPM\] Fix bug in package id and release id fetching strategy - [#1427](https://github.com/ethereum/web3.py/pull/1427) v5.0.1[](#v5-0-1 "Link to this heading") ------------------------------------------ Released August 15, 2019 * Bugfixes * \[ethPM\] Add begin/close chars to package name regex - [#1418](https://github.com/ethereum/web3.py/pull/1418) * \[ethPM\] Update deployments to work when only abi available - [#1417](https://github.com/ethereum/web3.py/pull/1417) * Fix tuples handled incorrectly in `decode_function_input` - [#1410](https://github.com/ethereum/web3.py/pull/1410) * Misc * Eliminate `signTransaction` warning - [#1404](https://github.com/ethereum/web3.py/pull/1404) v5.0.0[](#v5-0-0 "Link to this heading") ------------------------------------------ Released August 1, 2019 * Features * `web3.eth.chainId` now returns an integer instead of hex - [#1394](https://github.com/ethereum/web3.py/pull/1394) * Bugfixes * Deprecation Warnings now show for methods that have a `@combomethod` decorator - [#1401](https://github.com/ethereum/web3.py/pull/1401) * Misc * \[ethPM\] Add ethPM to the docker file - [#1405](https://github.com/ethereum/web3.py/pull/1405) * Docs * Docs are updated to use checksummed addresses - [#1390](https://github.com/ethereum/web3.py/pull/1390) * Minor doc formatting fixes - [#1338](https://github.com/ethereum/web3.py/pull/1338) & [#1345](https://github.com/ethereum/web3.py/pull/1345) v5.0.0-beta.5[](#v5-0-0-beta-5 "Link to this heading") -------------------------------------------------------- Released July 31, 2019 _This is intended to be the final release before the stable v5 release._ * Features * Parity operating mode can be read and set - [#1355](https://github.com/ethereum/web3.py/pull/1355) * Process a single event log, instead of a whole transaction receipt - [#1354](https://github.com/ethereum/web3.py/pull/1354) * Docs * Remove doctest dependency on ethtoken - [#1395](https://github.com/ethereum/web3.py/pull/1395) * Bugfixes * \[ethPM\] Bypass IPFS validation for large files - [#1393](https://github.com/ethereum/web3.py/pull/1393) * Misc * \[ethPM\] Update default Registry solidity contract - [#1400](https://github.com/ethereum/web3.py/pull/1400) * \[ethPM\] Update web3.pm to use new simple Registry implementation - [#1398](https://github.com/ethereum/web3.py/pull/1398) * Update dependency requirement formatting for releasing - [#1403](https://github.com/ethereum/web3.py/pull/1403) v5.0.0-beta.4[](#v5-0-0-beta-4 "Link to this heading") -------------------------------------------------------- Released July 18,2019 * Features * \[ethPM\] Update registry uri to support basic uris w/o package id - [#1389](https://github.com/ethereum/web3.py/pull/1389) * Docs * Clarify in docs the return of `Eth.sendRawTransaction()` as a HexBytes object, not a string. - [#1384](https://github.com/ethereum/web3.py/pull/1384) * Misc * \[ethPM\] Migrate tests over from pytest-ethereum - [#1385](https://github.com/ethereum/web3.py/pull/1385) v5.0.0-beta.3[](#v5-0-0-beta-3 "Link to this heading") -------------------------------------------------------- Released July 15, 2019 * Features * Add eth\_getProof support - [#1185](https://github.com/ethereum/web3.py/pull/1185) * Implement web3.pm.get\_local\_package() - [#1372](https://github.com/ethereum/web3.py/pull/1372) * Update registry URIs to support chain IDs - [#1382](https://github.com/ethereum/web3.py/pull/1382) * Add error flags to `event.processReceipt` - [#1366](https://github.com/ethereum/web3.py/pull/1366) * Bugfixes * Remove full IDNA processing in favor of UTS46 - [#1364](https://github.com/ethereum/web3.py/pull/1364) * Misc * Migrate py-ethpm library to web3/ethpm - [#1379](https://github.com/ethereum/web3.py/pull/1379) * Relax canonical address requirement in ethPM - [#1380](https://github.com/ethereum/web3.py/pull/1380) * Replace ethPM’s infura strategy with web3’s native infura support - [#1383](https://github.com/ethereum/web3.py/pull/1383) * Change `combine_argument_formatters` to `apply_formatters_to_sequence` - [#1360](https://github.com/ethereum/web3.py/pull/1360) * Move `pytest.xfail` instances to `@pytest.mark.xfail` - [#1376](https://github.com/ethereum/web3.py/pull/1376) * Change `net.version` to `eth.chainId` in default transaction params - [#1378](https://github.com/ethereum/web3.py/pull/1378) v5.0.0-beta.2[](#v5-0-0-beta-2 "Link to this heading") -------------------------------------------------------- Released May 13, 2019 * Features * Mark deprecated sha3 method as static - [#1350](https://github.com/ethereum/web3.py/pull/1350) * Upgrade to eth-account v0.4.0 - [#1348](https://github.com/ethereum/web3.py/pull/1348) * Docs * Add note about web3\[tester\] in documentation - [#1325](https://github.com/ethereum/web3.py/pull/1325) * Misc * Replace `web3._utils.toolz` imports with `eth_utils.toolz` - [#1317](https://github.com/ethereum/web3.py/pull/1317) v5.0.0-beta.1[](#v5-0-0-beta-1 "Link to this heading") -------------------------------------------------------- Released May 6, 2019 * Features * Add support for tilda in provider IPC Path - [#1049](https://github.com/ethereum/web3.py/pull/1049) * EIP 712 Signing Supported - [#1319](https://github.com/ethereum/web3.py/pull/1319) * Docs * Update contract example to use `compile_standard` - [#1263](https://github.com/ethereum/web3.py/pull/1263) * Fix typo in middleware docs - [#1339](https://github.com/ethereum/web3.py/pull/1339) v5.0.0-alpha.11[](#v5-0-0-alpha-11 "Link to this heading") ------------------------------------------------------------ Released April 24, 2019 * Docs * Add documentation for web3.py unit tests - [#1324](https://github.com/ethereum/web3.py/pull/1324) * Misc * Update deprecated collections.abc imports - [#1334](https://github.com/ethereum/web3.py/pull/1334) * Fix documentation typo - [#1335](https://github.com/ethereum/web3.py/pull/1335) * Upgrade eth-tester version - [#1332](https://github.com/ethereum/web3.py/pull/1332) v5.0.0-alpha.10[](#v5-0-0-alpha-10 "Link to this heading") ------------------------------------------------------------ Released April 15, 2019 * Features * Add getLogs by blockHash - [#1269](https://github.com/ethereum/web3.py/pull/1269) * Implement chainId endpoint - [#1295](https://github.com/ethereum/web3.py/pull/1295) * Moved non-standard JSON-RPC endpoints to applicable Parity/Geth docs. Deprecated `web3.version` for `web3.api` - [#1290](https://github.com/ethereum/web3.py/pull/1290) * Moved Whisper endpoints to applicable Geth or Parity namespace - [#1308](https://github.com/ethereum/web3.py/pull/1308) * Added support for Goerli provider - [#1286](https://github.com/ethereum/web3.py/pull/1286) * Added addReservedPeer to Parity module - [#1311](https://github.com/ethereum/web3.py/pull/1311) * Bugfixes * Cast gas price values to integers in gas strategies - [#1297](https://github.com/ethereum/web3.py/pull/1297) * Missing constructor function no longer ignores constructor args - [#1316](https://github.com/ethereum/web3.py/pull/1316) * Misc * Require eth-utils >= 1.4, downgrade Go version for integration tests - [#1310](https://github.com/ethereum/web3.py/pull/1310) * Fix doc build warnings - [#1331](https://github.com/ethereum/web3.py/pull/1331) * Zip Fixture data - [#1307](https://github.com/ethereum/web3.py/pull/1307) * Update Geth version for integration tests - [#1301](https://github.com/ethereum/web3.py/pull/1301) * Remove unneeded testrpc - [#1322](https://github.com/ethereum/web3.py/pull/1322) * Add ContractCaller docs to v5 migration guide - [#1323](https://github.com/ethereum/web3.py/pull/1323) v5.0.0-alpha.9[](#v5-0-0-alpha-9 "Link to this heading") ---------------------------------------------------------- Released March 26, 2019 * Breaking Changes * Raise error if there is no Infura API Key - [#1294](https://github.com/ethereum/web3.py/pull/1294) & - [#1299](https://github.com/ethereum/web3.py/pull/1299) * Misc * Upgraded Parity version for integration testing - [#1292](https://github.com/ethereum/web3.py/pull/1292) v5.0.0-alpha.8[](#v5-0-0-alpha-8 "Link to this heading") ---------------------------------------------------------- Released March 20, 2019 * Breaking Changes * Removed `web3/utils` directory in favor of `web3/_utils` - [#1282](https://github.com/ethereum/web3.py/pull/1282) * Relocated personal RPC endpoints to Parity and Geth class - [#1211](https://github.com/ethereum/web3.py/pull/1211) * Deprecated `web3.net.chainId()`, `web3.eth.getCompilers()`, and `web3.eth.getTransactionFromBlock()`. Removed `web3.eth.enableUnauditedFeatures()` - [#1270](https://github.com/ethereum/web3.py/pull/1270) * Relocated eth\_protocolVersion and web3\_clientVersion - [#1274](https://github.com/ethereum/web3.py/pull/1274) * Relocated `web3.txpool` to `web3.geth.txpool` - [#1275](https://github.com/ethereum/web3.py/pull/1275) * Relocated admin module to Geth namespace - [#1288](https://github.com/ethereum/web3.py/pull/1288) * Relocated miner module to Geth namespace - [#1287](https://github.com/ethereum/web3.py/pull/1287) * Features * Implement `eth_submitHashrate` and `eth_submitWork` JSONRPC endpoints. - [#1280](https://github.com/ethereum/web3.py/pull/1280) * Implement `web3.eth.signTransaction` - [#1277](https://github.com/ethereum/web3.py/pull/1277) * Docs * Added v5 migration docs - [#1284](https://github.com/ethereum/web3.py/pull/1284) v5.0.0-alpha.7[](#v5-0-0-alpha-7 "Link to this heading") ---------------------------------------------------------- Released March 11, 2019 * Breaking Changes * Updated JSON-RPC calls that lookup txs or blocks to raise an error if lookup fails - [#1218](https://github.com/ethereum/web3.py/pull/1218) and [#1268](https://github.com/ethereum/web3.py/pull/1268) * Features * Tuple ABI support - [#1235](https://github.com/ethereum/web3.py/pull/1235) * Bugfixes * One last `middleware_stack` was still hanging on. Changed to `middleware_onion` - [#1262](https://github.com/ethereum/web3.py/pull/1262) v5.0.0-alpha.6[](#v5-0-0-alpha-6 "Link to this heading") ---------------------------------------------------------- Released February 25th, 2019 * Features * New `NoABIFound` error for cases where there is no ABI - [#1247](https://github.com/ethereum/web3.py/pull/1247) * Misc * Interact with Infura using an API Key. Key will be required after March 27th. - [#1232](https://github.com/ethereum/web3.py/pull/1232) * Remove `process_type` utility function in favor of eth-abi functionality - [#1249](https://github.com/ethereum/web3.py/pull/1249) v5.0.0-alpha.5[](#v5-0-0-alpha-5 "Link to this heading") ---------------------------------------------------------- Released February 13th, 2019 * Breaking Changes * Remove deprecated `buildTransaction`, `call`, `deploy`, `estimateGas`, and `transact` methods - [#1232](https://github.com/ethereum/web3.py/pull/1232) * Features * Adds `Web3.toJSON` method - [#1173](https://github.com/ethereum/web3.py/pull/1173) * Contract Caller API Implemented - [#1227](https://github.com/ethereum/web3.py/pull/1227) * Add Geth POA middleware to use Rinkeby with Infura Auto - [#1234](https://github.com/ethereum/web3.py/pull/1234) * Add manifest and input argument validation to `pm.release_package()` - [#1237](https://github.com/ethereum/web3.py/pull/1237) * Misc * Clean up intro and block/tx sections in Filter docs - [#1223](https://github.com/ethereum/web3.py/pull/1223) * Remove unnecessary `EncodingError` exception catching - [#1224](https://github.com/ethereum/web3.py/pull/1224) * Improvements to `merge_args_and_kwargs` utility function - [#1228](https://github.com/ethereum/web3.py/pull/1228) * Update vyper registry assets - [#1242](https://github.com/ethereum/web3.py/pull/1242) v5.0.0-alpha.4[](#v5-0-0-alpha-4 "Link to this heading") ---------------------------------------------------------- Released January 23rd, 2019 * Breaking Changes * Rename `middleware_stack` to `middleware_onion` - [#1210](https://github.com/ethereum/web3.py/pull/1210) * Drop already deprecated `web3.soliditySha3` - [#1217](https://github.com/ethereum/web3.py/pull/1217) * ENS: Stop inferring `.eth` TLD on domain names - [#1205](https://github.com/ethereum/web3.py/pull/1205) * Bugfixes * Validate `ethereum_tester` class in `EthereumTesterProvider` - [#1217](https://github.com/ethereum/web3.py/pull/1217) * Support `getLogs()` method without creating filters - [#1192](https://github.com/ethereum/web3.py/pull/1192) * Features * Stablize the `PM` module - [#1125](https://github.com/ethereum/web3.py/pull/1125) * Implement async `Version` module - [#1166](https://github.com/ethereum/web3.py/pull/1166) * Misc * Update .gitignore to ignore `.DS_Store` and `.mypy_cache/` - [#1215](https://github.com/ethereum/web3.py/pull/1215) * Change CircleCI badge link to CircleCI project - [#1214](https://github.com/ethereum/web3.py/pull/1214) v5.0.0-alpha.3[](#v5-0-0-alpha-3 "Link to this heading") ---------------------------------------------------------- Released January 15th, 2019 * Breaking Changes * Remove `web3.miner.hashrate` and `web3.version.network` - [#1198](https://github.com/ethereum/web3.py/pull/1198) * Remove `web3.providers.tester.EthereumTesterProvider` and `web3.providers.tester.TestRPCProvider` - [#1199](https://github.com/ethereum/web3.py/pull/1199) * Change `manager.providers` from list to single `manager.provider` - [#1200](https://github.com/ethereum/web3.py/pull/1200) * Replace deprecated `web3.sha3` method with `web3.keccak` method - [#1207](https://github.com/ethereum/web3.py/pull/1207) * Drop auto detect testnets for IPCProvider - [#1206](https://github.com/ethereum/web3.py/pull/1206) * Bugfixes * Add check to make sure blockHash exists - [#1158](https://github.com/ethereum/web3.py/pull/1158) * Misc * Remove some unreachable code in providers/base.py - [#1160](https://github.com/ethereum/web3.py/pull/1160) * Migrate tester provider results from middleware to defaults - [#1188](https://github.com/ethereum/web3.py/pull/1188) * Fix doc formatting for build\_filter method - [#1187](https://github.com/ethereum/web3.py/pull/1187) * Add ERC20 example in docs - [#1178](https://github.com/ethereum/web3.py/pull/1178) * Code style improvements - [#1194](https://github.com/ethereum/web3.py/pull/1194) & [#1191](https://github.com/ethereum/web3.py/pull/1191) * Convert Web3 instance variables to w3 - [#1186](https://github.com/ethereum/web3.py/pull/1186) * Update eth-utils dependencies and clean up other dependencies - [#1195](https://github.com/ethereum/web3.py/pull/1195) v5.0.0-alpha.2[](#v5-0-0-alpha-2 "Link to this heading") ---------------------------------------------------------- Released December 20th, 2018 * Breaking Changes * Remove support for python3.5, drop support for eth-abi v1 - [#1163](https://github.com/ethereum/web3.py/pull/1163) * Features * Support for custom ReleaseManager was fixed - [#1165](https://github.com/ethereum/web3.py/pull/1165) * Misc * Fix doctest nonsense with unicorn token - [3b2047](https://github.com/ethereum/web3.py/commit/3b20479ea52) * Docs for installing web3 in FreeBSD - [#1156](https://github.com/ethereum/web3.py/pull/1156) * Use latest python in readthedocs - [#1162](https://github.com/ethereum/web3.py/pull/1162) * Use twine in release script - [#1164](https://github.com/ethereum/web3.py/pull/1164) * Upgrade eth-tester, for eth-abi v2 support - [#1168](https://github.com/ethereum/web3.py/pull/1168) v5.0.0-alpha.1[](#v5-0-0-alpha-1 "Link to this heading") ---------------------------------------------------------- Released December 13th, 2018 * Features * Add Rinkeby and Kovan Infura networks; made mainnet the default - [#1150](https://github.com/ethereum/web3.py/pull/1150) * Add parity-specific `listStorageKeys` RPC - [#1145](https://github.com/ethereum/web3.py/pull/1145) * Deprecated `Web3.soliditySha3`; use `Web3.solidityKeccak` instead. - [#1139](https://github.com/ethereum/web3.py/pull/1139) * Add default trinity locations to IPC path guesser - [#1121](https://github.com/ethereum/web3.py/pull/1121) * Add wss to `AutoProvider` - [#1110](https://github.com/ethereum/web3.py/pull/1110) * Add timeout for `WebsocketProvider` - [#1109](https://github.com/ethereum/web3.py/pull/1109) * Receipt timeout raises `TimeExhausted` - [#1070](https://github.com/ethereum/web3.py/pull/1070) * Allow specification of block number for `eth_estimateGas` - [#1046](https://github.com/ethereum/web3.py/pull/1046) * Misc * Removed `web3._utils.six` support - [#1116](https://github.com/ethereum/web3.py/pull/1116) * Upgrade eth-utils to 1.2.0 - [#1104](https://github.com/ethereum/web3.py/pull/1104) * Require Python version 3.5.3 or greater - [#1095](https://github.com/ethereum/web3.py/pull/1095) * Bump websockets version to 7.0.0 - [#1146](https://github.com/ethereum/web3.py/pull/1146) * Bump parity test binary to 1.11.11 - [#1064](https://github.com/ethereum/web3.py/pull/1064) v4.8.2[](#v4-8-2 "Link to this heading") ------------------------------------------ Released November 15, 2018 * Misc * Reduce unneeded memory usage - [#1138](https://github.com/ethereum/web3.py/pull/1138) v4.8.1[](#v4-8-1 "Link to this heading") ------------------------------------------ Released October 28, 2018 * Features * Add timeout for WebsocketProvider - [#1119](https://github.com/ethereum/web3.py/pull/1119) * Reject transactions that send ether to non-payable contract functions - [#1115](https://github.com/ethereum/web3.py/pull/1115) * Add Auto Infura Ropsten support: `from web3.auto.infura.ropsten import w3` - [#1124](https://github.com/ethereum/web3.py/pull/1124) * Auto-detect trinity IPC file location - [#1129](https://github.com/ethereum/web3.py/pull/1129) * Misc * Require Python >=3.5.3 - [#1107](https://github.com/ethereum/web3.py/pull/1107) * Upgrade eth-tester and eth-utils - [#1085](https://github.com/ethereum/web3.py/pull/1085) * Configure readthedocs dependencies - [#1082](https://github.com/ethereum/web3.py/pull/1082) * soliditySha3 docs fixup - [#1100](https://github.com/ethereum/web3.py/pull/1100) * Update ropsten faucet links in troubleshooting docs v4.7.2[](#v4-7-2 "Link to this heading") ------------------------------------------ Released September 25th, 2018 * Bugfixes * IPC paths starting with `~` are appropriately resolved to the home directory - [#1072](https://github.com/ethereum/web3.py/pull/1072) * You can use the local signing middleware with [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)") \-type addresses - [#1069](https://github.com/ethereum/web3.py/pull/1069) v4.7.1[](#v4-7-1 "Link to this heading") ------------------------------------------ Released September 11th, 2018 * Bugfixes * [old pip bug](https://github.com/pypa/pip/issues/4614) used during release made it impossible for non-windows users to install 4.7.0. v4.7.0[](#v4-7-0 "Link to this heading") ------------------------------------------ Released September 10th, 2018 * Features * Add traceFilter method to the parity module. - [#1051](https://github.com/ethereum/web3.py/pull/1051) * Move `datastructures` to public namespace `datastructures` to improve support for type checking. - [#1038](https://github.com/ethereum/web3.py/pull/1038) * Optimization to contract calls - [#944](https://github.com/ethereum/web3.py/pull/944) * Bugfixes * ENS name resolution only attempted on mainnet by default. - [#1037](https://github.com/ethereum/web3.py/pull/1037) * Fix attribute access error when attributedict middleware is not used. - [#1040](https://github.com/ethereum/web3.py/pull/1040) * Misc - Upgrade eth-tester to 0.1.0-beta.32, and remove integration tests for py-ethereum. - Upgrade eth-hash to 0.2.0 with pycryptodome 3.6.6 which resolves a vulnerability. v4.6.0[](#v4-6-0 "Link to this heading") ------------------------------------------ Released Aug 24, 2018 * Features * Support for Python 3.7, most notably in `WebsocketProvider` - [#996](https://github.com/ethereum/web3.py/pull/996) * You can now decode a transaction’s data to its original function call and arguments with: [`contract.decode_function_input()`](web3.contract.html#web3.contract.Contract.decode_function_input "web3.contract.Contract.decode_function_input") - [#991](https://github.com/ethereum/web3.py/pull/991) * Support for [`IPCProvider`](providers.html#web3.providers.ipc.IPCProvider "web3.providers.ipc.IPCProvider") in FreeBSD (and more readme docs) - [#1008](https://github.com/ethereum/web3.py/pull/1008) * Bugfixes * Fix crash in time-based gas strategies with small number of transactions - [#983](https://github.com/ethereum/web3.py/pull/983) * Fx crash when passing multiple addresses to `w3.eth.getLogs()` - [#1005](https://github.com/ethereum/web3.py/pull/1005) * Misc * Disallow configuring filters with both manual and generated topic lists - [#976](https://github.com/ethereum/web3.py/pull/976) * Add support for the upcoming eth-abi v2, which does ABI string decoding differently - [#974](https://github.com/ethereum/web3.py/pull/974) * Add a lot more filter tests - [#997](https://github.com/ethereum/web3.py/pull/997) * Add more tests for filtering with `None`. Note that geth & parity differ here. - [#985](https://github.com/ethereum/web3.py/pull/985) * Follow-up on Parity bug that we reported upstream ([parity#7816](https://github.com/paritytech/parity-ethereum/issues/7816) ): they resolved in 1.10. We removed xfail on that test. - [#992](https://github.com/ethereum/web3.py/pull/992) * Docs: add an example of interacting with an ERC20 contract - [#995](https://github.com/ethereum/web3.py/pull/995) * A couple doc typo fixes > * [#1006](https://github.com/ethereum/web3.py/pull/1006) > > * [#1010](https://github.com/ethereum/web3.py/pull/1010) > v4.5.0[](#v4-5-0 "Link to this heading") ------------------------------------------ Released July 30, 2018 * Features * Accept addresses supplied in [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)") format (which does not provide checksum validation) * Improve estimation of gas prices * Bugfixes * Can now use a block number with `getCode()` when connected to [`EthereumTesterProvider`](providers.html#web3.providers.eth_tester.EthereumTesterProvider "web3.providers.eth_tester.EthereumTesterProvider") (without crashing) * Misc * Test Parity 1.11.7 * Parity integration tests upgrade to use sha256 instead of md5 * Fix some filter docs * eth-account upgrade to v0.3.0 * eth-tester upgrade to v0.1.0-beta.29 v4.4.1[](#v4-4-1 "Link to this heading") ------------------------------------------ Released June 29, 2018 * Bugfixes * eth-pm package was renamed (old one deleted) which broke the web3 release. eth-pm was removed from the web3.py install until it’s stable. * Misc * [`IPCProvider`](providers.html#web3.providers.ipc.IPCProvider "web3.providers.ipc.IPCProvider") now accepts a [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.13)") argument for the IPC path * Docs explaining the new custom autoproviders in web3 v4.4.0[](#v4-4-0 "Link to this heading") ------------------------------------------ Released June 21, 2018 * Features * Add support for https in WEB3\_PROVIDER\_URI environment variable * Can send websocket connection parameters in `WebsocketProvider` * Two new auto-initialization options: * `from web3.auto.gethdev import w3` * `from web3.auto.infura import w3` (After setting the `INFURA_API_KEY` environment variable) * Alpha support for a new package management tool based on ethpm-spec * Bugfixes * Can now receive large responses in `WebsocketProvider` by specifying a large `max_size` in the websocket connection parameters. * Misc * Websockets dependency upgraded to v5 * Raise deprecation warning on `getTransactionFromBlock()` * Fix docs for `waitForTransactionReceipt()` * Developer Dockerfile now installs testing dependencies v4.3.0[](#v4-3-0 "Link to this heading") ------------------------------------------ Released June 6, 2018 * Features * Support for the ABI types like: [fixedMxN](http://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#types) which is used by Vyper. * In-flight transaction-signing middleware: Use local keys as if they were hosted keys using the new `sign_and_send_raw_middleware` * New `getUncleByBlock()` API * New name `getTransactionByBlock()`, which replaces the deprecated `getTransactionFromBlock()` * Add several new Parity trace functions * New API to resolve ambiguous function calls, for example: * Two functions with the same name that accept similar argument types, like `myfunc(uint8)` and `myfunc(int8)`, and you want to call `contract.functions.myfunc(1).call()` * See how to use it at: [Invoke Ambiguous Contract Functions](web3.contract.html#ambiguous-contract-functions) * Bugfixes * Gas estimation doesn’t crash, when 0 blocks are available. (ie~ on the genesis block) * Close out all HTTPProvider sessions, to squash warnings on exit * Stop adding Contract address twice to the filter. It was making some nodes unhappy * Misc * Friendlier json encoding/decoding failure error messages * Performance improvements, when the responses from the node are large (by reducing the number of times we evaluate if the response is valid json) * Parity CI test fixes (ugh, environment setup hell, thanks to the community for cleaning this up!) * Don’t crash when requesting a transaction that was created with the parity bug (which allowed an unsigned transaction to be included, so `publicKey` is `None`) * Doc fixes: addresses must be checksummed (or ENS names on mainnet) * Enable local integration testing of parity on non-Debian OS * README: * Testing setup for devs * Change the build badge from Travis to Circle CI * Cache the parity binary in Circle CI, to reduce the impact of their binary API going down * Dropped the dot: `py.test` -> `pytest` v4.2.1[](#v4-2-1 "Link to this heading") ------------------------------------------ Released May 9, 2018 * Bugfixes * When `getting a transaction` with data attached and trying to `modify it` (say, to increase the gas price), the data was not being reattached in the new transaction. * `web3.personal.sendTransaction()` was crashing when using a transaction generated with `buildTransaction()` * Misc * Improved error message when connecting to a geth-style PoA network * Improved error message when address is not checksummed * Started in on support for `fixedMxN` ABI arguments * Lots of documentation upgrades, including: * Guide for understanding nodes/networks/connections * Simplified Quickstart with notes for common issues * A new Troubleshooting section * Potential pypy performance improvements (use toolz instead of cytoolz) * eth-tester upgraded to beta 24 v4.2.0[](#v4-2-0 "Link to this heading") ------------------------------------------ Released Apr 25, 2018 * Removed audit warning and opt-in requirement for `w3.eth.account`. See more in: [Accounts](web3.eth.account.html#eth-account) * Added an API to look up contract functions: `fn = contract.functions['function_name_here']` * Upgrade Whisper (shh) module to use v6 API * Bugfix: set ‘to’ field of transaction to empty when using `transaction = contract.constructor().buildTransaction()` * You can now specify nonce in `buildTransaction()` * Distinguish between chain id and network id – currently always return None for `chainId` * Better error message when trying to use a contract function that has 0 or >1 matches * Better error message when trying to install on a python version <3.5 * Installs pypiwin32 during pip install, for a better Windows experience * Cleaned up a lot of test warnings by upgrading from deprecated APIs, especially from the deprecated `contract.deploy(txn_dict, args=contract_args)` to the new `contract.constructor(*contract_args).transact(txn_dict)` * Documentation typo fixes * Better template for Pull Requests v4.1.0[](#v4-1-0 "Link to this heading") ------------------------------------------ Released Apr 9, 2018 * New `WebsocketProvider`. If you’re looking for better performance than HTTP, check out websockets. * New `w3.eth.waitForTransactionReceipt()` * Added name collision detection to ConciseContract and ImplicitContract * Bugfix to allow fromBlock set to 0 in createFilter, like `contract.events.MyEvent.createFilter(fromBlock=0, ...)` * Bugfix of ENS automatic connection * eth-tester support for Byzantium * New migration guide for v3 -> v4 upgrade * Various documentation updates * Pinned eth-account to older version v4.0.0[](#v4-0-0 "Link to this heading") ------------------------------------------ Released Apr 2, 2018 * Marked beta.13 as stable * Documentation tweaks v4.0.0-beta.13[](#v4-0-0-beta-13 "Link to this heading") ---------------------------------------------------------- Released Mar 27, 2018 _This is intended to be the final release before the stable v4 release._ * Add support for geth 1.8 (fixed error on `getTransactionReceipt()`) * You can now call a contract method at a specific block with the `block_identifier` keyword argument, see: [`call()`](web3.contract.html#web3.contract.ContractFunction.call "web3.contract.ContractFunction.call") * In preparation for stable release, disable `w3.eth.account` by default, until a third-party audit is complete & resolved. * New API for contract deployment, which enables gas estimation, local signing, etc. See [`constructor()`](web3.contract.html#web3.contract.Contract.constructor "web3.contract.Contract.constructor") . * Find contract events with [contract.events.$my\_event.createFilter()](web3.contract.html#contract-create-filter) * Support auto-complete for contract methods. * Upgrade most dependencies to stable * eth-abi * eth-utils * hexbytes * _not included: eth-tester and eth-account_ * Switch the default EthereumTesterProvider backend from eth-testrpc to eth-tester: [`web3.providers.eth_tester.EthereumTesterProvider`](providers.html#web3.providers.eth_tester.EthereumTesterProvider "web3.providers.eth_tester.EthereumTesterProvider") * A lot of documentation improvements * Test node integrations over a variety of providers * geth 1.8 test suite v4.0.0-beta.12[](#v4-0-0-beta-12 "Link to this heading") ---------------------------------------------------------- A little hiccup on release. Skipped. v4.0.0-beta.11[](#v4-0-0-beta-11 "Link to this heading") ---------------------------------------------------------- Released Feb 28, 2018 * New methods to modify or replace pending transactions * A compatibility option for connecting to `geth --dev` – see [Proof of Authority](middleware.html#geth-poa) * A new `web3.net.chainId` * Create a filter object from an existing filter ID. * eth-utils v1.0.1 (stable) compatibility v4.0.0-beta.10[](#v4-0-0-beta-10 "Link to this heading") ---------------------------------------------------------- Released Feb 21, 2018 * bugfix: Compatibility with eth-utils v1-beta2 (the incompatibility was causing fresh web3.py installs to fail) * bugfix: crash when sending the output of `contract.functions.myFunction().buildTransaction()` to `sendTransaction()`. Now, having a chainID key does not crash sendTransaction. * bugfix: a TypeError when estimating gas like: `contract.functions.myFunction().estimateGas()` is fixed * Added parity integration tests to the continuous integration suite! * Some py3 and docs cleanup v4.0.0-beta.9[](#v4-0-0-beta-9 "Link to this heading") -------------------------------------------------------- Released Feb 8, 2018 * Access event log parameters as attributes * Support for specifying nonce in eth-tester * [Bugfix](https://github.com/ethereum/web3.py/pull/616) dependency conflicts between eth-utils, eth-abi, and eth-tester * Clearer error message when invalid keywords provided to contract constructor function * New docs for working with private keys + set up doctests * First parity integration tests * replace internal implementation of w3.eth.account with [`eth_account.account.Account`](https://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account "(in eth-account v0.13)") v4.0.0-beta.8[](#v4-0-0-beta-8 "Link to this heading") -------------------------------------------------------- Released Feb 7, 2018, then recalled. It added 32MB of test data to git history, so the tag was deleted, as well as the corresponding release. (Although the release would not have contained that test data) v4.0.0-beta.7[](#v4-0-0-beta-7 "Link to this heading") -------------------------------------------------------- Released Jan 29, 2018 * Support for `web3.eth.Eth.getLogs()` in eth-tester with py-evm * Process transaction receipts with Event ABI, using Contract.events.myEvent(\*args, \*\*kwargs).processReceipt(transaction\_receipt) see [Event Log Object](web3.contract.html#event-log-object) for the new type. * Add timeout parameter to [`web3.providers.ipc.IPCProvider`](providers.html#web3.providers.ipc.IPCProvider "web3.providers.ipc.IPCProvider") * bugfix: make sure idna package is always installed * Replace ethtestrpc with py-evm, in all tests * Dockerfile fixup * Test refactoring & cleanup * Reduced warnings during tests v4.0.0-beta.6[](#v4-0-0-beta-6 "Link to this heading") -------------------------------------------------------- Released Jan 18, 2018 * New contract function call API: my\_contract.functions.my\_func().call() is preferred over the now deprecated my\_contract.call().my\_func() API. * A new, sophisticated gas estimation algorithm, based on the [https://ethgasstation.info](https://ethgasstation.info) approach. You must opt-in to the new approach, because it’s quite slow. We recommend using the new caching middleware. See [`web3.gas_strategies.time_based.construct_time_based_gas_price_strategy()`](gas_price.html#web3.gas_strategies.time_based.construct_time_based_gas_price_strategy "web3.gas_strategies.time_based.construct_time_based_gas_price_strategy") * New caching middleware that can cache based on time, block, or indefinitely. * Automatically retry JSON-RPC requests over HTTP, a few times. * ConciseContract now has the address directly * Many eth-tester fixes. `web3.providers.eth_tester.main.EthereumTesterProvider` is now a legitimate alternative to `web3.providers.tester.EthereumTesterProvider`. * ethtest-rpc removed from testing. Tests use eth-tester only, on pyethereum. Soon it will be eth-tester with py-evm. * Bumped several dependencies, like eth-tester * Documentation updates v4.0.0-beta.5[](#v4-0-0-beta-5 "Link to this heading") -------------------------------------------------------- Released Dec 28, 2017 * Improvements to working with eth-tester, using [`EthereumTesterProvider`](providers.html#web3.providers.eth_tester.EthereumTesterProvider "web3.providers.eth_tester.EthereumTesterProvider") : * Bugfix the key names in event logging * Add support for `sendRawTransaction()` * [`IPCProvider`](providers.html#web3.providers.ipc.IPCProvider "web3.providers.ipc.IPCProvider") now automatically retries on a broken connection, like when you restart your node * New gas price engine API, laying groundwork for more advanced gas pricing strategies v4.0.0-beta.4[](#v4-0-0-beta-4 "Link to this heading") -------------------------------------------------------- Released Dec 7, 2017 * New `buildTransaction()` method to prepare contract transactions, offline * New automatic provider detection, for `w3 = Web3()` initialization * Set environment variable WEB3\_PROVIDER\_URI to suggest a provider for automatic detection * New API to set providers like: `w3.providers = [IPCProvider()]` * Crashfix: [`web3.eth.Eth.filter()`](web3.eth.html#web3.eth.Eth.filter "web3.eth.Eth.filter") when retrieving logs with the argument ‘latest’ * Bump eth-tester to v0.1.0-beta.5, with bugfix for filtering by topic * Removed GPL lib `pylru`, now believed to be in full MIT license compliance. v4.0.0-beta.3[](#v4-0-0-beta-3 "Link to this heading") -------------------------------------------------------- Released Dec 1, 2017 * Fix encoding of ABI types: `bytes[]` and `string[]` * Windows connection error bugfix * Bugfix message signatures that were broken ~1% of the time (zero-pad `r` and `s`) * Autoinit web3 now produces None instead of raising an exception on `from web3.auto import w3` * Clearer errors on formatting failure (includes field name that failed) * Python modernization, removing Py2 compatibility cruft * Update dependencies with changed names, now: * `eth-abi` * `eth-keyfile` * `eth-keys` * `eth-tester` * `eth-utils` * Faster Travis CI builds, with cached geth binary v4.0.0-beta.2[](#v4-0-0-beta-2 "Link to this heading") -------------------------------------------------------- Released Nov 22, 2017 Bug Fixes: * `sendRawTransaction()` accepts raw bytes * [`contract()`](web3.eth.html#web3.eth.Eth.contract "web3.eth.Eth.contract") accepts an ENS name as contract address * `signTransaction()` returns the expected hash (_after_ signing the transaction) * `Account` methods can all be called statically, like: `Account.sign(...)` * `getTransactionReceipt()` returns the `status` field as an `int` * `Web3.soliditySha3()` looks up ENS names if they are supplied with an “address” ABI * If running multiple threads with the same w3 instance, `ValueError: Recursively called ...` is no longer raised Plus, various python modernization code cleanups, and testing against geth 1.7.2. v4.0.0-beta.1[](#v4-0-0-beta-1 "Link to this heading") -------------------------------------------------------- * Python 3 is now required * ENS names can be used anywhere that a hex address can * Sign transactions and messages with local private keys * New filter mechanism: [`get_all_entries()`](filters.html#web3.utils.filters.Filter.get_all_entries "web3.utils.filters.Filter.get_all_entries") and [`get_new_entries()`](filters.html#web3.utils.filters.Filter.get_new_entries "web3.utils.filters.Filter.get_new_entries") * Quick automatic initialization with `from web3.auto import w3` * All addresses must be supplied with an EIP-55 checksum * All addresses are returned with a checksum * Renamed `Web3.toDecimal()` to `toInt()`, see: [Encoding and Decoding Helpers](web3.main.html#overview-type-conversions) * All filter calls are synchronous, gevent integration dropped * Contract `eventFilter()` has replaced both `Contract.on()` and `Contract.pastEvents()` * Contract arguments of `bytes` ABI type now accept hex strings. * Contract arguments of `string` ABI type now accept python `str`. * Contract return values of `string` ABI type now return python `str`. * Many methods now return a `bytes`\-like object where they used to return a hex string, like in `Web3.sha3()` * IPC connection left open and reused, rather than opened and closed on each call * A number of deprecated methods from v3 were removed 3.16.1[](#id468 "Link to this heading") ----------------------------------------- * Addition of `ethereum-tester` as a dependency 3.16.0[](#id469 "Link to this heading") ----------------------------------------- * Addition of _named_ middlewares for easier manipulation of middleware stack. * Provider middlewares can no longer be modified during runtime. * Experimental custom ABI normalization API for Contract objects. 3.15.0[](#id470 "Link to this heading") ----------------------------------------- * Change docs to use RTD theme * Experimental new `EthereumTesterProvider` for the `ethereum-tester` library. * Bugfix for `function` type abi encoding via `ethereum-abi-utils` upgrade to `v0.4.1` * Bugfix for `Web3.toHex` to conform to RPC spec. 3.14.2[](#id471 "Link to this heading") ----------------------------------------- * Fix PyPi readme text. 3.14.1[](#id472 "Link to this heading") ----------------------------------------- * Fix PyPi readme text. 3.14.0[](#id473 "Link to this heading") ----------------------------------------- * New `stalecheck_middleware` * Improvements to `Web3.toHex` and `Web3.toText`. * Improvements to `Web3.sha3` signature. * Bugfixes for `Web3.eth.sign` api 3.13.5[](#id474 "Link to this heading") ----------------------------------------- * Add experimental `fixture_middleware` * Various bugfixes introduced in middleware API introduction and migration to formatter middleware. 3.13.4[](#id475 "Link to this heading") ----------------------------------------- * Bugfix for formatter handling of contract creation transaction. 3.13.3[](#id476 "Link to this heading") ----------------------------------------- * Improved testing infrastructure. 3.13.2[](#id477 "Link to this heading") ----------------------------------------- * Bugfix for retrieving filter changes for both new block filters and pending transaction filters. 3.13.1[](#id478 "Link to this heading") ----------------------------------------- * Fix mispelled `attrdict_middleware` (was spelled `attrdict_middlware`). 3.13.0[](#id479 "Link to this heading") ----------------------------------------- * New Middleware API * Support for multiple providers * New `web3.soliditySha3` * Remove multiple functions that were never implemented from the original web3. * Deprecated `web3.currentProvider` accessor. Use `web3.provider` now instead. * Deprecated password prompt within `web3.personal.newAccount`. 3.12.0[](#id480 "Link to this heading") ----------------------------------------- * Bugfix for abi filtering to correctly handle `constructor` and `fallback` type abi entries. 3.11.0[](#id481 "Link to this heading") ----------------------------------------- * All web3 apis which accept `address` parameters now enforce checksums if the address _looks_ like it is checksummed. * Improvements to error messaging with when calling a contract on a node that may not be fully synced * Bugfix for `web3.eth.syncing` to correctly handle `False` 3.10.0[](#id482 "Link to this heading") ----------------------------------------- * Web3 now returns `web3.utils.datastructures.AttributeDict` in places where it previously returned a normal `dict`. * `web3.eth.contract` now performs validation on the `address` parameter. * Added `web3.eth.getWork` API 3.9.0[](#id483 "Link to this heading") ---------------------------------------- * Add validation for the `abi` parameter of `eth` * Contract return values of `bytes`, `bytesXX` and `string` are no longer converted to text types and will be returned in their raw byte-string format. 3.8.1[](#id484 "Link to this heading") ---------------------------------------- * Bugfix for `eth_sign` double hashing input. * Removed deprecated `DelegatedSigningManager` * Removed deprecate `PrivateKeySigningManager` 3.8.0[](#id485 "Link to this heading") ---------------------------------------- * Update pyrlp dependency to `>=0.4.7` * Update eth-testrpc dependency to `>=1.2.0` * Deprecate `DelegatedSigningManager` * Deprecate `PrivateKeySigningManager` 3.7.1[](#id486 "Link to this heading") ---------------------------------------- * upstream version bump for bugfix in eth-abi-utils 3.7.0[](#id487 "Link to this heading") ---------------------------------------- * deprecate `eth.defaultAccount` defaulting to the coinbase account. 3.6.2[](#id488 "Link to this heading") ---------------------------------------- * Fix error message from contract factory creation. * Use `ethereum-utils` for utility functions. 3.6.1[](#id489 "Link to this heading") ---------------------------------------- * Upgrade `ethereum-abi-utils` dependency for upstream bugfix. 3.6.0[](#id490 "Link to this heading") ---------------------------------------- * Deprecate `Contract.code`: replaced by `Contract.bytecode` * Deprecate `Contract.code_runtime`: replaced by `Contract.bytecode_runtime` * Deprecate `abi`, `code`, `code_runtime` and `source` as arguments for the `Contract` object. * Deprecate `source` as a property of the `Contract` object * Add `Contract.factory()` API. * Deprecate the `construct_contract_factory` helper function. 3.5.3[](#id491 "Link to this heading") ---------------------------------------- * Bugfix for how `requests` library is used. Now reuses session. 3.5.2[](#id492 "Link to this heading") ---------------------------------------- * Bugfix for construction of `request_kwargs` within HTTPProvider 3.5.1[](#id493 "Link to this heading") ---------------------------------------- * Allow `HTTPProvider` to be imported from `web3` module. * make `HTTPProvider` accessible as a property of `web3` instances. 3.5.0[](#id494 "Link to this heading") ---------------------------------------- * Deprecate `web3.providers.rpc.RPCProvider` * Deprecate `web3.providers.rpc.KeepAliveRPCProvider` * Add new `web3.providers.rpc.HTTPProvider` * Remove hard dependency on gevent. 3.4.4[](#id495 "Link to this heading") ---------------------------------------- * Bugfix for `web3.eth.getTransaction` when the hash is unknown. 3.4.3[](#id496 "Link to this heading") ---------------------------------------- * Bugfix for event log data decoding to properly handle dynamic sized values. * New `web3.tester` module to access extra RPC functionality from `eth-testrpc` 3.4.2[](#id497 "Link to this heading") ---------------------------------------- * Fix package so that `eth-testrpc` is not required. 3.4.1[](#id498 "Link to this heading") ---------------------------------------- * Force gevent<1.2.0 until this issue is fixed: [https://github.com/gevent/gevent/issues/916](https://github.com/gevent/gevent/issues/916) 3.4.0[](#id499 "Link to this heading") ---------------------------------------- * Bugfix for contract instances to respect `web3.eth.defaultAccount` * Better error reporting when ABI decoding fails for contract method response. 3.3.0[](#id500 "Link to this heading") ---------------------------------------- * New `EthereumTesterProvider` now available. Faster test runs than `TestRPCProvider` * Updated underlying eth-testrpc requirement. 3.2.0[](#id501 "Link to this heading") ---------------------------------------- * `web3.shh` is now implemented. * Introduced `KeepAliveRPCProvider` to correctly recycle HTTP connections and use HTTP keep alive 3.1.1[](#id502 "Link to this heading") ---------------------------------------- * Bugfix for contract transaction sending not respecting the `web3.eth.defaultAccount` configuration. 3.1.0[](#id503 "Link to this heading") ---------------------------------------- * New DelegatedSigningManager and PrivateKeySigningManager classes. 3.0.2[](#id504 "Link to this heading") ---------------------------------------- * Bugfix or IPCProvider not handling large JSON responses well. 3.0.1[](#id505 "Link to this heading") ---------------------------------------- * Better RPC compliance to be compatable with the Parity JSON-RPC server. 3.0.0[](#id506 "Link to this heading") ---------------------------------------- * `Filter` objects now support controlling the interval through which they poll using the `poll_interval` property 2.9.0[](#id507 "Link to this heading") ---------------------------------------- * Bugfix generation of event topics. * Web3.Iban now allows access to Iban address tools. 2.8.1[](#id508 "Link to this heading") ---------------------------------------- * Bugfix for `geth.ipc` path on linux systems. 2.8.0[](#id509 "Link to this heading") ---------------------------------------- * Changes to the `Contract` API: * `Contract.deploy()` parameter arguments renamed to args * `Contract.deploy()` now takes args and kwargs parameters to allow constructing with keyword arguments or positional arguments. * `Contract.pastEvents` now allows you to specify a `fromBlock or ``toBlock.` Previously these were forced to be `'earliest'` and `web3.eth.blockNumber` respectively. * `Contract.call`, `Contract.transact` and `Contract.estimateGas` are now callable as class methods as well as instance methods. When called this way, an address must be provided with the transaction parameter. * `Contract.call`, `Contract.transact` and `Contract.estimateGas` now allow specifying an alternate address for the transaction. * `RPCProvider` now supports the following constructor arguments. * `ssl` for enabling SSL * `connection_timeout` and `network_timeout` for controlling the timeouts for requests. 2.7.1[](#id510 "Link to this heading") ---------------------------------------- * Bugfix: Fix KeyError in merge\_args\_and\_kwargs helper fn. 2.7.0[](#id511 "Link to this heading") ---------------------------------------- * Bugfix for usage of block identifiers ‘latest’, ‘earliest’, ‘pending’ * Sphinx documentation * Non-data transactions now default to 90000 gas. * Web3 object now has helpers set as static methods rather than being set at initialization. * RPCProvider now takes a `path` parameter to allow configuration for requests to go to paths other than `/`. 2.6.0[](#id512 "Link to this heading") ---------------------------------------- * TestRPCProvider no longer dumps logging output to stdout and stderr. * Bugfix for return types of `address[]` * Bugfix for event data types of `address` 2.5.0[](#id513 "Link to this heading") ---------------------------------------- * All transactions which contain a `data` element will now have their gas automatically estimated with 100k additional buffer. This was previously only true with transactions initiated from a `Contract` object. 2.4.0[](#id514 "Link to this heading") ---------------------------------------- * Contract functions can now be called using keyword arguments. 2.3.0[](#id515 "Link to this heading") ---------------------------------------- * Upstream fixes for filters * Filter APIs `on` and `pastEvents` now callable as both instance and class methods. 2.2.0[](#id516 "Link to this heading") ---------------------------------------- * The filters that come back from the contract `on` and `pastEvents` methods now call their callbacks with the same data format as `web3.js`. 2.1.1[](#id517 "Link to this heading") ---------------------------------------- * Cast RPCProvider port to an integer. 2.1.0[](#id518 "Link to this heading") ---------------------------------------- * Remove all monkeypatching 2.0.0[](#id519 "Link to this heading") ---------------------------------------- * Pull in downstream updates to proper gevent usage. * Fix `eth_sign` * Bugfix with contract operations mutating the transaction object that is passed in. * More explicit linting ignore statements. 1.9.0[](#id520 "Link to this heading") ---------------------------------------- * BugFix: fix for python3 only `json.JSONDecodeError` handling. 1.8.0[](#id521 "Link to this heading") ---------------------------------------- * BugFix: `RPCProvider` not sending a content-type header * Bugfix: `web3.toWei` now returns an integer instead of a decimal.Decimal 1.7.1[](#id522 "Link to this heading") ---------------------------------------- * `TestRPCProvider` can now be imported directly from `web3` 1.7.0[](#id523 "Link to this heading") ---------------------------------------- * Add `eth.admin` interface. * Bugfix: Format the return value of `web3.eth.syncing` * Bugfix: IPCProvider socket interactions are now more robust. 1.6.0[](#id524 "Link to this heading") ---------------------------------------- * Downstream package upgrades for `eth-testrpc` and `ethereum-tester-client` to handle configuration of the Homestead and DAO fork block numbers. 1.5.0[](#id525 "Link to this heading") ---------------------------------------- * Rename `web3.contract._Contract` to `web3.contract.Contract` to expose it for static analysis and auto completion tools * Allow passing string parameters to functions * Automatically compute gas requirements for contract deployment and * transactions. * Contract Filters * Block, Transaction, and Log filters * `web3.eth.txpool` interface * `web3.eth.mining` interface * Fixes for encoding. 1.4.0[](#id526 "Link to this heading") ---------------------------------------- * Bugfix to allow address types in constructor arguments. 1.3.0[](#id527 "Link to this heading") ---------------------------------------- * Partial implementation of the `web3.eth.contract` interface. 1.2.0[](#id528 "Link to this heading") ---------------------------------------- * Restructure project modules to be more _flat_ * Add ability to run test suite without the _slow_ tests. * Breakup `encoding` utils into smaller modules. * Basic pep8 formatting. * Apply python naming conventions to internal APIs * Lots of minor bugfixes. * Removal of dead code left behind from `1.0.0` refactor. * Removal of `web3/solidity` module. 1.1.0[](#id529 "Link to this heading") ---------------------------------------- * Add missing `isConnected()` method. * Add test coverage for `setProvider()` 1.0.1[](#id530 "Link to this heading") ---------------------------------------- * Specify missing `pyrlp` and `gevent` dependencies 1.0.0[](#id531 "Link to this heading") ---------------------------------------- * Massive refactor to the majority of the app. 0.1.0[](#id532 "Link to this heading") ---------------------------------------- * Initial release --- # Accounts — web3.py 7.6.1 documentation * [](index.html) * Accounts * [View page source](_sources/web3.eth.account.rst.txt) * * * Accounts[](#accounts "Link to this heading") ============================================== Local vs Hosted Nodes[](#local-vs-hosted-nodes "Link to this heading") ------------------------------------------------------------------------ Hosted Node A **hosted** node is controlled by someone else. You may also see these referred to as **remote** nodes. View a list of commercial [node providers](https://ethereum.org/en/developers/docs/nodes-and-clients/nodes-as-a-service/) . Local Node A **local** node is started and controlled by you on your computer. For several reasons (e.g., privacy, security), this is the recommended path, but it requires more resources and work to set up and maintain. See [ethereum.org](https://ethereum.org/en/developers/docs/nodes-and-clients/) for a guided tour. Local vs Hosted Keys[](#local-vs-hosted-keys "Link to this heading") ---------------------------------------------------------------------- An Ethereum private key is a 256-bit (32 bytes) random integer. For each private key, you get one Ethereum address, also known as an Externally Owned Account (EOA). In Python, the private key is expressed as a 32-byte long Python `bytes` object. When a private key is presented to users in a hexadecimal format, it may or may not contain a starting `0x` hexadecimal prefix. Local Private Key A local private key is a locally stored secret you import to your Python application. Please read below how you can create and import a local private key and use it to sign transactions. Hosted Private Key This is a legacy way to use accounts when working with unit test backends like `EthereumTesterProvider` or [Anvil](https://book.getfoundry.sh/reference/anvil/) . Calling `web3.eth.accounts` gives you a predefined list of accounts that have been funded with test ETH. You can use [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") on any of these accounts without further configuration. In the past, around 2015, this was also a way to use private keys in a locally hosted node, but this practice is now discouraged. Warning `web3.eth.send_transaction` does not work with modern node providers, because they relied on a node state and all modern nodes are stateless. You must always use local private keys when working with nodes hosted by someone else. Some Common Uses for Local Private Keys[](#some-common-uses-for-local-private-keys "Link to this heading") ------------------------------------------------------------------------------------------------------------ A very common reason to work with local private keys is to interact with a hosted node. Some common things you might want to do with a Local Private Key are: * [Sign a Transaction](#sign-a-transaction) * [Sign a Contract Transaction](#sign-a-contract-transaction) * [Sign a Message](#sign-a-message) * [Verify a Message](#verify-a-message) Using private keys usually involves `w3.eth.account` in one way or another. Read on for more, or see a full list of things you can do in the docs for [`eth_account.Account`](https://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account "(in eth-account v0.13)") . Creating a Private Key[](#creating-a-private-key "Link to this heading") -------------------------------------------------------------------------- Each Ethereum address has a matching private key. To create a new Ethereum account you can just generate a random number that acts as a private key. * A private key is just a random unguessable, or cryptographically safe, 256-bit integer number * A valid private key is > 0 and < max private key value (a number above the elliptic curve order FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141) * Private keys do not have checksums. To create a private key using web3.py and command line you can do: python \-c "from web3 import Web3; w3 = Web3(); acc = w3.eth.account.create(); print(f'private key={w3.to\_hex(acc.key)}, account={acc.address}')" Which outputs a new private key and an account pair: private key\=0x480c4aec9fa..., account\=0x9202a9d5D2d129CB400a40e00aC822a53ED81167 * _Never store private key with your source_. Use environment variables to store the key. Read more below. * You can also import the raw hex private key to MetaMask and any other wallet - the private key can be shared between your Python code and any number of wallets. Funding a New Account[](#funding-a-new-account "Link to this heading") ------------------------------------------------------------------------ If you create a private key, it comes with its own Ethereum address. By default, the balance of this address is zero. Before you can send any transactions with your account, you need to top up. * For a local test environment (e.g., `EthereumTesterProvider`), any environment is bootstrapped with accounts that have test ETH in them. Move ETH from default accounts to your newly created account. * For public mainnet, you need to buy ETH in a cryptocurrency exchange and send it to your privately controlled account. * For a testnet, find a relevant testnet [faucet](troubleshooting.html#faucets) . Reading a Private Key from an Environment Variable[](#reading-a-private-key-from-an-environment-variable "Link to this heading") ---------------------------------------------------------------------------------------------------------------------------------- In this example we pass the private key to our Python application in an [environment variable](https://en.wikipedia.org/wiki/Environment_variable) . This private key is then added to the transaction signing keychain with `Signing` middleware. If unfamiliar, note that you can [export your private keys from Metamask and other wallets](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key) . Warning * **Never** share your private keys. * **Never** put your private keys in source code. * **Never** commit private keys to a Git repository. Example `account_test_script.py` 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 Example how to run this in UNIX shell: \# Generate a new 256-bit random integer using openssl UNIX command that acts as a private key. \# You can also do: \# python -c "from web3 import Web3; w3 = Web3(); acc = w3.eth.account.create(); print(f'private key={w3.to\_hex(acc.key)}, account={acc.address}')" \# Store this in a safe place, like in your password manager. export PRIVATE\_KEY\=0x\`openssl rand \-hex 32\` \# Run our script python account\_test\_script.py This will print: Your hot wallet address is 0x27C8F899bb69E1501BBB96d09d7477a2a7518918 Extract private key from geth keyfile[](#extract-private-key-from-geth-keyfile "Link to this heading") -------------------------------------------------------------------------------------------------------- Note The amount of available ram should be greater than 1GB. with open('~/.ethereum/keystore/UTC--...--5ce9454909639D2D17A3F753ce7d93fa0b9aB12E') as keyfile: encrypted\_key \= keyfile.read() private\_key \= w3.eth.account.decrypt(encrypted\_key, 'correcthorsebatterystaple') \# tip: do not save the key or password anywhere, especially into a shared source file Sign a Message[](#sign-a-message "Link to this heading") ---------------------------------------------------------- Warning There is no single message format that is broadly adopted with community consensus. Keep an eye on several options, like [EIP-683](https://github.com/ethereum/EIPs/pull/683) , [EIP-712](https://github.com/ethereum/EIPs/pull/712) , and [EIP-719](https://github.com/ethereum/EIPs/pull/719) . Consider the [`w3.eth.sign()`](web3.eth.html#web3.eth.Eth.sign "web3.eth.Eth.sign") approach be deprecated. For this example, we will use the same message hashing mechanism that is provided by [`w3.eth.sign()`](web3.eth.html#web3.eth.Eth.sign "web3.eth.Eth.sign") . \>>> from web3 import Web3, EthereumTesterProvider \>>> from eth\_account.messages import encode\_defunct \>>> w3 \= Web3(EthereumTesterProvider()) \>>> msg \= "I♥SF" \>>> private\_key \= b"\\xb2\\\\}\\xb3\\x1f\\xee\\xd9\\x12''\\xbf\\t9\\xdcv\\x9a\\x96VK-\\xe4\\xc4rm\\x03\[6\\xec\\xf1\\xe5\\xb3d"\ \>>> message \= encode\_defunct(text\=msg)\ \>>> signed\_message \= w3.eth.account.sign\_message(message, private\_key\=private\_key)\ \>>> signed\_message\ SignedMessage(message\_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'),\ r=104389933075820307925104709181714897380569894203213074526835978196648170704563,\ s=28205917190874851400050446352651915501321657673772411533993420917949420456142,\ v=28,\ signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c'))\ \ Verify a Message[](#verify-a-message "Link to this heading")\ \ --------------------------------------------------------------\ \ With the original message text and a signature:\ \ \>>> message \= encode\_defunct(text\="I♥SF")\ \>>> w3.eth.account.recover\_message(message, signature\=signed\_message.signature)\ '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'\ \ Prepare message for ecrecover in Solidity[](#prepare-message-for-ecrecover-in-solidity "Link to this heading")\ \ ----------------------------------------------------------------------------------------------------------------\ \ Let’s say you want a contract to validate a signed message, like if you’re making payment channels, and you want to validate the value in Remix or web3.js.\ \ You might have produced the signed\_message locally, as in [Sign a Message](#sign-a-message)\ . If so, this will prepare it for Solidity:\ \ \>>> 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'))\ \ \>>> ec\_recover\_args \= (msghash, v, r, s) \= (\ ... Web3.to\_hex(signed\_message.message\_hash),\ ... signed\_message.v,\ ... to\_32byte\_hex(signed\_message.r),\ ... to\_32byte\_hex(signed\_message.s),\ ... )\ \>>> ec\_recover\_args\ ('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750',\ 28,\ '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3',\ '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce')\ \ Instead, you might have received a message and a signature encoded to hex. Then this will prepare it for Solidity:\ \ \>>> from web3 import Web3\ \>>> from eth\_account.messages import encode\_defunct, \_hash\_eip191\_message\ \ \>>> hex\_message \= '0x49e299a55346'\ \>>> hex\_signature \= '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c'\ \ \# ecrecover in Solidity expects an encoded version of the message\ \ \# - encode the message\ \>>> message \= encode\_defunct(hexstr\=hex\_message)\ \ \# - hash the message explicitly\ \>>> message\_hash \= \_hash\_eip191\_message(message)\ \ \# Remix / web3.js expect the message hash to be encoded to a hex string\ \>>> hex\_message\_hash \= Web3.to\_hex(message\_hash)\ \ \# ecrecover in Solidity expects the signature to be split into v as a uint8,\ \# and r, s as a bytes32\ \# Remix / web3.js expect r and s to be encoded to hex\ \>>> sig \= Web3.to\_bytes(hexstr\=hex\_signature)\ \>>> v, hex\_r, hex\_s \= Web3.to\_int(sig\[\-1\]), Web3.to\_hex(sig\[:32\]), Web3.to\_hex(sig\[32:64\])\ \ \# ecrecover in Solidity takes the arguments in order = (msghash, v, r, s)\ \>>> ec\_recover\_args \= (hex\_message\_hash, v, hex\_r, hex\_s)\ \>>> ec\_recover\_args\ ('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750',\ 28,\ '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3',\ '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce')\ \ Verify a message with ecrecover in Solidity[](#verify-a-message-with-ecrecover-in-solidity "Link to this heading")\ \ --------------------------------------------------------------------------------------------------------------------\ \ Create a simple ecrecover contract in [Remix](https://remix.ethereum.org/)\ :\ \ pragma solidity ^0.4.19;\ \ contract Recover {\ function ecr (bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public pure\ returns (address sender) {\ return ecrecover(msgh, v, r, s);\ }\ }\ \ Then call ecr with these arguments from [Prepare message for ecrecover in Solidity](#prepare-message-for-ecrecover-in-solidity)\ in Remix, `"0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750", 28, "0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3", "0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce"`\ \ The message is verified, because we get the correct sender of the message back in response: `0x5ce9454909639d2d17a3f753ce7d93fa0b9ab12e`.\ \ Sign a Transaction[](#sign-a-transaction "Link to this heading")\ \ ------------------------------------------------------------------\ \ Create a transaction, sign it locally, and then send it to your node for broadcasting, with [`send_raw_transaction()`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction")\ .\ \ \>>> transaction \= {\ ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55',\ ... 'value': 1000000000,\ ... 'gas': 2000000,\ ... 'maxFeePerGas': 2000000000,\ ... 'maxPriorityFeePerGas': 1000000000,\ ... 'nonce': 0,\ ... 'chainId': 1,\ ... 'type': '0x2', \# the type is optional and, if omitted, will be interpreted based on the provided transaction parameters\ ... 'accessList': ( \# accessList is optional for dynamic fee transactions\ ... {\ ... 'address': '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae',\ ... 'storageKeys': (\ ... '0x0000000000000000000000000000000000000000000000000000000000000003',\ ... '0x0000000000000000000000000000000000000000000000000000000000000007',\ ... )\ ... },\ ... {\ ... 'address': '0xbb9bc244d798123fde783fcc1c72d3bb8c189413',\ ... 'storageKeys': ()\ ... },\ ... )\ ... }\ \>>> key \= '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318'\ \>>> signed \= w3.eth.account.sign\_transaction(transaction, key)\ \>>> signed.raw\_transaction\ HexBytes('0x02f8e20180843b9aca008477359400831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080f872f85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000007d694bb9bc244d798123fde783fcc1c72d3bb8c189413c001a0b9ec671ccee417ff79e06e9e52bfa82b37cf1145affde486006072ca7a11cf8da0484a9beea46ff6a90ac76e7bbf3718db16a8b4b09cef477fb86cf4e123d98fde')\ \>>> signed.hash\ HexBytes('0xe85ce7efa52c16cb5c469c7bde54fbd4911639fdfde08003f65525a85076d915')\ \>>> signed.r\ 84095564551732371065849105252408326384410939276686534847013731510862163857293\ \>>> signed.s\ 32698347985257114675470251181312399332782188326270244072370350491677872459742\ \>>> signed.v\ 1\ \ \# When you run send\_raw\_transaction, you get back the hash of the transaction:\ \>>> w3.eth.send\_raw\_transaction(signed.raw\_transaction) \ '0xe85ce7efa52c16cb5c469c7bde54fbd4911639fdfde08003f65525a85076d915'\ \ Sign a Contract Transaction[](#sign-a-contract-transaction "Link to this heading")\ \ ------------------------------------------------------------------------------------\ \ To sign a transaction locally that will invoke a smart contract:\ \ 1. Initialize your [`Contract`](web3.eth.html#web3.eth.Eth.contract "web3.eth.Eth.contract")\ object\ \ 2. Build the transaction\ \ 3. Sign the transaction, with [`w3.eth.account.sign_transaction()`](https://eth-account.readthedocs.io/en/latest/eth_account.html#eth_account.account.Account.sign_transaction "(in eth-account v0.13)")\ \ 4. Broadcast the transaction with [`send_raw_transaction()`](web3.eth.html#web3.eth.Eth.send_raw_transaction "web3.eth.Eth.send_raw_transaction")\ \ \ \# When running locally, execute the statements found in the file linked below to load the EIP20\_ABI variable.\ \# See: https://github.com/carver/ethtoken.py/blob/v0.0.1-alpha.4/ethtoken/abi.py\ \ \>>> from web3 import Web3, EthereumTesterProvider\ \>>> w3 \= Web3(EthereumTesterProvider())\ \ \>>> unicorns \= w3.eth.contract(address\="0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359", abi\=EIP20\_ABI)\ \ \>>> nonce \= w3.eth.get\_transaction\_count('0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E') \ \ \# Build a transaction that invokes this contract's function, called transfer\ \>>> unicorn\_txn \= unicorns.functions.transfer(\ ... '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',\ ... 1,\ ... ).build\_transaction({\ ... 'chainId': 1,\ ... 'gas': 70000,\ ... 'maxFeePerGas': w3.to\_wei('2', 'gwei'),\ ... 'maxPriorityFeePerGas': w3.to\_wei('1', 'gwei'),\ ... 'nonce': nonce,\ ... })\ \ \>>> unicorn\_txn\ {'value': 0,\ 'chainId': 1,\ 'gas': 70000,\ 'maxFeePerGas': 2000000000,\ 'maxPriorityFeePerGas': 1000000000,\ 'nonce': 0,\ 'to': '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359',\ 'data': '0xa9059cbb000000000000000000000000fb6916095ca1df60bb79ce92ce3ea74c37c5d3590000000000000000000000000000000000000000000000000000000000000001'}\ \ \>>> private\_key \= b"\\xb2\\\\}\\xb3\\x1f\\xee\\xd9\\x12''\\xbf\\t9\\xdcv\\x9a\\x96VK-\\xe4\\xc4rm\\x03\[6\\xec\\xf1\\xe5\\xb3d"\ \>>> signed\_txn \= w3.eth.account.sign\_transaction(unicorn\_txn, private\_key\=private\_key)\ \>>> signed\_txn.hash\ HexBytes('0x748db062639a45e519dba934fce09c367c92043867409160c9989673439dc817')\ \>>> signed\_txn.raw\_transaction\ HexBytes('0x02f8b00180843b9aca0084773594008301117094fb6916095ca1df60bb79ce92ce3ea74c37c5d35980b844a9059cbb000000000000000000000000fb6916095ca1df60bb79ce92ce3ea74c37c5d3590000000000000000000000000000000000000000000000000000000000000001c001a0cec4150e52898cf1295cc4020ac0316cbf186071e7cdc5ec44eeb7cdda05afa2a06b0b3a09c7fb0112123c0bef1fd6334853a9dcf3cb5bab3ccd1f5baae926d449')\ \>>> signed\_txn.r\ 93522894155654168208483453926995743737629589441154283159505514235904280342434\ \>>> signed\_txn.s\ 48417310681110102814014302147799665717176259465062324746227758019974374282313\ \>>> signed\_txn.v\ 1\ \ \>>> w3.eth.send\_raw\_transaction(signed\_txn.raw\_transaction) \ \ \# When you run send\_raw\_transaction, you get the same result as the hash of the transaction:\ \>>> w3.to\_hex(w3.keccak(signed\_txn.raw\_transaction))\ '0x748db062639a45e519dba934fce09c367c92043867409160c9989673439dc817' --- # Contracts — web3.py 7.6.1 documentation * [](index.html) * Contracts * [View page source](_sources/web3.contract.rst.txt) * * * Contracts[](#contracts "Link to this heading") ================================================ Smart contracts are programs deployed to the Ethereum network. See the [ethereum.org docs](https://ethereum.org/en/developers/docs/smart-contracts) for a proper introduction. Interacting with deployed contracts[](#interacting-with-deployed-contracts "Link to this heading") ---------------------------------------------------------------------------------------------------- In order to use an existing contract, you’ll need its deployed address and its ABI. Both can be found using block explorers, like Etherscan. Once you instantiate a contract instance, you can read data and execute transactions. \# Configure w3, e.g., w3 = Web3(...) address \= '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F988' abi \= '\[{"inputs":\[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"minter\_","type":"address"},...'\ contract\_instance \= w3.eth.contract(address\=address, abi\=abi)\ \ \# read state:\ contract\_instance.functions.storedValue().call()\ \# 42\ \ \# update state:\ tx\_hash \= contract\_instance.functions.updateValue(43).transact()\ \ Contract Deployment Example[](#contract-deployment-example "Link to this heading")\ \ ------------------------------------------------------------------------------------\ \ To run this example, you will need to install a few extra features:\ \ * The sandbox node provided by eth-tester. You can install it with:\ \ \ $ pip install \-U "web3\[tester\]"\ \ * `py-solc-x`. This is the supported route to installing the solidity compiler `solc`. You can install it with:\ \ \ $ pip install py-solc-x\ \ After `py-solc-x` is installed, you will need to install a version of `solc`. You can install the latest version via a new REPL with:\ \ \>>> from solcx import install\_solc\ \>>> install\_solc(version\='latest')\ \ You should now be set up to compile and deploy a contract.\ \ The following example runs through these steps:\ \ 1. Compile Solidity contract into bytecode and an ABI\ \ 2. Initialize a Contract instance\ \ 3. Deploy the contract using the Contract instance to initiate a transaction\ \ 4. Interact with the contract functions using the Contract instance\ \ \ \>>> 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'\ \ Contract Factories[](#contract-factories "Link to this heading")\ \ ------------------------------------------------------------------\ \ These factories are not intended to be initialized directly. Instead, create contract objects using the [`w3.eth.contract()`](web3.eth.html#web3.eth.Eth.contract "web3.eth.Eth.contract")\ method. By default, the contract factory is [`Contract`](#web3.contract.Contract "web3.contract.Contract")\ .\ \ _class_ web3.contract.Contract(_address_)[](#web3.contract.Contract "Link to this definition")\ \ Contract provides a default interface for deploying and interacting with Ethereum smart contracts.\ \ The address parameter can be a hex address or an ENS name, like `mycontract.eth`.\ \ Properties[](#properties "Link to this heading")\ \ --------------------------------------------------\ \ Each Contract Factory exposes the following properties.\ \ Contract.address[](#web3.contract.Contract.address "Link to this definition")\ \ The hexadecimal encoded 20-byte address of the contract, or an ENS name. May be `None` if not provided during factory creation.\ \ Contract.abi[](#web3.contract.Contract.abi "Link to this definition")\ \ The contract `abi`, or Application Binary Interface, specifies how a contract can be interacted with. Without an `abi`, the contract cannot be decoded. The `abi` enables the Contract instance to expose functions and events as object properties.\ \ For further details, see the [Solidity ABI specification](https://docs.soliditylang.org/en/develop/abi-spec.html)\ .\ \ Contract.bytecode[](#web3.contract.Contract.bytecode "Link to this definition")\ \ The contract bytecode string. May be `None` if not provided during factory creation.\ \ Contract.bytecode\_runtime[](#web3.contract.Contract.bytecode_runtime "Link to this definition")\ \ The runtime part of the contract bytecode string. May be `None` if not provided during factory creation.\ \ Contract.decode\_tuples[](#web3.contract.Contract.decode_tuples "Link to this definition")\ \ If a Tuple/Struct is returned by a contract function, this flag defines whether to apply the field names from the ABI to the returned data. If False, the returned value will be a normal Python `Tuple`. If True, the returned value will be a Python `NamedTuple` of the class `ABIDecodedNamedTuple`.\ \ NamedTuples have some restrictions regarding field names. web3.py sets `NamedTuple`’s `rename=True`, so disallowed field names may be different than expected. See the [Python docs](https://docs.python.org/3/library/collections.html#collections.namedtuple)\ for more information.\ \ Defaults to `False` if not provided during factory creation.\ \ Contract.functions[](#web3.contract.Contract.functions "Link to this definition")\ \ This provides access to contract functions as attributes. For example: `myContract.functions.MyMethod()`. The exposed contract functions are classes of the type [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ .\ \ Contract.events[](#web3.contract.Contract.events "Link to this definition")\ \ This provides access to contract events as attributes. For example: `myContract.events.MyEvent()`. The exposed contract events are classes of the type [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ .\ \ Methods[](#methods "Link to this heading")\ \ --------------------------------------------\ \ Method doctests use the following ABI and bytecode.\ \ \>>> bytecode \= '6060604052341561000c57fe5b604051602080610acb833981016040528080519060200190919050505b620f42408114151561003b5760006000fd5b670de0b6b3a76400008102600281905550600254600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b505b610a27806100a46000396000f30060606040523615610097576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde0314610099578063095ea7b31461013257806318160ddd1461018957806323b872dd146101af578063313ce5671461022557806370a082311461025157806395d89b411461029b578063a9059cbb14610334578063dd62ed3e1461038b575bfe5b34156100a157fe5b6100a96103f4565b60405180806020018281038252838181518152602001915080519060200190808383600083146100f8575b8051825260208311156100f8576020820191506020810190506020830392506100d4565b505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013a57fe5b61016f600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061042e565b604051808215151515815260200191505060405180910390f35b341561019157fe5b610199610521565b6040518082815260200191505060405180910390f35b34156101b757fe5b61020b600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610527565b604051808215151515815260200191505060405180910390f35b341561022d57fe5b610235610791565b604051808260ff1660ff16815260200191505060405180910390f35b341561025957fe5b610285600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610796565b6040518082815260200191505060405180910390f35b34156102a357fe5b6102ab6107e0565b60405180806020018281038252838181518152602001915080519060200190808383600083146102fa575b8051825260208311156102fa576020820191506020810190506020830392506102d6565b505050905090810190601f1680156103265780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561033c57fe5b610371600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061081a565b604051808215151515815260200191505060405180910390f35b341561039357fe5b6103de600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610973565b6040518082815260200191505060405180910390f35b604060405190810160405280600981526020017f54657374546f6b656e000000000000000000000000000000000000000000000081525081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60025481565b600081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410806105f1575081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054105b156105fc5760006000fd5b81600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b9392505050565b601281565b6000600060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b604060405190810160405280600481526020017f544553540000000000000000000000000000000000000000000000000000000081525081565b600081600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156108695760006000fd5b81600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b929150505600a165627a7a723058205071371ee2a4a1be3c96e77d939cdc26161a256fdd638efc08bd33dfc65d3b850029'\ \>>> abi \= '\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_spender","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_from","type":"address"},{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"},{"name":"\_spender","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"inputs":\[{"name":"\_totalSupply","type":"uint256"}\],"payable":false,"type":"constructor","stateMutability":"nonpayable"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Approval","type":"event"}\]'\ \>>> contract \= w3.eth.contract(abi\=abi, bytecode\=bytecode)\ \ Each Contract Factory exposes the following methods.\ \ _classmethod_ Contract.constructor(_\*args_, _\*\*kwargs).transact(transaction=None_)[](#web3.contract.Contract.constructor "Link to this definition")\ \ Construct and deploy a contract by sending a new public transaction.\ \ If provided `transaction` should be a dictionary conforming to the `web3.eth.send_transaction(transaction)` method. This value may not contain the keys `data` or `to`.\ \ If the contract takes constructor parameters they should be provided as positional arguments or keyword arguments.\ \ If any of the arguments specified in the ABI are an `address` type, they will accept ENS names.\ \ If a `gas` value is not provided, then the `gas` value for the deployment transaction will be created using the `web3.eth.estimate_gas()` method.\ \ Returns the transaction hash for the deploy transaction.\ \ \>>> deploy\_txn \= contract.constructor(1000000).transact({'from': w3.eth.accounts\[0\], 'gas': 899000, 'gasPrice': Web3.to\_wei(1, 'gwei')})\ \>>> txn\_receipt \= w3.eth.get\_transaction\_receipt(deploy\_txn)\ \>>> txn\_receipt\['contractAddress'\]\ '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b'\ \ _classmethod_ Contract.constructor(_\*args_, _\*\*kwargs).estimate\_gas(transaction=None_, _block\_identifier=None_)\ \ Estimate gas for constructing and deploying the contract.\ \ This method behaves the same as the `Contract.constructor(*args, **kwargs).transact()` method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion.\ \ The `block_identifier` parameter is passed directly to the call at the end portion of the function call.\ \ Returns the amount of gas consumed which can be used as a gas estimate for executing this transaction publicly.\ \ Returns the gas needed to deploy the contract.\ \ \>>> contract.constructor(1000000).estimate\_gas()\ 664971\ \ _classmethod_ Contract.constructor(_\*args_, _\*\*kwargs).build\_transaction(transaction=None_)\ \ Construct the contract deploy transaction bytecode data.\ \ If the contract takes constructor parameters they should be provided as positional arguments or keyword arguments.\ \ If any of the `args` specified in the ABI are an `address` type, they will accept ENS names.\ \ Returns the transaction dictionary that you can pass to send\_transaction method.\ \ \>>> transaction \= {\ ... 'gas': 664971,\ ... 'chainId': 131277322940537\ ... }\ \>>> contract\_data \= contract.constructor(1000000).build\_transaction(transaction)\ \>>> w3.eth.send\_transaction(contract\_data)\ HexBytes('0x40c51804800dee88e14e69826cfe51bc5f25f61935331e8aa6d8d7771fb36350')\ \ _classmethod_ Contract.events.your\_event\_name.create\_filter(_from\_block\=None_, _to\_block\='latest'_, _argument\_filters\={}_, _topics\=\[\]_)[](#web3.contract.Contract.events.your_event_name.create_filter "Link to this definition")\ \ Creates a new event filter, an instance of [`web3.utils.filters.LogFilter`](filters.html#web3.utils.filters.LogFilter "web3.utils.filters.LogFilter")\ .\ \ * `from_block` is a mandatory field. Defines the starting block (exclusive) filter block range. It can be either the starting block number, or ‘latest’ for the last mined block, or ‘pending’ for unmined transactions. In the case of `from_block`, ‘latest’ and ‘pending’ set the ‘latest’ or ‘pending’ block as a static value for the starting filter block.\ \ * `to_block` optional. Defaults to ‘latest’. Defines the ending block (inclusive) in the filter block range. Special values ‘latest’ and ‘pending’ set a dynamic range that always includes the ‘latest’ or ‘pending’ blocks for the filter’s upper block range.\ \ * `address` optional. Defaults to the contract address. The filter matches the event logs emanating from `address`.\ \ * `argument_filters`, optional. Expects a dictionary of argument names and values. When provided event logs are filtered for the event argument values. Event arguments can be both indexed or unindexed. Indexed values will be translated to their corresponding topic arguments. Unindexed arguments will be filtered using a regular expression.\ \ * `topics` optional, accepts the standard JSON-RPC topics argument. See the JSON-RPC documentation for [eth\_newFilter](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter)\ more information on the `topics` parameters.\ \ \ \>>> filter \= contract.events.Transfer.create\_filter(from\_block\='latest')\ \ _classmethod_ Contract.events.your\_event\_name.build\_filter()[](#web3.contract.Contract.events.your_event_name.build_filter "Link to this definition")\ \ Creates a EventFilterBuilder instance with the event abi, and the contract address if called from a deployed contract instance. The EventFilterBuilder provides a convenient way to construct the filter parameters with value checking against the event abi. It allows for defining multiple match values or of single values through the match\_any and match\_single methods.\ \ \>>> filter\_builder \= contract.events.Transfer.build\_filter()\ \>>> filter\_builder.from\_block \= "latest"\ \>>> filter\_builder.args\['from'\].match\_any(w3.eth.accounts\[0\])\ \>>> filter\_builder.args\['to'\].match\_single(w3.eth.accounts\[1\])\ \>>> filter\_builder.args\['value'\].match\_single(10000)\ \>>> filter\_instance \= filter\_builder.deploy(w3)\ \ The `deploy` method returns a [`web3.utils.filters.LogFilter`](filters.html#web3.utils.filters.LogFilter "web3.utils.filters.LogFilter")\ instance from the filter parameters generated by the filter builder. Defining multiple match values for array arguments can be accomplished easily with the filter builder:\ \ \>>> filter\_builder \= contract.events.Transfer.build\_filter()\ \>>> filter\_builder.args\['to'\].match\_any(w3.eth.accounts\[0\], w3.eth.accounts\[1\])\ \ The filter builder blocks already defined filter parameters from being changed.\ \ \>>> filter\_builder \= contract.events.Transfer.build\_filter()\ \>>> filter\_builder.from\_block \= "latest"\ \>>> filter\_builder.from\_block \= 0\ Traceback (most recent call last):\ web3.exceptions.Web3ValueError: from\_block is already set to 'latest'. Resetting filter parameters is not permitted\ \ _classmethod_ Contract.encode\_abi(_abi\_element\_identifier_, _args\=None_, _kwargs\=None_, _data\=None_)[](#web3.contract.Contract.encode_abi "Link to this definition")\ \ Encodes the arguments using the Ethereum ABI for the contract function that matches the given `abi_element_identifier` and arguments `args`. The `data` parameter defaults to the function selector.\ \ \>>> contract.encode\_abi("approve", args\=\[w3.eth.accounts\[0\], 10\])\ '0x095ea7b30000000000000000000000007e5f4552091a69125d5dfcb7b8c2659029395bdf000000000000000000000000000000000000000000000000000000000000000a'\ \ _classmethod_ Contract.all\_events()[](#web3.contract.Contract.all_events "Link to this definition")\ \ Returns a list of all the events present in a Contract where every event is an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ .\ \ \>>> contract.all\_events()\ \[, \]\ \ _classmethod_ Contract.get\_event\_by\_signature(_signature_)[](#web3.contract.Contract.get_event_by_signature "Link to this definition")\ \ Searches for a distinct event with matching signature. Returns an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ upon finding a match. Raises `Web3ValueError` if no match is found.\ \ \>>> contract.get\_event\_by\_signature('Transfer(address,address,uint256)')\ \ \ _classmethod_ Contract.find\_events\_by\_name(_name_)[](#web3.contract.Contract.find_events_by_name "Link to this definition")\ \ Searches for all events matching the provided name. Returns a list of matching events where every event is an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ . Returns an empty list when no match is found.\ \ \>>> contract.find\_events\_by\_name('Transfer')\ \[\]\ \ _classmethod_ Contract.get\_event\_by\_name(_name_)[](#web3.contract.Contract.get_event_by_name "Link to this definition")\ \ Searches for a distinct event matching the name. Returns an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ upon finding a match. Raises `Web3ValueError` if no match is found or if multiple matches are found.\ \ \>>> contract.get\_event\_by\_name('Approval')\ \ \ _classmethod_ Contract.find\_events\_by\_selector(_selector_)[](#web3.contract.Contract.find_events_by_selector "Link to this definition")\ \ Searches for all events matching the provided selector. Returns a list of matching events where every event is an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ . Returns an empty list when no match is found.\ \ \>>> contract.find\_events\_by\_selector('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925')\ \[\]\ \ _classmethod_ Contract.get\_event\_by\_selector(_selector_)[](#web3.contract.Contract.get_event_by_selector "Link to this definition")\ \ Searches for a distinct event with matching selector. The selector can be a hexadecimal string, bytes or int. Returns an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ upon finding a match. Raises `Web3ValueError` if no match is found.\ \ \>>> contract.get\_event\_by\_selector('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925')\ \ \>>> contract.get\_event\_by\_selector(b'\\x8c\[\\xe1\\xe5\\xeb\\xec}\[\\xd1OqB}\\x1e\\x84\\xf3\\xdd\\x03\\x14\\xc0\\xf7\\xb2)\\x1e\[ \\n\\xc8\\xc7\\xc3\\xb9%')\ \ \>>> contract.get\_event\_by\_selector(0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925)\ \ \ _classmethod_ Contract.find\_events\_by\_topic(_topic_)[](#web3.contract.Contract.find_events_by_topic "Link to this definition")\ \ Searches for all events matching the provided topic. Returns a list of matching events where every event is an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ . Returns an empty list when no match is found.\ \ \>>> contract.find\_events\_by\_topic('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925')\ \[\]\ \ _classmethod_ Contract.get\_event\_by\_topic(_topic_)[](#web3.contract.Contract.get_event_by_topic "Link to this definition")\ \ Searches for a distinct event with matching topic. The topic is a hexadecimal string. Returns an instance of [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ upon finding a match. Raises `Web3ValueError` if no match is found.\ \ \>>> contract.get\_event\_by\_topic('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925')\ \ \ _classmethod_ Contract.all\_functions()[](#web3.contract.Contract.all_functions "Link to this definition")\ \ Returns a list of all the functions present in a Contract where every function is an instance of [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ .\ \ \>>> contract.all\_functions()\ \[, , , , , , , , \]\ \ _classmethod_ Contract.get\_function\_by\_signature(_signature_)[](#web3.contract.Contract.get_function_by_signature "Link to this definition")\ \ Searches for a distinct function with matching signature. Returns an instance of [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ upon finding a match. Raises `Web3ValueError` if no match is found.\ \ \>>> contract.get\_function\_by\_signature('approve(address,uint256)')\ \ \ _classmethod_ Contract.find\_functions\_by\_name(_name_)[](#web3.contract.Contract.find_functions_by_name "Link to this definition")\ \ Searches for all functions matching the name. Returns a list of matching functions where every function is an instance of [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ . Returns an empty list when no match is found.\ \ \>>> contract.find\_functions\_by\_name('transferFrom')\ \[\]\ \ _classmethod_ Contract.get\_function\_by\_name(_name_)[](#web3.contract.Contract.get_function_by_name "Link to this definition")\ \ Searches for a distinct function with matching name. Returns an instance of [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ upon finding a match. Raises `Web3ValueError` if no match is found or if multiple matches are found.\ \ \>>> contract.get\_function\_by\_name('decimals')\ \ \ _classmethod_ Contract.get\_function\_by\_selector(_selector_)[](#web3.contract.Contract.get_function_by_selector "Link to this definition")\ \ Searches for a distinct function with matching selector. The selector can be a hexadecimal string, bytes or int. Returns an instance of [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ upon finding a match. Raises `Web3ValueError` if no match is found.\ \ \>>> contract.get\_function\_by\_selector('0xdd62ed3e')\ \ \>>> contract.get\_function\_by\_selector(b'\\xddb\\xed\>')\ \ \>>> contract.get\_function\_by\_selector(0xdd62ed3e)\ \ \ _classmethod_ Contract.find\_functions\_by\_args(_\*args_)[](#web3.contract.Contract.find_functions_by_args "Link to this definition")\ \ Searches for all function with matching args. Returns a list of matching functions where every function is an instance of [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ . Returns an empty list when no match is found.\ \ \>>> contract.find\_functions\_by\_args(w3.eth.accounts\[0\], 10000)\ \[, \]\ \ _classmethod_ Contract.get\_function\_by\_args(_\*args_)[](#web3.contract.Contract.get_function_by_args "Link to this definition")\ \ Searches for a distinct function with matching args. Returns an instance of [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ upon finding a match. Raises `ValueError` if no match is found or if multiple matches are found.\ \ \>>> contract.get\_function\_by\_args(w3.eth.accounts\[0\], w3.eth.accounts\[1\], 10000)\ \ \ Note\ \ `Contract` methods `all_functions`, `get_function_by_signature`, `find_functions_by_name`, `get_function_by_name`, `get_function_by_selector`, `find_functions_by_args` and `get_function_by_args` can only be used when abi is provided to the contract.\ \ Note\ \ web3.py rejects the initialization of contracts that have more than one function with the same selector or signature. eg. `blockHashAddendsInexpansible(uint256)` and `blockHashAskewLimitary(uint256)` have the same selector value equal to `0x00000000`. A contract containing both of these functions will be rejected.\ \ Disabling Strict Checks for Bytes Types[](#disabling-strict-checks-for-bytes-types "Link to this heading")\ \ ------------------------------------------------------------------------------------------------------------\ \ By default, web3 is strict when it comes to hex and bytes values, as of `v6`. If an abi specifies a byte size, but the value that gets passed in is not the specified size, web3 will invalidate the value. For example, if an abi specifies a type of `bytes4`, web3 will invalidate the following values:\ \ | | |\ | --- | --- |Invalid byte and hex strings with strict (default) bytes4 type checking[](#id9 "Link to this table")\ \ | Input | Reason |\ | --- | --- |\ | `''` | Needs to be prefixed with a “0x” to be interpreted as an empty hex string |\ | `2` | Wrong type |\ | `'ah'` | String is not valid hex |\ | `'1234'` | Needs to either be a bytestring (b’1234’) or be a hex value of the right size, prefixed with 0x (in this case: ‘0x31323334’) |\ | `b''` | Needs to have exactly 4 bytes |\ | `b'ab'` | Needs to have exactly 4 bytes |\ | `'0xab'` | Needs to have exactly 4 bytes |\ | `'0x6162636464'` | Needs to have exactly 4 bytes |\ \ However, you may want to be less strict with acceptable values for bytes types. This may prove useful if you trust that values coming through are what they are meant to be with respect to the ABI. In this case, the automatic padding might be convenient for inferred types. For this, you can set the `w3.strict_bytes_type_checking()` flag to `False`, which is available on the Web3 instance. A Web3 instance which has this flag set to `False` will have a less strict set of rules on which values are accepted. A `bytes` type will allow values as a hex string, a bytestring, or a regular Python string that can be decoded as a hex. 0x-prefixed hex strings are also not required.\ \ > * A Python string that is not prefixed with `0x` is valid.\ > \ > * A bytestring whose length is less than the specified byte size is valid.\ > \ \ | | |\ | --- | --- |Valid byte and hex strings for a non-strict bytes4 type[](#id10 "Link to this table")\ \ | Input | Normalizes to |\ | --- | --- |\ | `''` | `b'\x00\x00\x00\x00'` |\ | `'0x'` | `b'\x00\x00\x00\x00'` |\ | `b''` | `b'\x00\x00\x00\x00'` |\ | `b'ab'` | `b'ab\x00\x00'` |\ | `'0xab'` | `b'\xab\x00\x00\x00'` |\ | `'1234'` | `b'\x124\x00\x00'` |\ | `'0x61626364'` | `b'abcd'` |\ | `'1234'` | `b'1234'` |\ \ Taking the following contract code as an example:\ \ \>>> \# 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..."\ \ \>>> arrays\_contract\_instance \= w3.eth.contract(abi\=abi, bytecode\=bytecode)\ \ \>>> tx\_hash \= arrays\_contract\_instance.constructor(\[b'bb'\]).transact()\ \>>> tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash)\ \>>> arrays\_contract \= w3.eth.contract(\ ... address\=tx\_receipt.contractAddress,\ ... abi\=abi\ ... )\ \>>> arrays\_contract.functions.getBytes2Value().call()\ \[b'bb'\]\ \ \>>> \# set value with appropriate byte size\ \>>> arrays\_contract.functions.setBytes2Value(\[b'aa'\]).transact({'gas': 420000, "maxPriorityFeePerGas": 10 \*\* 9, "maxFeePerGas": 10 \*\* 9})\ HexBytes('0xcb95151142ea56dbf2753d70388aef202a7bb5a1e323d448bc19f1d2e1fe3dc9')\ \>>> \# check value\ \>>> arrays\_contract.functions.getBytes2Value().call()\ \[b'aa'\]\ \ \>>> \# trying to set value without appropriate size (bytes2) is not valid\ \>>> arrays\_contract.functions.setBytes2Value(\[b'b'\]).transact()\ Traceback (most recent call last):\ ...\ web3.exceptions.MismatchedABI:\ Could not identify the intended function with name\ \>>> \# check value is still b'aa'\ \>>> arrays\_contract.functions.getBytes2Value().call()\ \[b'aa'\]\ \ \>>> \# disabling strict byte checking...\ \>>> w3.strict\_bytes\_type\_checking \= False\ \ \>>> tx\_hash \= arrays\_contract\_instance.constructor(\[b'b'\]).transact()\ \>>> tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash)\ \>>> arrays\_contract \= w3.eth.contract(\ ... address\=tx\_receipt.contractAddress,\ ... abi\=abi\ ... )\ \>>> \# check value is zero-padded... i.e. b'b\\x00'\ \>>> arrays\_contract.functions.getBytes2Value().call()\ \[b'b\\x00'\]\ \ \>>> \# set the flag back to True\ \>>> w3.strict\_bytes\_type\_checking \= True\ \ \>>> arrays\_contract.functions.setBytes2Value(\[b'a'\]).transact()\ Traceback (most recent call last):\ ...\ web3.exceptions.MismatchedABI:\ Could not identify the intended function with name\ \ Contract Functions[](#contract-functions "Link to this heading")\ \ ------------------------------------------------------------------\ \ The named functions exposed through the [`Contract.functions`](#web3.contract.Contract.functions "web3.contract.Contract.functions")\ property are of the ContractFunction type. This class is not to be used directly, but instead through [`Contract.functions`](#web3.contract.Contract.functions "web3.contract.Contract.functions")\ .\ \ For example:\ \ > myContract \= web3.eth.contract(address\=contract\_address, abi\=contract\_abi)\ > twentyone \= myContract.functions.multiply7(3).call()\ \ If you have the function name in a variable, you might prefer this alternative:\ \ > func\_to\_call \= 'multiply7'\ > contract\_func \= myContract.functions\[func\_to\_call\]\ > twentyone \= contract\_func(3).call()\ \ You can also interact with contract functions without parentheses if the function doesn’t take any arguments. For example:\ \ > \>>> myContract.functions.return13.call()\ > 13\ > \>>> myContract.functions.return13().call()\ > 13\ \ In cases where functions are overloaded and use arguments of similar types, a function may resolve to an undesired function when using the method syntax. For example, given two functions with the same name that take a single argument of differing types of `bytes` and `bytes32`. When a reference to `contract.functions.setBytes(b'1')()` is used, the function will resolve as the one that takes `bytes`. If a value is passed that was meant to be 32 bytes but the given argument was off by one, the function reference will still use the one that takes `bytes`.\ \ When in doubt, use explicit function references to the signature. Use bracket notation (`contract.functions["setBytes(bytes32)"](b'')()`) or the contract API contract.get\_function\_by\_signature(“setBytes(bytes32)”) to retrieve the desired function. This will ensure an exception is raised if the argument is not strictly 32 bytes in length.\ \ _class_ web3.contract.ContractFunction[](#web3.contract.ContractFunction "Link to this definition")\ \ ### Attributes[](#attributes "Link to this heading")\ \ The [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ class provides attributes for each function. Access the function attributes through Contract.functions.myMethod.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).abi\_element\_identifier\ \ The signature of the function assigned to the class `__name__` during initialization. Fallback and Receive functions will be assigned as classes `FallbackFn` or `RecieveFn` respectively.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).name\ \ A string representing the function, receive or fallback name.\ \ Use `ContractFunction.signature` when the function arguments are needed.\ \ This is an alias of `ContractFunction.fn_name`.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).signature\ \ A string representing the function, receive or fallback signature.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).selector\ \ A HexStr encoded from the first four bytes of the function signature.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).abi\ \ The function ABI with the type, name, inputs and outputs.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).arguments\ \ A tuple of all function inputs, normalized so that kwargs themselves are flattened into a tuple as returned by `eth_utils.abi.get_normalized_abi_inputs()`.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).argument\_names\ \ The function input names.\ \ ContractFunction.myMethod(\*args, \*\*kwargs).argument\_types\ \ The function input types.\ \ ### Methods[](#id3 "Link to this heading")\ \ [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ provides methods to interact with contract functions. Positional and keyword arguments supplied to the contract function subclass will be used to find the contract function by signature, and forwarded to the contract function when applicable.\ \ [EIP-3668](https://eips.ethereum.org/EIPS/eip-3668)\ introduced support for the `OffchainLookup` revert / CCIP Read support. CCIP Read is set to `True` for calls by default, as recommended in EIP-3668. This is done via a global `global_ccip_read_enabled` flag on the provider. If raising the `OffchainLookup` revert is preferred for a specific call, the `ccip_read_enabled` flag on the call may be set to `False`.\ \ > \>>> \# raises the revert instead of handling the offchain lookup\ > \>>> myContract.functions.revertsWithOffchainLookup(myData).call(ccip\_read\_enabled\=False)\ > \*\*\* web3.exceptions.OffchainLookup\ \ Disabling CCIP Read support can be useful if a transaction needs to be sent to the callback function. In such cases, “preflighting” with an `eth_call`, handling the `OffchainLookup`, and sending the data via a transaction may be necessary. See [CCIP Read support for offchain lookup](#ccip-read-example)\ in the examples section for how to preflight a transaction with a contract call.\ \ Similarly, if CCIP Read is globally set to `False` via the `global_ccip_read_enabled` flag on the provider, it may be enabled on a per-call basis - overriding the global flag. This ensures only explicitly enabled calls will handle the `OffchainLookup` revert appropriately.\ \ > \>>> \# global flag set to \`False\`\ > \>>> w3.provider.global\_ccip\_read\_enabled \= False\ > \ > \>>> \# does not raise the revert since explicitly enabled on the call:\ > \>>> response \= myContract.functions.revertsWithOffchainLookup(myData).call(ccip\_read\_enabled\=True)\ \ If the function called results in a `revert` error, a `ContractLogicError` will be raised. If there is an error message with the error, web3.py attempts to parse the message that comes back and return it to the user as the error string. As of v6.3.0, the raw data is also returned and can be accessed via the `data` attribute on `ContractLogicError`.\ \ ContractFunction.transact(_transaction_)[](#web3.contract.ContractFunction.transact "Link to this definition")\ \ Execute the specified function by sending a new public transaction.\ \ Refer to the following invocation:\ \ myContract.functions.myMethod(\*args, \*\*kwargs).transact(transaction)\ \ The first portion of the function call `myMethod(*args, **kwargs)` selects the appropriate contract function based on the name and provided argument. Arguments can be provided as positional arguments, keyword arguments, or a mix of the two.\ \ The end portion of this function call `transact(transaction)` takes a single parameter which should be a python dictionary conforming to the same format as the `web3.eth.send_transaction(transaction)` method. This dictionary may not contain the keys `data`.\ \ If any of the `args` or `kwargs` specified in the ABI are an `address` type, they will accept ENS names.\ \ If a `gas` value is not provided, then the `gas` value for the method transaction will be created using the `web3.eth.estimate_gas()` method.\ \ Returns the transaction hash.\ \ \>>> token\_contract.functions.transfer(web3.eth.accounts\[1\], 12345).transact()\ "0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd"\ \ ContractFunction.call(_transaction_, _block\_identifier\='latest'_)[](#web3.contract.ContractFunction.call "Link to this definition")\ \ Call a contract function, executing the transaction locally using the `eth_call` API. This will not create a new public transaction.\ \ Refer to the following invocation:\ \ myContract.functions.myMethod(\*args, \*\*kwargs).call(transaction)\ \ This method behaves the same as the [`ContractFunction.transact()`](#web3.contract.ContractFunction.transact "web3.contract.ContractFunction.transact")\ method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion.\ \ Returns the return value of the executed function.\ \ \>>> my\_contract.functions.multiply7(3).call()\ 21\ \>>> token\_contract.functions.myBalance().call({'from': web3.eth.accounts\[0\]})\ 12345 # the token balance for \`web3.eth.accounts\[0\]\`\ \>>> token\_contract.functions.myBalance().call({'from': web3.eth.accounts\[1\]})\ 54321 # the token balance for the account \`web3.eth.accounts\[1\]\`\ \ You can call the method at a historical block using `block_identifier`. Some examples:\ \ \# You can call your contract method at a block number:\ \>>> token\_contract.functions.myBalance().call(block\_identifier\=10)\ \ \# or a number of blocks back from pending,\ \# in this case, the block just before the latest block:\ \>>> token\_contract.functions.myBalance().call(block\_identifier\=-2)\ \ \# or a block hash:\ \>>> token\_contract.functions.myBalance().call(block\_identifier\='0x4ff4a38b278ab49f7739d3a4ed4e12714386a9fdf72192f2e8f7da7822f10b4d')\ \>>> token\_contract.functions.myBalance().call(block\_identifier\=b'O\\xf4\\xa3\\x8b\\'\\x8a\\xb4\\x9fw9\\xd3\\xa4\\xedN\\x12qC\\x86\\xa9\\xfd\\xf7!\\x92\\xf2\\xe8\\xf7\\xdax"\\xf1\\x0bM')\ \ \# Latest is the default, so this is redundant:\ \>>> token\_contract.functions.myBalance().call(block\_identifier\='latest')\ \ \# You can check the state after your pending transactions (if supported by your node):\ \>>> token\_contract.functions.myBalance().call(block\_identifier\='pending')\ \ Passing the `block_identifier` parameter for past block numbers requires that your Ethereum API node is running in the more expensive archive node mode. Normally synced Ethereum nodes will fail with a “missing trie node” error, because Ethereum node may have purged the past state from its database. [More information about archival nodes here](https://ethereum.stackexchange.com/a/84200/620)\ .\ \ ContractFunction.estimate\_gas(_transaction_, _block\_identifier\=None_)[](#web3.contract.ContractFunction.estimate_gas "Link to this definition")\ \ Call a contract function, executing the transaction locally using the `eth_call` API. This will not create a new public transaction.\ \ Refer to the following invocation:\ \ myContract.functions.myMethod(\*args, \*\*kwargs).estimate\_gas(transaction)\ \ This method behaves the same as the [`ContractFunction.transact()`](#web3.contract.ContractFunction.transact "web3.contract.ContractFunction.transact")\ method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion.\ \ Returns the amount of gas consumed which can be used as a gas estimate for executing this transaction publicly.\ \ \>>> my\_contract.functions.multiply7(3).estimate\_gas()\ 42650\ \ Note\ \ The parameter `block_identifier` is not enabled in geth nodes, hence passing a value of `block_identifier` when connected to a geth nodes would result in an error like: `ValueError: {'code': -32602, 'message': 'too many arguments, want at most 1'}`\ \ ContractFunction.build\_transaction(_transaction_)[](#web3.contract.ContractFunction.build_transaction "Link to this definition")\ \ Builds a transaction dictionary based on the contract function call specified.\ \ Refer to the following invocation:\ \ myContract.functions.myMethod(\*args, \*\*kwargs).build\_transaction(transaction)\ \ This method behaves the same as the `Contract.transact()` method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion.\ \ Note\ \ nonce is not returned as part of the transaction dictionary unless it is specified in the first portion of the function call:\ \ \>>> math\_contract.functions.increment(5).build\_transaction({'nonce': 10})\ \ You may use `getTransactionCount()` to get the current nonce for an account. Therefore a shortcut for producing a transaction dictionary with nonce included looks like:\ \ \>>> math\_contract.functions.increment(5).build\_transaction({'nonce': web3.eth.get\_transaction\_count('0xF5...')})\ \ Returns a transaction dictionary. This transaction dictionary can then be sent using [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction")\ .\ \ Additionally, the dictionary may be used for offline transaction signing using `sign_transaction()`.\ \ \>>> math\_contract.functions.increment(5).build\_transaction({'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000})\ {\ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD',\ 'data': '0x7cf5dab00000000000000000000000000000000000000000000000000000000000000005',\ 'value': 0,\ 'gas': 43242,\ 'maxFeePerGas': 2000000000,\ 'maxPriorityFeePerGas': 1000000000,\ 'chainId': 1\ }\ \ ### Fallback Function[](#fallback-function "Link to this heading")\ \ > The Contract Factory also offers an API to interact with the fallback function, which supports four methods like normal functions:\ \ Contract.fallback.call(_transaction_)[](#web3.contract.Contract.fallback.call "Link to this definition")\ \ Call fallback function, executing the transaction locally using the `eth_call` API. This will not create a new public transaction.\ \ Contract.fallback.estimate\_gas(_transaction_)[](#web3.contract.Contract.fallback.estimate_gas "Link to this definition")\ \ Call fallback function and return the gas estimation.\ \ Contract.fallback.transact(_transaction_)[](#web3.contract.Contract.fallback.transact "Link to this definition")\ \ Execute fallback function by sending a new public transaction.\ \ Contract.fallback.build\_transaction(_transaction_)[](#web3.contract.Contract.fallback.build_transaction "Link to this definition")\ \ Builds a transaction dictionary based on the contract fallback function call.\ \ Contract Events[](#contract-events "Link to this heading")\ \ ------------------------------------------------------------\ \ The named events exposed through the [`Contract.events`](#web3.contract.Contract.events "web3.contract.Contract.events")\ property are of the ContractEvent type. This class is not to be used directly, but instead through [`Contract.events`](#web3.contract.Contract.events "web3.contract.Contract.events")\ .\ \ For example:\ \ > myContract \= web3.eth.contract(address\=contract\_address, abi\=contract\_abi)\ > tx\_hash \= myContract.functions.myFunction().transact()\ > receipt \= web3.eth.get\_transaction\_receipt(tx\_hash)\ > myContract.events.myEvent().process\_receipt(receipt)\ \ _class_ web3.contract.ContractEvent[](#web3.contract.ContractEvent "Link to this definition")\ \ ### Attributes[](#id5 "Link to this heading")\ \ The [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ class provides attributes for each event. Access the event attributes through Contract.events.myEvent.\ \ ContractEvent.myEvent(\*args, \*\*kwargs).abi\_element\_identifier\ \ The signature of the event assigned to the class `__name__` during initialization.\ \ ContractEvent.myEvent(\*args, \*\*kwargs).name\ \ A string representing the event, receive or fallback name.\ \ Use `ContractEvent.myEvent(*args, **kwargs).signature` when the event arguments are needed.\ \ This is an alias of `ContractEvent.myEvent(*args, **kwargs).event_name`.\ \ ContractEvent.myEvent(\*args, \*\*kwargs).signature\ \ A string representing the event signature.\ \ ContractEvent.myEvent(\*args, \*\*kwargs).abi\ \ The event ABI with the type, name, inputs.\ \ ContractEvent.myEvent(\*args, \*\*kwargs).argument\_names\ \ The event input names.\ \ ContractEvent.myEvent(\*args, \*\*kwargs).argument\_types\ \ The event input types.\ \ ### Methods[](#id6 "Link to this heading")\ \ [`ContractEvent`](#web3.contract.ContractEvent "web3.contract.ContractEvent")\ provides methods to interact with contract events. Positional and keyword arguments supplied to the contract event subclass will be used to find the contract event by signature.\ \ ContractEvent.get\_logs(_from\_block\=None_, _to\_block\='latest'_, _block\_hash\=None_, _argument\_filters\={}_)\ \ Fetches all logs for a given event within the specified block range or block hash.\ \ Returns a list of decoded event logs sorted by `logIndex`.\ \ > `argument_filters` is an optional dictionary argument that can be used to filter for logs where the event’s argument values match the values provided in the dictionary. The keys must match the event argument names as they exist in the ABI. The values can either be a single value or a list of values to match against. If a list is provided, the logs will be filtered for any logs that match any of the values in the list. Indexed arguments are filtered pre-call by building specific `topics` to filter for. Non-indexed arguments are filtered by the library after the logs are fetched from the node.\ > \ > my\_contract \= web3.eth.contract(address\=contract\_address, abi\=contract\_abi)\ > \ > \# get \`\`myEvent\`\` logs from block 1337 to block 2337 where the value for the\ > \# event argument "eventArg1" is either 1, 2, or 3\ > my\_contract.events.myEvent().get\_logs(\ > argument\_filters\={"eventArg1": \[1, 2, 3\]},\ > from\_block\=1337,\ > to\_block\=2337,\ > )\ \ ContractEvent.process\_receipt(_transaction\_receipt_, _errors\=WARN_)\ \ Extracts the pertinent logs from a transaction receipt.\ \ If there are no errors, `process_receipt` returns a tuple of [Event Log Objects](#event-log-object)\ , emitted from the event (e.g. `myEvent`), with decoded output.\ \ \>>> tx\_hash \= contract.functions.myFunction(12345).transact({'to':contract\_address})\ \>>> tx\_receipt \= w3.eth.get\_transaction\_receipt(tx\_hash)\ \>>> rich\_logs \= contract.events.myEvent().process\_receipt(tx\_receipt)\ \>>> rich\_logs\[0\]\['args'\]\ {'myArg': 12345}\ \ If there are errors, the logs will be handled differently depending on the flag that is passed in:\ \ > * `WARN` (default) - logs a warning to the console for the log that has an error, and discards the log. Returns any logs that are able to be processed.\ > \ > * `STRICT` - stops all processing and raises the error encountered.\ > \ > * `IGNORE` - returns any raw logs that raised an error with an added “errors” field, along with any other logs were able to be processed.\ > \ > * `DISCARD` - silently discards any logs that have errors, and returns processed logs that don’t have errors.\ > \ \ An event log error flag needs to be imported from `web3/logs.py`.\ \ \>>> tx\_hash \= contract.functions.myFunction(12345).transact({'to':contract\_address})\ \>>> tx\_receipt \= w3.eth.get\_transaction\_receipt(tx\_hash)\ \>>> processed\_logs \= contract.events.myEvent().process\_receipt(tx\_receipt)\ \>>> processed\_logs\ (\ AttributeDict({\ 'args': AttributeDict({}),\ 'event': 'myEvent',\ 'logIndex': 0,\ 'transactionIndex': 0,\ 'transactionHash': HexBytes('0xfb95ccb6ab39e19821fb339dee33e7afe2545527725b61c64490a5613f8d11fa'),\ 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\ 'blockHash': HexBytes('0xd74c3e8bdb19337987b987aee0fa48ed43f8f2318edfc84e3a8643e009592a68'),\ 'blockNumber': 3\ })\ )\ \ \# Or, if there were errors encountered during processing:\ \>>> from web3.logs import STRICT, IGNORE, DISCARD, WARN\ \>>> processed\_logs \= contract.events.myEvent().process\_receipt(tx\_receipt, errors\=IGNORE)\ \>>> processed\_logs\ (\ AttributeDict({\ 'type': 'mined',\ 'logIndex': 0,\ 'transactionIndex': 0,\ 'transactionHash': HexBytes('0x01682095d5abb0270d11a31139b9a1f410b363c84add467004e728ec831bd529'),\ 'blockHash': HexBytes('0x92abf9325a3959a911a2581e9ea36cba3060d8b293b50e5738ff959feb95258a'),\ 'blockNumber': 5,\ 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\ 'data': '0x0000000000000000000000000000000000000000000000000000000000003039',\ 'topics': \[\ HexBytes('0xf70fe689e290d8ce2b2a388ac28db36fbb0e16a6d89c6804c461f65a1b40bb15')\ \],\ 'errors': LogTopicError('Expected 1 log topics. Got 0')})\ })\ )\ \>>> processed\_logs \= contract.events.myEvent().process\_receipt(tx\_receipt, errors\=DISCARD)\ \>>> assert processed\_logs \== ()\ True\ \ ContractEvent.process\_log(_log_)[](#web3.contract.ContractEvent.process_log "Link to this definition")\ \ Similar to [process\_receipt](#process-receipt)\ , but only processes one log at a time, instead of a whole transaction receipt. Will return a single [Event Log Object](#event-log-object)\ if there are no errors encountered during processing. If an error is encountered during processing, it will be raised.\ \ \>>> tx\_hash \= contract.functions.myFunction(12345).transact({'to':contract\_address})\ \>>> tx\_receipt \= w3.eth.get\_transaction\_receipt(tx\_hash)\ \>>> log\_to\_process \= tx\_receipt\['logs'\]\[0\]\ \>>> processed\_log \= contract.events.myEvent().process\_log(log\_to\_process)\ \>>> processed\_log\ AttributeDict({\ 'args': AttributeDict({}),\ 'event': 'myEvent',\ 'logIndex': 0,\ 'transactionIndex': 0,\ 'transactionHash': HexBytes('0xfb95ccb6ab39e19821fb339dee33e7afe2545527725b61c64490a5613f8d11fa'),\ 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\ 'blockHash': HexBytes('0xd74c3e8bdb19337987b987aee0fa48ed43f8f2318edfc84e3a8643e009592a68'),\ 'blockNumber': 3\ })\ \ ### Event Log Object[](#event-log-object "Link to this heading")\ \ > The Event Log Object is a python dictionary with the following keys:\ > \ > * `args`: Dictionary - The arguments coming from the event.\ > \ > * `event`: String - The event name.\ > \ > * `logIndex`: Number - integer of the log index position in the block.\ > \ > * `transactionIndex`: Number - integer of the transactions index position log was created from.\ > \ > * `transactionHash`: String, 32 Bytes - hash of the transactions this log was created from.\ > \ > * `address`: String, 32 Bytes - address from which this log originated.\ > \ > * `blockHash`: String, 32 Bytes - hash of the block where this log was in. null when it’s pending.\ > \ > * `blockNumber`: Number - the block number where this log was in. null when it’s pending.\ > \ \ \>>> transfer\_filter \= my\_token\_contract.events.Transfer.create\_filter(from\_block\="0x0", argument\_filters\={'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf'})\ \>>> transfer\_filter.get\_new\_entries()\ \[AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'value': 10}),\ 'event': 'Transfer',\ 'logIndex': 0,\ 'transactionIndex': 0,\ 'transactionHash': HexBytes('0x9da859237e7259832b913d51cb128c8d73d1866056f7a41b52003c953e749678'),\ 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\ 'blockHash': HexBytes('...'),\ 'blockNumber': 2})\]\ \>>> transfer\_filter.get\_new\_entries()\ \[\]\ \>>> tx\_hash \= contract.functions.transfer(alice, 10).transact({'gas': 899000, 'gasPrice': 1000000000})\ \>>> tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash)\ \>>> transfer\_filter.get\_new\_entries()\ \[AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'value': 10}),\ 'event': 'Transfer',\ 'logIndex': 0,\ 'transactionIndex': 0,\ 'transactionHash': HexBytes('...'),\ 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\ 'blockHash': HexBytes('...'),\ 'blockNumber': 3})\]\ \>>> transfer\_filter.get\_all\_entries()\ \[AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'value': 10}),\ 'event': 'Transfer',\ 'logIndex': 0,\ 'transactionIndex': 0,\ 'transactionHash': HexBytes('...'),\ 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\ 'blockHash': HexBytes('...'),\ 'blockNumber': 2}),\ AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf',\ 'value': 10}),\ 'event': 'Transfer',\ 'logIndex': 0,\ 'transactionIndex': 0,\ 'transactionHash': HexBytes('...'),\ 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',\ 'blockHash': HexBytes('...'),\ 'blockNumber': 3})\]\ \ Utils[](#utils "Link to this heading")\ \ ----------------------------------------\ \ _classmethod_ Contract.decode\_function\_input(_data_)[](#web3.contract.Contract.decode_function_input "Link to this definition")\ \ Decodes the transaction data used to invoke a smart contract function, and returns [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ and decoded parameters as [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)")\ .\ \ \>>> transaction \= w3.eth.get\_transaction('0x5798fbc45e3b63832abc4984b0f3574a13545f415dd672cd8540cd71f735db56')\ \>>> transaction.input\ '0x612e45a3000000000000000000000000b656b2a9c3b2416437a811e07466ca712f5a5b5a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000093a80000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000116c6f6e656c792c20736f206c6f6e656c7900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'\ \>>> contract.decode\_function\_input(transaction.input)\ (,\ {'\_recipient': '0xB656b2a9c3b2416437A811e07466cA712F5a5b5a',\ '\_amount': 0,\ '\_description': b'lonely, so lonely',\ '\_transactionData': b'',\ '\_debatingPeriod': 604800,\ '\_newCurator': True})\ \ ContractCaller[](#contractcaller "Link to this heading")\ \ ----------------------------------------------------------\ \ _class_ web3.contract.ContractCaller[](#web3.contract.ContractCaller "Link to this definition")\ \ The `ContractCaller` class provides an API to call functions in a contract. This class is not to be used directly, but instead through `Contract.caller`.\ \ There are a number of different ways to invoke the `ContractCaller`.\ \ For example:\ \ \>>> myContract \= w3.eth.contract(address\=address, abi\=ABI)\ \>>> twentyone \= myContract.caller.multiply7(3)\ \>>> twentyone\ 21\ \ It can also be invoked using parentheses:\ \ \>>> twentyone \= myContract.caller().multiply7(3)\ \>>> twentyone\ 21\ \ And a transaction dictionary, with or without the `transaction` keyword. You can also optionally include a block identifier. For example:\ \ \>>> from\_address \= w3.eth.accounts\[1\]\ \>>> twentyone \= myContract.caller({'from': from\_address}).multiply7(3)\ \>>> twentyone\ 21\ \>>> twentyone \= myContract.caller(transaction\={'from': from\_address}).multiply7(3)\ \>>> twentyone\ 21\ \>>> twentyone \= myContract.caller(block\_identifier\='latest').multiply7(3)\ \>>> twentyone\ 21\ \ Like [`ContractFunction`](#web3.contract.ContractFunction "web3.contract.ContractFunction")\ , [`ContractCaller`](#web3.contract.ContractCaller "web3.contract.ContractCaller")\ provides methods to interact with contract functions. Positional and keyword arguments supplied to the contract caller subclass will be used to find the contract function by signature, and forwarded to the contract function when applicable.\ \ Examples[](#examples "Link to this heading")\ \ ----------------------------------------------\ \ ### Working with an ERC-20 Token Contract[](#working-with-an-erc-20-token-contract "Link to this heading")\ \ Most fungible tokens on the Ethereum blockchain conform to the [ERC-20](https://github.com/ethereum/ERCs/blob/master/ERCS/erc-20.md)\ standard. This section of the guide covers interacting with an existing token contract which conforms to this standard.\ \ In this guide we will interact with an existing token contract that we have already deployed to a local testing chain. This guide assumes:\ \ 1. An existing token contract at a known address.\ \ 2. Access to the proper `ABI` for the given contract.\ \ 3. A `web3.main.Web3` instance connected to a provider with an unlocked account which can send transactions.\ \ \ #### Creating the contract factory[](#creating-the-contract-factory "Link to this heading")\ \ First we need to create a contract instance with the address of our token contract and the `ERC-20` ABI.\ \ \>>> contract \= w3.eth.contract(contract\_address, abi\=ABI)\ \>>> contract.address\ '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b'\ \ #### Querying token metadata[](#querying-token-metadata "Link to this heading")\ \ Each token will have a total supply which represents the total number of tokens in circulation. In this example we’ve initialized the token contract to have 1 million tokens. Since this token contract is setup to have 18 decimal places, the raw total supply returned by the contract is going to have 18 additional decimal places.\ \ \>>> contract.functions.name().call()\ 'TestToken'\ \>>> contract.functions.symbol().call()\ 'TEST'\ \>>> decimals \= contract.functions.decimals().call()\ \>>> decimals\ 18\ \>>> DECIMALS \= 10 \*\* decimals\ \>>> contract.functions.totalSupply().call() // DECIMALS\ 1000000\ \ #### Query account balances[](#query-account-balances "Link to this heading")\ \ Next we can query some account balances using the contract’s `balanceOf` function. The token contract we are using starts with a single account which we’ll refer to as `alice` holding all of the tokens.\ \ \>>> alice \= '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf'\ \>>> bob \= '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF'\ \>>> raw\_balance \= contract.functions.balanceOf(alice).call()\ \>>> raw\_balance\ 1000000000000000000000000\ \>>> raw\_balance // DECIMALS\ 1000000\ \>>> contract.functions.balanceOf(bob).call()\ 0\ \ #### Sending tokens[](#sending-tokens "Link to this heading")\ \ Next we can transfer some tokens from `alice` to `bob` using the contract’s `transfer` function.\ \ \>>> tx\_hash \= contract.functions.transfer(bob, 100).transact({'from': alice})\ \>>> tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash)\ \>>> contract.functions.balanceOf(alice).call()\ 999999999999999999999900\ \>>> contract.functions.balanceOf(bob).call()\ 100\ \ #### Creating an approval for external transfers[](#creating-an-approval-for-external-transfers "Link to this heading")\ \ Alice could also _approve_ someone else to spend tokens from her account using the `approve` function. We can also query how many tokens we’re approved to spend using the `allowance` function.\ \ \>>> contract.functions.allowance(alice, bob).call()\ 0\ \>>> tx\_hash \= contract.functions.approve(bob, 200).transact({'from': alice})\ \>>> tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash)\ \>>> contract.functions.allowance(alice, bob).call()\ 200\ \ #### Performing an external transfer[](#performing-an-external-transfer "Link to this heading")\ \ When someone has an allowance they can transfer those tokens using the `transferFrom` function.\ \ \>>> contract.functions.allowance(alice, bob).call()\ 200\ \>>> contract.functions.balanceOf(bob).call()\ 100\ \>>> tx\_hash \= contract.functions.transferFrom(alice, bob, 75).transact({'from': bob})\ \>>> tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash)\ \>>> contract.functions.allowance(alice, bob).call()\ 125\ \>>> contract.functions.balanceOf(bob).call()\ 175\ \ ### Using a struct as a function argument[](#using-a-struct-as-a-function-argument "Link to this heading")\ \ web3.py accepts struct arguments as dictionaries. This format also supports nested structs. Let’s take a look at a quick example. Given the following Solidity contract:\ \ contract Example {\ address addr;\ \ struct S1 {\ address a1;\ address a2;\ }\ \ struct S2 {\ bytes32 b1;\ bytes32 b2;\ }\ \ struct X {\ S1 s1;\ S2 s2;\ address\[\] users;\ }\ \ function update(X memory x) public {\ addr = x.s1.a2;\ }\ \ function retrieve() public view returns (address) {\ return addr;\ }\ }\ \ You can interact with the web3.py contract API as follows:\ \ \# deploy or lookup the deployed contract, then:\ \ \>>> deployed\_contract.functions.retrieve().call()\ '0x0000000000000000000000000000000000000000'\ \ \>>> deployed\_contract.functions.update({'s1': \['0x0000000000000000000000000000000000000001', '0x0000000000000000000000000000000000000002'\], 's2': \[b'0'\*32, b'1'\*32\], 'users': \[\]}).transact()\ \ \>>> deployed\_contract.functions.retrieve().call()\ '0x0000000000000000000000000000000000000002'\ \ ### Invoke Ambiguous Contract Functions[](#invoke-ambiguous-contract-functions "Link to this heading")\ \ Calling overloaded functions can be done as you would expect. Passing arguments will disambiguate which function you want to call.\ \ For example, if you have a contract with two functions with the name `identity` that accept different types of arguments, you can call them like this:\ \ \>>> ambiguous\_contract \= w3.eth.contract(address\=..., abi\=...)\ \>>> ambiguous\_contract.functions.identity(1, True).call()\ 1\ \>>> ambiguous\_contract.functions.identity("one", 1, True).call()\ 1\ \ If there is a need to first retrieve the function, you can use the contract instance’s `get_function_by_signature` method to get the function you want to call.\ \ Below is an example of a contract that has multiple functions of the same name, and the arguments are ambiguous. You can use the [`Contract.get_function_by_signature()`](#web3.contract.Contract.get_function_by_signature "web3.contract.Contract.get_function_by_signature")\ method to reference the intended function and call it with the correct arguments.\ \ \>>> contract\_source\_code \= """\ pragma solidity ^0.8.24;\ contract AmbiguousDuo {\ function identity(uint256 input, bool uselessFlag) public pure returns (uint256) {\ return input;\ }\ function identity(int256 input, bool uselessFlag) public pure returns (int256) {\ return input;\ }\ }\ """\ \# fast forward all the steps of compiling and deploying the contract.\ \ \>>> identity\_func = ambiguous\_contract.get\_function\_by\_signature('identity(uint256,bool)')\ \>>> identity\_func(1, True)\ \ \>>> identity\_func(1, True).call()\ 1\ \ ### CCIP Read support for offchain lookup[](#ccip-read-support-for-offchain-lookup "Link to this heading")\ \ Contract calls support CCIP Read by default, via a `ccip_read_enabled` flag on the call and, more globally, a `global_ccip_read_enabled` flag on the provider. The following should work by default without raising an `OffchainLookup` and instead handling it appropriately as per the specification outlined in [EIP-3668](https://eips.ethereum.org/EIPS/eip-3668)\ .\ \ myContract.functions.revertsWithOffchainLookup(myData).call()\ \ If the offchain lookup requires the user to send a transaction rather than make a call, this may be handled appropriately in the following way:\ \ from web3 import Web3, WebSocketProvider\ from web3.utils import handle\_offchain\_lookup\ \ w3 \= Web3(WebSocketProvider(...))\ \ myContract \= w3.eth.contract(address\=...)\ myData \= b'data for offchain lookup function call'\ \ \# preflight with an \`eth\_call\` and handle the exception\ try:\ myContract.functions.revertsWithOffchainLookup(myData).call(ccip\_read\_enabled\=False)\ except OffchainLookup as ocl:\ tx \= {'to': myContract.address, 'from': my\_account}\ data\_for\_callback\_function \= handle\_offchain\_lookup(ocl.payload)\ tx\['data'\] \= data\_for\_callback\_function\ \ \# send the built transaction with \`eth\_sendTransaction\` or sign and send with \`eth\_sendRawTransaction\`\ tx\_hash \= w3.eth.send\_transaction(tx)\ \ ### Contract Unit Tests in Python[](#contract-unit-tests-in-python "Link to this heading")\ \ Here is an example of how one can use the [pytest](https://docs.pytest.org/en/latest/)\ framework in python, web3.py, eth-tester, and PyEVM to perform unit tests entirely in python without any additional need for a full featured ethereum node/client. To install needed dependencies you can use the pinned extra for testing:\ \ $ pip install web3\[test\] pytest\ \ Once you have an environment set up for testing, you can then write your tests like so:\ \ \# of how to write unit tests with web3.py\ import pytest\ \ import pytest\_asyncio\ \ from web3 import (\ AsyncWeb3,\ EthereumTesterProvider,\ Web3,\ )\ from web3.providers.eth\_tester.main import (\ AsyncEthereumTesterProvider,\ )\ \ @pytest.fixture\ def tester\_provider():\ return EthereumTesterProvider()\ \ @pytest.fixture\ def eth\_tester(tester\_provider):\ return tester\_provider.ethereum\_tester\ \ @pytest.fixture\ def w3(tester\_provider):\ return Web3(tester\_provider)\ \ @pytest.fixture\ def foo\_contract(eth\_tester, w3):\ \# For simplicity of this example we statically define the\ \# contract code here. You might read your contracts from a\ \# file, or something else to test with in your own code\ #\ \# pragma solidity^0.5.3;\ #\ \# contract Foo {\ #\ \# string public bar;\ \# event barred(string \_bar);\ #\ \# constructor() public {\ \# bar = "hello world";\ \# }\ #\ \# function setBar(string memory \_bar) public {\ \# bar = \_bar;\ \# emit barred(\_bar);\ \# }\ #\ \# }\ \ deploy\_address \= eth\_tester.get\_accounts()\[0\]\ \ abi \= """\[{"anonymous":false,"inputs":\[{"indexed":false,"name":"\_bar","type":"string"}\],"name":"barred","type":"event"},{"constant":false,"inputs":\[{"name":"\_bar","type":"string"}\],"name":"setBar","outputs":\[\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":\[\],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"constant":true,"inputs":\[\],"name":"bar","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"}\]""" \# noqa: E501\ \# This bytecode is the output of compiling with\ \# solc version:0.5.3+commit.10d17f24.Emscripten.clang\ bytecode \= """608060405234801561001057600080fd5b506040805190810160405280600b81526020017f68656c6c6f20776f726c640000000000000000000000000000000000000000008152506000908051906020019061005c929190610062565b50610107565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a357805160ff19168380011785556100d1565b828001600101855582156100d1579182015b828111156100d05782518255916020019190600101906100b5565b5b5090506100de91906100e2565b5090565b61010491905b808211156101005760008160009055506001016100e8565b5090565b90565b6103bb806101166000396000f3fe608060405234801561001057600080fd5b5060043610610053576000357c01000000000000000000000000000000000000000000000000000000009004806397bc14aa14610058578063febb0f7e14610113575b600080fd5b6101116004803603602081101561006e57600080fd5b810190808035906020019064010000000081111561008b57600080fd5b82018360208201111561009d57600080fd5b803590602001918460018302840111640100000000831117156100bf57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050610196565b005b61011b61024c565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561015b578082015181840152602081019050610140565b50505050905090810190601f1680156101885780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b80600090805190602001906101ac9291906102ea565b507f5f71ad82e16f082de5ff496b140e2fbc8621eeb37b36d59b185c3f1364bbd529816040518080602001828103825283818151815260200191508051906020019080838360005b8381101561020f5780820151818401526020810190506101f4565b50505050905090810190601f16801561023c5780820380516001836020036101000a031916815260200191505b509250505060405180910390a150565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102e25780601f106102b7576101008083540402835291602001916102e2565b820191906000526020600020905b8154815290600101906020018083116102c557829003601f168201915b505050505081565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061032b57805160ff1916838001178555610359565b82800160010185558215610359579182015b8281111561035857825182559160200191906001019061033d565b5b509050610366919061036a565b5090565b61038c91905b80821115610388576000816000905550600101610370565b5090565b9056fea165627a7a72305820ae6ca683d45ee8a71bba45caee29e4815147cd308f772c853a20dfe08214dbb50029""" \# noqa: E501\ \ \# Create our contract class.\ FooContract \= w3.eth.contract(abi\=abi, bytecode\=bytecode)\ \# issue a transaction to deploy the contract.\ tx\_hash \= FooContract.constructor().transact(\ {\ "from": deploy\_address,\ }\ )\ \# wait for the transaction to be mined\ tx\_receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash, 180)\ \# instantiate and return an instance of our contract.\ return FooContract(tx\_receipt.contractAddress)\ \ def test\_initial\_greeting(foo\_contract):\ hw \= foo\_contract.caller.bar()\ assert hw \== "hello world"\ \ def test\_can\_update\_greeting(w3, foo\_contract):\ \# send transaction that updates the greeting\ tx\_hash \= foo\_contract.functions.setBar("testing contracts is easy").transact(\ {\ "from": w3.eth.accounts\[1\],\ }\ )\ w3.eth.wait\_for\_transaction\_receipt(tx\_hash, 180)\ \ \# verify that the contract is now using the updated greeting\ hw \= foo\_contract.caller.bar()\ assert hw \== "testing contracts is easy"\ \ def test\_updating\_greeting\_emits\_event(w3, foo\_contract):\ \# send transaction that updates the greeting\ tx\_hash \= foo\_contract.functions.setBar("testing contracts is easy").transact(\ {\ "from": w3.eth.accounts\[1\],\ }\ )\ receipt \= w3.eth.wait\_for\_transaction\_receipt(tx\_hash, 180)\ \ \# get all of the \`barred\` logs for the contract\ logs \= foo\_contract.events.barred.get\_logs()\ assert len(logs) \== 1\ \ \# verify that the log's data matches the expected value\ event \= logs\[0\]\ assert event.blockHash \== receipt.blockHash\ assert event.args.\_bar \== "testing contracts is easy"\ \ @pytest.fixture\ def async\_eth\_tester():\ return AsyncEthereumTesterProvider().ethereum\_tester\ \ @pytest\_asyncio.fixture()\ async def async\_w3():\ async\_w3 \= AsyncWeb3(AsyncEthereumTesterProvider())\ accounts \= await async\_w3.eth.accounts\ async\_w3.eth.default\_account \= accounts\[0\]\ return async\_w3\ \ @pytest\_asyncio.fixture()\ async def async\_foo\_contract(async\_w3):\ \# For simplicity of this example we statically define the\ \# contract code here. You might read your contracts from a\ \# file, or something else to test with in your own code\ #\ \# pragma solidity^0.5.3;\ #\ \# contract Foo {\ #\ \# string public bar;\ \# event barred(string \_bar);\ #\ \# constructor() public {\ \# bar = "hello world";\ \# }\ #\ \# function setBar(string memory \_bar) public {\ \# bar = \_bar;\ \# emit barred(\_bar);\ \# }\ #\ \# }\ \ abi \= """\[{"anonymous":false,"inputs":\[{"indexed":false,"name":"\_bar","type":"string"}\],"name":"barred","type":"event"},{"constant":false,"inputs":\[{"name":"\_bar","type":"string"}\],"name":"setBar","outputs":\[\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":\[\],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"constant":true,"inputs":\[\],"name":"bar","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"}\]""" \# noqa: E501\ \# This bytecode is the output of compiling with\ \# solc version:0.5.3+commit.10d17f24.Emscripten.clang\ bytecode \= """608060405234801561001057600080fd5b506040805190810160405280600b81526020017f68656c6c6f20776f726c640000000000000000000000000000000000000000008152506000908051906020019061005c929190610062565b50610107565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a357805160ff19168380011785556100d1565b828001600101855582156100d1579182015b828111156100d05782518255916020019190600101906100b5565b5b5090506100de91906100e2565b5090565b61010491905b808211156101005760008160009055506001016100e8565b5090565b90565b6103bb806101166000396000f3fe608060405234801561001057600080fd5b5060043610610053576000357c01000000000000000000000000000000000000000000000000000000009004806397bc14aa14610058578063febb0f7e14610113575b600080fd5b6101116004803603602081101561006e57600080fd5b810190808035906020019064010000000081111561008b57600080fd5b82018360208201111561009d57600080fd5b803590602001918460018302840111640100000000831117156100bf57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050610196565b005b61011b61024c565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561015b578082015181840152602081019050610140565b50505050905090810190601f1680156101885780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b80600090805190602001906101ac9291906102ea565b507f5f71ad82e16f082de5ff496b140e2fbc8621eeb37b36d59b185c3f1364bbd529816040518080602001828103825283818151815260200191508051906020019080838360005b8381101561020f5780820151818401526020810190506101f4565b50505050905090810190601f16801561023c5780820380516001836020036101000a031916815260200191505b509250505060405180910390a150565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102e25780601f106102b7576101008083540402835291602001916102e2565b820191906000526020600020905b8154815290600101906020018083116102c557829003601f168201915b505050505081565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061032b57805160ff1916838001178555610359565b82800160010185558215610359579182015b8281111561035857825182559160200191906001019061033d565b5b509050610366919061036a565b5090565b61038c91905b80821115610388576000816000905550600101610370565b5090565b9056fea165627a7a72305820ae6ca683d45ee8a71bba45caee29e4815147cd308f772c853a20dfe08214dbb50029""" \# noqa: E501\ \ \# Create our contract class.\ FooContract \= async\_w3.eth.contract(abi\=abi, bytecode\=bytecode)\ \# issue a transaction to deploy the contract.\ tx\_hash \= await FooContract.constructor().transact(\ {\ "from": async\_w3.eth.default\_account,\ }\ )\ \# wait for the transaction to be mined\ tx\_receipt \= await async\_w3.eth.wait\_for\_transaction\_receipt(tx\_hash, 180)\ \# instantiate and return an instance of our contract.\ return FooContract(tx\_receipt\["contractAddress"\])\ \ @pytest.mark.asyncio\ async def test\_async\_initial\_greeting(async\_foo\_contract):\ hw \= await async\_foo\_contract.caller.bar()\ assert hw \== "hello world"\ \ @pytest.mark.asyncio\ async def test\_async\_can\_update\_greeting(async\_w3, async\_foo\_contract):\ tx\_hash \= await async\_foo\_contract.functions.setBar(\ "testing contracts is easy",\ ).transact(\ {\ "from": async\_w3.eth.default\_account,\ }\ )\ await async\_w3.eth.wait\_for\_transaction\_receipt(tx\_hash, 180)\ \ \# verify that the contract is now using the updated greeting\ hw \= await async\_foo\_contract.caller.bar()\ assert hw \== "testing contracts is easy"\ \ @pytest.mark.asyncio\ async def test\_async\_updating\_greeting\_emits\_event(async\_w3, async\_foo\_contract):\ \# send transaction that updates the greeting\ tx\_hash \= await async\_foo\_contract.functions.setBar(\ "testing contracts is easy",\ ).transact(\ {\ "from": async\_w3.eth.default\_account,\ }\ )\ receipt \= await async\_w3.eth.wait\_for\_transaction\_receipt(tx\_hash, 180)\ \ \# get all of the \`barred\` logs for the contract\ logs \= await async\_foo\_contract.events.barred.get\_logs()\ assert len(logs) \== 1\ \ \# verify that the log's data matches the expected value\ event \= logs\[0\]\ assert event.blockHash \== receipt.blockHash\ assert event.args.\_bar \== "testing contracts is easy" --- # Ethereum Name Service (ENS) — web3.py 7.6.1 documentation * [](index.html) * Ethereum Name Service (ENS) * [View page source](_sources/ens_overview.rst.txt) * * * Ethereum Name Service (ENS)[](#ethereum-name-service-ens "Link to this heading") ================================================================================== The Ethereum Name Service (ENS) is analogous to the Domain Name Service. It enables users and developers to use human-friendly names in place of error-prone hexadecimal addresses, content hashes, and more. The [`ens`](ens.html#module-ens "ens") module is included with web3.py. It provides an interface to look up domains and addresses, add resolver records, or get and set metadata. Note web3.py `v6.6.0` introduced ENS name normalization standard [ENSIP-15](https://docs.ens.domains/ensip/15) . This update to ENS name validation and normalization won’t affect ~99% of names but may prevent invalid names from being created and from interacting with the ENS contracts via web3.py. We feel strongly that this change, though breaking, is in the best interest of our users as it ensures compatibility with the latest ENS standards. Setup[](#setup "Link to this heading") ---------------------------------------- Create an `ENS` object (named `ns` below) in one of three ways: 1. Automatic detection 2. Specify an instance of a [provider](providers.html#providers) 3. From an existing [`web3.Web3`](web3.main.html#web3.Web3 "web3.Web3") object \# 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: 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. \# instantiate w3 instance from web3 import Web3, IPCProvider w3 \= Web3(IPCProvider(...)) \# use the module w3.ens.address('ethereum.eth') ens.strict\_bytes\_type\_checking[](#ens.strict_bytes_type_checking "Link to this definition") 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.html#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. \>>> from web3 import Web3, EthereumTesterProvider \>>> from ens import ENS \>>> w3 \= Web3(EthereumTesterProvider()) \>>> assert w3.strict\_bytes\_type\_checking \# assert strict by default \>>> w3.is\_encodable('bytes2', b'1') False \>>> w3.strict\_bytes\_type\_checking \= False \>>> w3.is\_encodable('bytes2', b'1') \# zero-padded, so encoded to: b'1\\x00' True \>>> ns \= ENS.from\_web3(w3) \>>> \# assert inherited from w3 at time of instantiation via ENS.from\_web3() \>>> assert ns.strict\_bytes\_type\_checking is False \>>> ns.w3.is\_encodable('bytes2', b'1') True \>>> \# assert these are now separate instances \>>> ns.strict\_bytes\_type\_checking \= True \>>> ns.w3.is\_encodable('bytes2', b'1') False \>>> \# assert w3 flag value remains \>>> assert w3.strict\_bytes\_type\_checking is False \>>> w3.is\_encodable('bytes2', b'1') True 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. \>>> from web3 import Web3, EthereumTesterProvider \>>> w3 \= Web3(EthereumTesterProvider()) \>>> assert w3.strict\_bytes\_type\_checking \# assert strict by default \>>> w3.is\_encodable('bytes2', b'1') False \>>> w3.strict\_bytes\_type\_checking \= False \>>> w3.is\_encodable('bytes2', b'1') \# zero-padded, so encoded to: b'1\\x00' True \>>> assert w3 \== w3.ens.w3 \# assert same object \>>> assert not w3.ens.w3.strict\_bytes\_type\_checking \>>> w3.ens.w3.is\_encodable('bytes2', b'1') True \>>> \# sanity check on eth module as well \>>> assert not w3.eth.w3.strict\_bytes\_type\_checking \>>> w3.eth.w3.is\_encodable('bytes2', b'1') True Usage[](#usage "Link to this heading") ---------------------------------------- ### Name Info[](#name-info "Link to this heading") #### Get the Address for an ENS Name[](#get-the-address-for-an-ens-name "Link to this heading") from ens.auto import ns eth\_address \= ns.address('ens.eth') assert eth\_address \== '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' The `ENS` module has no opinion as to which **TLD (Top Level Domain)** you can use, but will not infer a TLD if it is not provided with the name. ##### Multichain Address Resolution[](#multichain-address-resolution "Link to this heading") [ENSIP-9](https://docs.ens.domains/ensip/9) introduced multichain address resolution, allowing users to resolve addresses from different chains, specified by the coin type index from [SLIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) . The `address()` method on the `ENS` class supports multichain address resolution via the `coin_type` keyword argument. from ens.auto import ns eth\_address \= ns.address('ens.eth', coin\_type\=60) \# ETH is coin\_type 60 assert eth\_address \== '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' #### Get the ENS Name for an Address[](#get-the-ens-name-for-an-address "Link to this heading") domain \= ns.name('0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') \# name() also accepts the bytes version of the address assert ns.name(b'\\xfe\\x89\\xccz\\xbb,A\\x83h:\\xb7\\x16S\\xc4\\xcd\\xc9\\xb0\-D\\xb7') \== domain \# confirm that the name resolves back to the address that you looked up: assert ns.address(domain) \== '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' Note For accuracy, and as a recommendation from the ENS documentation on [reverse resolution](https://docs.ens.domains/web/resolution#reverse-resolution) , the `ENS` module now verifies that the forward resolution matches the address with every call to get the `name()` for an address. This is the only sure way to know whether the reverse resolution is correct. Anyone can claim any name, only forward resolution implies that the owner of the name gave their stamp of approval. #### Get the Owner of a Name[](#get-the-owner-of-a-name "Link to this heading") eth\_address \= ns.owner('exchange.eth') * * * ### Set Up Your Name and Address[](#set-up-your-name-and-address "Link to this heading") #### Link a Name to an Address[](#link-a-name-to-an-address "Link to this heading") You can set up your name so that `address()` will show the address it points to. In order to do so, you must already be the owner of the domain (or its parent). ns.setup\_address('ens.eth', '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') In the common case where you want to point the name to the owning address, you can skip the address. ns.setup\_address('ens.eth') You can claim arbitrarily deep subdomains. ns.setup\_address('supreme.executive.power.derives.from.a.mandate.from.the.masses.ens.eth') \# wait for the transaction to be mined, then: assert ( ns.address('supreme.executive.power.derives.from.a.mandate.from.the.masses.ens.eth') \== '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' ) Warning Gas costs scale up with the number of subdomains! ##### Multichain Address Support[](#multichain-address-support "Link to this heading") [ENSIP-9](https://docs.ens.domains/ensip/9) introduced multichain address resolution, allowing users to resolve addresses from different chains, specified by the coin type index from [SLIP44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md) . The `setup_address()` method on the `ENS` class supports multichain address setup via the `coin_type` keyword argument. from ens.auto import ns ns.setup\_address('ens.eth', coin\_type\=60) \# ETH is coin\_type 60 assert ns.address('ens.eth', coin\_type\=60) \== '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' #### Link an Address to a Name[](#link-an-address-to-a-name "Link to this heading") You can set up your address so that `name()` will show the name that points to it. This is like Caller ID. It enables you and others to take an account and determine what name points to it. Sometimes this is referred to as “reverse” resolution. The ENS Reverse Resolver is used for this functionality. ns.setup\_name('ens.eth', '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') If you don’t supply the address, `setup_name()` will assume you want the address returned by `address()`. ns.setup\_name('ens.eth') If the name doesn’t already point to an address, `setup_name()` will call `setup_address()` for you. Wait for the transaction to be mined, then: assert ns.name('0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') \== 'ens.eth' * * * ### Text Records[](#text-records "Link to this heading") #### Set Text Metadata for an ENS Record[](#set-text-metadata-for-an-ens-record "Link to this heading") As the owner of an ENS record, you can add text metadata. A list of supported fields can be found in the [ENS documentation](https://docs.ens.domains/resolvers/public#get-text-data) . You’ll need to setup the address first, and then the text can be set: ns.setup\_address('ens.eth', '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') ns.set\_text('ens.eth', 'url', 'https://example.com') A transaction dictionary can be passed as the last argument if desired: transaction\_dict \= {'from': '0x123...'} ns.set\_text('ens.eth', 'url', 'https://example.com', transaction\_dict) If the transaction dictionary is not passed, sensible defaults will be used, and if a transaction dictionary is passed but does not have a `from` value, the default will be the `owner`. #### Read Text Metadata for an ENS Record[](#read-text-metadata-for-an-ens-record "Link to this heading") Anyone can read the data from an ENS Record: url \= ns.get\_text('ens.eth', 'url') assert url \== 'https://example.com' * * * ### Working With Resolvers[](#working-with-resolvers "Link to this heading") #### Get the Resolver for an ENS Record[](#get-the-resolver-for-an-ens-record "Link to this heading") You can get the resolver for an ENS name via the `resolver()` method. \>>> resolver \= ns.resolver('ens.eth') \>>> resolver.address '0x5B2063246F2191f18F2675ceDB8b28102e957458' * * * Wildcard Resolution Support[](#wildcard-resolution-support "Link to this heading") ------------------------------------------------------------------------------------ The `ENS` module supports Wildcard Resolution for resolvers that implement the `ExtendedResolver` interface as described in [ENSIP-10](https://docs.ens.domains/ensip/10) . Resolvers that implement the extended resolver interface should return `True` when calling the `supportsInterface()` function with the extended resolver interface id `"0x9061b923"` and should resolve subdomains to a unique address. --- # Migration Guide — web3.py 7.6.1 documentation * [](index.html) * Migration Guide * [View page source](_sources/migration.rst.txt) * * * Migration Guide[](#migration-guide "Link to this heading") ============================================================ Migrating from v6 to v7[](#migrating-from-v6-to-v7 "Link to this heading") ---------------------------------------------------------------------------- web3.py follows [Semantic Versioning](http://semver.org) , which means that version 7 introduced backwards-incompatible changes. If you’re upgrading from web3.py `v6` or earlier, you can expect to need to make some changes. Refer to this guide for a summary of breaking changes when updating from `v6` to `v7`. If you are more than one major version behind, you should also review the migration guides for the versions in between. ### Provider Updates[](#provider-updates "Link to this heading") #### WebSocketProvider[](#websocketprovider "Link to this heading") `WebsocketProviderV2`, introduced in web3.py `v6`, has taken priority over the legacy `WebsocketProvider`. The `LegacyWebSocketProvider` has been deprecated in `v7` and is slated for removal in the next major version of the library. In summary: * `WebsocketProvider` -> `LegacyWebSocketProvider` (and deprecated) * `WebsocketProviderV2` -> `WebSocketProvider` If migrating from `WebSocketProviderV2` to `WebSocketProvider`, you can expect the following changes: * Instantiation no longer requires the `persistant_websocket` method: \# WebsocketsProviderV2: AsyncWeb3.persistent\_websocket(WebsocketProviderV2('...')) \# WebSocketProvider: AsyncWeb3(WebSocketProvider('...')) * Handling incoming subscription messages now occurs under a more flexible namespace: `socket`. The `AsyncIPCProvider` uses the same API to listen for messages via an IPC socket. \# WebsocketsProviderV2: async for message in w3.ws.process\_subscriptions(): ... \# WebSocketProvider: async for message in w3.socket.process\_subscriptions(): ... #### AsyncIPCProvider (non-breaking feature)[](#asyncipcprovider-non-breaking-feature "Link to this heading") An asynchronous IPC provider, `AsyncIPCProvider`, is newly available in `v7`. This provider makes use of some of the same internals that the new `WebSocketProvider` introduced, allowing it to also support `eth_subscription`. #### EthereumTesterProvider[](#ethereumtesterprovider "Link to this heading") `EthereumTesterProvider` now returns `input` instead of `data` for `eth_getTransaction*` calls, as expected. ### Middlewares -> Middleware[](#middlewares-middleware "Link to this heading") All references to `middlewares` have been replaced with the more grammatically correct `middleware`. Notably, this includes when a provider needs to be instantiated with custom middleware. ### Class-Based Middleware Model[](#class-based-middleware-model "Link to this heading") The middleware model has been changed to a class-based model. \# v6 (no longer supported) from web3.middleware import pythonic\_middleware w3.middleware\_onion.add(pythonic\_middleware) \# v7 from web3.middleware import PythonicMiddleware w3.middleware\_onion.add(PythonicMiddleware) Previously, middleware were defined as functions that tightly wrapped the provider’s `make_request` function, where transformations could be conditionally applied before and after the request was made. Now, middleware logic can be separated into `request_processor` and `response_processor` functions that enable pre-request and post-response logic, respectively. This change offers a simpler, clearer interface for defining middleware, gives more flexibility for asynchronous operations and also paved the way for supporting [Batch Requests](web3.main.html#batch-requests) . Major changes for migration are highlighted in this section. Consult the [Middleware](middleware.html#middleware-internals) section of the documentation for specifics and examples on the new class-based design. ### Middleware Builder Classes[](#middleware-builder-classes "Link to this heading") In `v6`, certain middleware needed to be constructed with parameters. This was done by passing the parameters to a constructor method. \# v6 (no longer supported) from web3.middleware import construct\_sign\_and\_send\_raw\_middleware w3.middleware\_onion.add(construct\_sign\_and\_send\_raw\_middleware(private\_key)) In the class-based `v7` middleware model, a middleware builder class is instantiated with the necessary parameters via the `build()` method. \# v7 from web3.middleware import SignAndSendRawMiddlewareBuilder w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(private\_key), layer\=0) ### Middleware Renaming and Removals[](#middleware-renaming-and-removals "Link to this heading") The following middleware have been renamed for generalization or clarity: * `name_to_address_middleware` -> `ENSNameToAddressMiddleware` * `geth_poa_middleware` -> `ExtraDataToPOAMiddleware` The following middleware have been removed: #### ABI Middleware[](#abi-middleware "Link to this heading") `abi_middleware` is no longer necessary and has been removed. All of the functionality of the `abi_middleware` was already handled by web3.py’s ABI formatters. For additional context: a bug in the ENS name-to-address middleware would override the formatters. Fixing this bug has removed the need for the `abi_middleware`. #### Caching Middleware[](#caching-middleware "Link to this heading") The following middleware have been removed: * `simple_cache_middleware` * `latest_block_based_cache_middleware` * `time_based_cache_middleware` All caching middleware has been removed in favor of a decorator/wrapper around the `make_request` methods of providers with configuration options on the provider class. The configuration options are outlined in the documentation in the [Request Caching](internals.html#request-caching) section. If desired, the previous caching middleware can be re-created using the new class-based middleware model overriding the `wrap_make_request` (or `async_wrap_make_request`) method in the middleware class. #### Result Generating Middleware[](#result-generating-middleware "Link to this heading") The following middleware have been removed: * `fixture_middleware` * `result_generator_middleware` The `fixture_middleware` and `result_generator_middleware` which were used for testing/mocking purposes have been removed. These have been replaced internally by the `RequestMocker` class, utilized for testing via a `request_mocker` pytest fixture. #### HTTP Retry Request Middleware[](#http-retry-request-middleware "Link to this heading") The `http_retry_request_middleware` has been removed in favor of a configuration option on the `HTTPProvider` and `AsyncHTTPProvider` classes. The configuration options are outlined in the documentation in the [Retry Requests for HTTP Providers](internals.html#http-retry-requests) section. #### Normalize Request Parameters Middleware[](#normalize-request-parameters-middleware "Link to this heading") The `normalize_request_parameters` middleware was not used anywhere internally and has been removed. ### Remaining camelCase -> snake\_case Updates[](#remaining-camelcase-snake-case-updates "Link to this heading") The following arguments have been renamed across the library from camelCase to snake\_case in all methods where they are passed in as a kwarg. * `fromBlock` -> `from_block` * `toBlock` -> `to_block` * `blockHash` -> `block_hash` Note that if a dictionary is used instead, say to a call such as eth\_getLogs, the keys in the dictionary should be camelCase. This is because the dictionary is passed directly to the JSON-RPC request, where the keys are expected to be in camelCase. ### Changes to Exception Handling[](#changes-to-exception-handling "Link to this heading") All Python standard library exceptions that were raised from within web3.py have been replaced with custom `Web3Exception` classes. This change allows for better control over exception handling, being able to distinguish between exceptions raised by web3.py and those raised from elsewhere in a codebase. The following exceptions have been replaced: * `AssertionError` -> `Web3AssertionError` * `ValueError` -> `Web3ValueError` * `TypeError` -> `Web3TypeError` * `AttributeError` -> `Web3AttributeError` A new `MethodNotSupported` exception is now raised when a method is not supported by web3.py. This allows a user to distinguish between when a method is not available on the current provider, `MethodUnavailable`, and when a method is not supported by web3.py under certain conditions, `MethodNotSupported`. A `MismatchedABI` exception is now raised instead of a `Web3ValidationError` in cases where an ABI is not compatible with the data being passed to it. This change allows for more specific error handling when using certain ABI types. #### JSON-RPC Error Handling[](#json-rpc-error-handling "Link to this heading") Rather than a `ValueError` being replaced with a `Web3ValueError` when a JSON-RPC response comes back with an `error` object, a new `Web3RPCError` exception is now raised to provide more distinction for JSON-RPC error responses. Some previously existing exceptions now extend from this class since they too are related to JSON-RPC errors: * `MethodUnavailable` * `BlockNotFound` * `TransactionNotFound` * `TransactionIndexingInProgress` ### End of Support and Feature Removals[](#end-of-support-and-feature-removals "Link to this heading") #### Python 3.7 Support Dropped[](#python-3-7-support-dropped "Link to this heading") Python 3.7 support has been dropped in favor of Python 3.8+. Python 3.7 is no longer supported by the Python core team, and we want to focus our efforts on supporting the latest versions of Python. #### EthPM Module Removed[](#ethpm-module-removed "Link to this heading") The EthPM module has been removed from the library. It was not widely used and has not been functional since around October 2022. It was deprecated in `v6` and has been completely removed in `v7`. Types in the [eth\_typing.ethpm](https://github.com/ethereum/eth-typing/blob/ef9c2d566b7747bb6799214e2c89006b8cde4c36/eth_typing/ethpm.py) module have been deprecated and will be removed from `eth-typing` in the next major release. #### Geth Miner Namespace Removed[](#geth-miner-namespace-removed "Link to this heading") The `geth.miner` namespace, deprecated in `v6`, has been removed in `v7`. The `miner` namespace was used for managing the concept of a miner in geth. This is no longer a feature in geth and is planned for complete removal in the future, with Ethereum having transitioned to proof-of-stake. #### Geth Personal Namespace Removed[](#geth-personal-namespace-removed "Link to this heading") The `geth.personal` namespace, deprecated in `v6`, has been removed in `v7`. The `personal` namespace was used for managing accounts and keys and was deprecated in geth in `v1.11.0`. Geth has moved to using `clef` for account and key management. #### ABI Types Removed[](#abi-types-removed "Link to this heading") The type definitions for ABIs, deprecated in `v6`, have been removed in `v7`. New types have been introduced in the `eth_typing` `v5` package for ABIs. Improvements have been made to make required types more explicit and to offer better semantics. The following types from `web3.types` have been removed: - `ABIEventParams` is no longer avaiable. Use `ABIComponentIndexed` from `eth_typing` to represent event input components. - `ABIEvent` now resides in `eth_typing`. `ABIEvent.type` and `ABIEvent.name` are now required fields. - `ABIFunctionComponents` and `ABIFunctionParams` are no longer available. Use `ABIComponent` from `eth_typing` to represent function input components. - `ABIFunction` now resides in `eth_typing`. `ABIFunction.type` and `ABIFunction.name` are now required fields. - `ABIElement` now resides in `eth_typing` and represents a `Union` of all valid ABI element types, `ABICallable`, `ABIEvent` and `ABIError`. ### Miscellaneous Changes[](#miscellaneous-changes "Link to this heading") * `LRU` has been removed from the library and dependency on `lru-dict` library was dropped. * `CallOverride` type was changed to `StateOverride` since more methods than `eth_call` utilize the state override params. * `User-Agent` header was changed to a more readable format. * `BaseContractFunctions` iterator now returns instances of `ContractFunction` rather than the function names. * `BaseContractFunction` class attribute `function_identifier` has been removed in favor of the `abi_element_identifier` attribute. * `web3.contract.utils.call_contract_function()` no longers uses `fn_abi` as a parameter. Instead, the `abi_callable` parameter of type `ABICallable` is used. * Beacon API filename change: `beacon/main.py` -> `beacon/beacon.py`. * The asynchronous version of `w3.eth.wait_for_transaction_receipt()` changes its signature to use `Optional[float]` instead of `float` since it may be `None`. * `get_default_ipc_path()` and `get_dev_ipc_path()` now return the path value without checking if the `geth.ipc` file exists. * `Web3.is_address()` returns `True` for non-checksummed addresses. * `Contract.encodeABI()` has been renamed to `Contract.encode_abi()`. The `fn_name` argument has been changed to `abi_element_identifier`. * JSON-RPC responses are now more strictly validated against the JSON-RPC 2.0 specification while providing more informative error messages for invalid responses. Migrating from v5 to v6[](#migrating-from-v5-to-v6 "Link to this heading") ---------------------------------------------------------------------------- web3.py follows [Semantic Versioning](http://semver.org) , which means that version 6 introduced backwards-incompatible changes. If your project depends on web3.py v6, then you’ll probably need to make some changes. Breaking Changes: ### Strict Bytes Checking by Default[](#strict-bytes-checking-by-default "Link to this heading") web3.py v6 moved to requiring strict bytes checking by default. This means that if an ABI specifies a `bytes4` argument, web3.py will invalidate any entry that is not encodable as a bytes type with length of 4. This means only 0x-prefixed hex strings with a length of 4 and bytes types with a length of 4 will be considered valid. This removes doubt that comes from inferring values and assuming they should be padded. This behavior was previously available in via the `w3.enable_strict_bytes_checking()` method. This is now, however, a toggleable flag on the `Web3` instance via the `w3.strict_bytes_type_checking` property. As outlined above, this property is set to `True` by default but can be toggled on and off via the property’s setter (e.g. `w3.strict_bytes_type_checking = False`). ### Snake Case[](#snake-case "Link to this heading") web3.py v6 moved to the more Pythonic convention of snake\_casing wherever possible. There are some exceptions to this pattern: * Contract methods and events use whatever is listed in the ABI. If the smart contract convention is to use camelCase for method and event names, web3.py won’t do any magic to convert it to snake\_casing. * Arguments to JSON-RPC methods. For example: transaction and filter parameters still use camelCasing. The reason for this is primarily due to error messaging. It would be confusing to pass in a snake\_cased parameter and get an error message with a camelCased parameter. * Data that is returned from JSON-RPC methods. For example: The keys in a transaction receipt will still be returned as camelCase. ### Python 3.10 and 3.11 Support[](#python-3-10-and-3-11-support "Link to this heading") Support for Python 3.10 and 3.11 is here. In order to support Python 3.10, we had to update the `websockets` dependency to v10+. ### Exceptions[](#exceptions "Link to this heading") #### Exceptions inherit from a base class[](#exceptions-inherit-from-a-base-class "Link to this heading") In v5, some web3.py exceptions inherited from `AttributeError`, namely: * `NoABIFunctionsFound` * `NoABIFound` * `NoABIEventsFound` Others inherited from `ValueError`, namely: * `InvalidAddress` * `NameNotFound` * `LogTopicError` * `InvalidEventABI` Now web3.py exceptions inherit from the same base `Web3Exception`. As such, any code that was expecting a `ValueError` or an `AttributeError` from web3.py must update to expecting one of the exceptions listed above, or `Web3Exception`. Similarly, exceptions raised in the EthPM and ENS modules inherit from the base `EthPMException` and `ENSException`, respectively. #### ValidationError[](#validationerror "Link to this heading") The Python dev tooling ecosystem is moving towards standardizing `ValidationError`, so users know that they’re catching the correct `ValidationError`. The base `ValidationError` is imported from `eth_utils`. However, we also wanted to empower users to catch all errors emitted by a particular module. So we now have a `Web3ValidationError`, `EthPMValidationError`, and an `ENSValidationError` that all inherit from the generic `eth_utils.exceptions.ValidationError`. ### Web3 class split into Web3 and AsyncWeb3[](#web3-class-split-into-web3-and-asyncweb3 "Link to this heading") The Web3 class previously contained both sync and async methods. We’ve separated Web3 and AsyncWeb3 functionality to tighten up typing. For example: from web3 import Web3, AsyncWeb3 w3 \= Web3(Web3.HTTPProvider()) async\_w3 \= AsyncWeb3(AsyncWeb3.AsyncHTTPProvider()) ### dict to AttributeDict conversion moved to middleware[](#dict-to-attributedict-conversion-moved-to-middleware "Link to this heading") Eth module data returned as key-value pairs was previously automatically converted to an AttributeDict by result formatters, which could cause problems with typing. This conversion has been moved to a default attrdict\_middleware where it can be easily removed if necessary. See the [Eth module](web3.eth.html#web3.eth.Eth) docs for more detail. ### Other Misc Changes[](#other-misc-changes "Link to this heading") * `InfuraKeyNotFound` exception has been changed to `InfuraProjectIdNotFound` * `SolidityError` has been removed in favor of `ContractLogicError` * When a method is unavailable from a node provider (i.e. a response error code of -32601 is returned), a `MethodUnavailable` error is now raised instead of `ValueError` * Logs’ data field was previously formatted with to\_ascii\_if\_bytes, now formatted to HexBytes * Receipts’ type field was previously not formatted, now formatted with to\_integer\_if\_hex ### Removals[](#removals "Link to this heading") * Removed unused IBAN module * Removed `WEB3_INFURA_API_KEY` environment variable in favor of `WEB3_INFURA_PROJECT_ID` * Removed Kovan auto provider * Removed deprecated `sha3` and `soliditySha3` methods in favor of `keccak` and `solidityKeccak` * Remove Parity Module and References ### Other notable changes[](#other-notable-changes "Link to this heading") * The `ipfshttpclient` library is now opt-in via a web3 install extra. This only affects the ethpm ipfs backends, which rely on the library. Migrating from v4 to v5[](#migrating-from-v4-to-v5 "Link to this heading") ---------------------------------------------------------------------------- Web3.py follows [Semantic Versioning](http://semver.org) , which means that version 5 introduced backwards-incompatible changes. If your project depends on Web3.py v4, then you’ll probably need to make some changes. Here are the most common required updates: ### Python 3.5 no longer supported[](#python-3-5-no-longer-supported "Link to this heading") You will need to upgrade to either Python 3.6 or 3.7 ### `eth-abi` v1 no longer supported[](#eth-abi-v1-no-longer-supported "Link to this heading") You will need to upgrade the `eth-abi` dependency to v2 ### Changes to base API[](#changes-to-base-api "Link to this heading") #### JSON-RPC Updates[](#json-rpc-updates "Link to this heading") In v4, JSON-RPC calls that looked up transactions or blocks and didn’t find them, returned `None`. Now if a transaction or block is not found, a `BlockNotFound` or a `TransactionNotFound` error will be thrown as appropriate. This applies to the following web3 methods: * `getTransaction()` will throw a `TransactionNotFound` error * `getTransactionReceipt()` will throw a `TransactionNotFound` error * `getTransactionByBlock()` will throw a `TransactionNotFound` error * `getTransactionCount()` will throw a `BlockNotFound` error * `getBlock()` will throw a `BlockNotFound` error * `getUncleCount()` will throw a `BlockNotFound` error * `getUncleByBlock()` will throw a `BlockNotFound` error #### Removed Methods[](#removed-methods "Link to this heading") * `contract.buildTransaction` was removed for `contract.functions.buildTransaction.` * `contract.deploy` was removed for `contract.constructor.transact` * `contract.estimateGas` was removed for `contract.functions..estimateGas` * `contract.call` was removed for `contract...call` * `contract.transact` was removed for `contract...transact` * `contract.eventFilter` was removed for `contract.events..createFilter` * `middleware_stack` was renamed to `middleware_onion()` * `web3.miner.hashrate` was a duplicate of `hashrate()` and was removed. * `web3.version.network` was a duplicate of `version()` and was removed. * `web3.providers.tester.EthereumTesterProvider` and `web3.providers.tester.TestRPCProvider` have been removed for [`EthereumTesterProvider()`](providers.html#web3.providers.eth_tester.EthereumTesterProvider "web3.providers.eth_tester.EthereumTesterProvider") * `web3.eth.enableUnauditedFeatures` was removed * `web3.txpool` was moved to [`txpool()`](web3.geth.html#module-web3.geth.txpool "web3.geth.txpool") * `web3.version.node` was removed for `web3.clientVersion` * `web3.version.ethereum` was removed for `protocolVersion()` * Relocated personal RPC endpoints to reflect Parity and Geth implementations: * `web3.personal.listAccounts` was removed for `listAccounts()` or `listAccounts()` * `web3.personal.importRawKey` was removed for `importRawKey()` or `importRawKey()` * `web3.personal.newAccount` was removed for `newAccount()` or `newAccount()` * `web3.personal.lockAccount` was removed for `lockAccount()` * `web3.personal.unlockAccount` was removed for `unlockAccount()` or `unlockAccount()` * `web3.personal.sendTransaction` was removed for `sendTransaction()` or `sendTransaction()` * Relocated `web3.admin` module to `web3.geth` namespace * Relocated `web3.miner` module to `web3.geth` namespace #### Deprecated Methods[](#deprecated-methods "Link to this heading") Expect the following methods to be removed in v6: * `web3.sha3` was deprecated for `keccak()` * `web3.soliditySha3` was deprecated for `solidityKeccak()` * `chainId()` was deprecated for `chainId()`. Follow issue [#1293](https://github.com/ethereum/web3.py/issues/1293) for details * `web3.eth.getCompilers()` was deprecated and will not be replaced * `getTransactionFromBlock()` was deprecated for `getTransactionByBlock()` #### Deprecated ConciseContract and ImplicitContract[](#deprecated-concisecontract-and-implicitcontract "Link to this heading") The ConciseContract and ImplicitContract have been deprecated and will be removed in v6. ImplicitContract instances will need to use the verbose syntax. For example: `contract.functions..transact({})` ConciseContract has been replaced with the ContractCaller API. Instead of using the ConciseContract factory, you can now use: `contract.caller.` or the classic contract syntax: `contract.functions..call()`. Some more concrete examples can be found in the [ContractCaller docs](https://web3py.readthedocs.io/en/stable/web3.contract.html#contractcaller) ### Manager Provider[](#manager-provider "Link to this heading") In v5, only a single provider will be allowed. While allowing multiple providers is a feature we’d like to support in the future, the way that multiple providers was handled in v4 wasn’t ideal. The only thing they could do was fall back. There was no mechanism for any round robin, nor was there any control around which provider was chosen. Eventually, the idea is to expand the Manager API to support injecting custom logic into the provider selection process. For now, `manager.providers` has changed to `manager.provider`. Similarly, instances of `web3.providers` have been changed to `web3.provider`. ### Testnet Changes[](#testnet-changes "Link to this heading") Web3.py will no longer automatically look up a testnet connection in IPCProvider. ### ENS[](#ens "Link to this heading") Web3.py has stopped inferring the `.eth` TLD on domain names. If a domain name is used instead of an address, you’ll need to specify the TLD. An `InvalidTLD` error will be thrown if the TLD is missing. ### Required Infura API Key[](#required-infura-api-key "Link to this heading") In order to interact with Infura after March 27, 2019, you’ll need to set an environment variable called `WEB3_INFURA_PROJECT_ID`. You can get a project id by visiting [https://infura.io/register](https://infura.io/register) . Migrating from v3 to v4[](#migrating-from-v3-to-v4 "Link to this heading") ---------------------------------------------------------------------------- Web3.py follows [Semantic Versioning](http://semver.org) , which means that version 4 introduced backwards-incompatible changes. If your project depends on Web3.py v3, then you’ll probably need to make some changes. Here are the most common required updates: ### Python 2 to Python 3[](#python-2-to-python-3 "Link to this heading") Only Python 3 is supported in v4. If you are running in Python 2, it’s time to upgrade. We recommend using 2to3 which can make most of your code compatible with Python 3, automatically. The most important update, relevant to Web3.py, is the new [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)") type. It is used regularly, throughout the library, whenever dealing with data that is not guaranteed to be text. Many different methods in Web3.py accept text or binary data, like contract methods, transaction details, and cryptographic functions. The following example uses `sha3()`, but the same pattern applies elsewhere. In v3 & Python 2, you might have calculated the hash of binary data this way: \>>> Web3.sha3('I\\xe2\\x99\\xa5SF') '0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e' Or, you might have calculated the hash of text data this way: \>>> Web3.sha3(text\=u'I♥SF') '0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e' After switching to Python 3, these would instead be executed as: \>>> Web3.sha3(b'I\\xe2\\x99\\xa5SF') HexBytes('0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e') \>>> Web3.sha3(text\='I♥SF') HexBytes('0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e') Note that the return value is different too: you can treat [`hexbytes.main.HexBytes`](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)") like any other bytes value, but the representation on the console shows you the hex encoding of those bytes, for easier visual comparison. It takes a little getting used to, but the new py3 types are much better. We promise. ### Filters[](#filters "Link to this heading") Filters usually don’t work quite the way that people want them to. The first step toward fixing them was to simplify them by removing the polling logic. Now, you must request an update on your filters explicitly. That means that any exceptions during the request will bubble up into your code. In v3, those exceptions (like “filter is not found”) were swallowed silently in the automated polling logic. Here was the invocation for printing out new block hashes as they appear: \>>> def new\_block\_callback(block\_hash): ... print(f"New Block: {block\_hash}") ... \>>> new\_block\_filter \= web3.eth.filter('latest') \>>> new\_block\_filter.watch(new\_block\_callback) In v4, that same logic: \>>> new\_block\_filter \= web3.eth.filter('latest') \>>> for block\_hash in new\_block\_filter.get\_new\_entries(): ... print(f"New Block: {block\_hash}") The caller is responsible for polling the results from `get_new_entries()`. See [Asynchronous Filter Polling](filters.html#asynchronous-filters) for examples of filter-event handling with web3 v4. ### TestRPCProvider and EthereumTesterProvider[](#testrpcprovider-and-ethereumtesterprovider "Link to this heading") These providers are fairly uncommon. If you don’t recognize the names, you can probably skip the section. However, if you were using web3.py for testing contracts, you might have been using TestRPCProvider or EthereumTesterProvider. In v4 there is a new `EthereumTesterProvider`, and the old v3 implementation has been removed. Web3.py v4 uses `eth_tester.main.EthereumTester` under the hood, instead of eth-testrpc. While `eth-tester` is still in beta, many parts are already in better shape than testrpc, so we decided to replace it in v4. If you were using TestRPC, or were explicitly importing EthereumTesterProvider, like: `from web3.providers.tester import EthereumTesterProvider`, then you will need to update. With v4 you should import with `from web3 import EthereumTesterProvider`. As before, you’ll need to install Web3.py with the `tester` extra to get these features, like: $ pip install web3\[tester\] ### Changes to base API convenience methods[](#changes-to-base-api-convenience-methods "Link to this heading") #### Web3.toDecimal()[](#web3-todecimal "Link to this heading") In v4 `Web3.toDecimal()` is renamed: `toInt()` for improved clarity. It does not return a [`decimal.Decimal`](https://docs.python.org/3/library/decimal.html#decimal.Decimal "(in Python v3.13)") , it returns an [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") . #### Removed Methods[](#id5 "Link to this heading") * `Web3.toUtf8` was removed for `toText()`. * `Web3.fromUtf8` was removed for `toHex()`. * `Web3.toAscii` was removed for `toBytes()`. * `Web3.fromAscii` was removed for `toHex()`. * `Web3.fromDecimal` was removed for `toHex()`. ### Provider Access[](#provider-access "Link to this heading") In v4, `w3.currentProvider` was removed, in favor of `w3.providers`. ### Disambiguating String Inputs[](#disambiguating-string-inputs "Link to this heading") There are a number of places where an arbitrary string input might be either a byte-string that has been hex-encoded, or unicode characters in text. These are named `hexstr` and `text` in Web3.py. You specify which kind of [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") you have by using the appropriate keyword argument. See examples in [Encoding and Decoding Helpers](web3.main.html#overview-type-conversions) . In v3, some methods accepted a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") as the first positional argument. In v4, you must pass strings as one of `hexstr` or `text` keyword arguments. Notable methods that no longer accept ambiguous strings: * `sha3()` * `toBytes()` ### Contracts[](#contracts "Link to this heading") * When a contract returns the ABI type `string`, Web3.py v4 now returns a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") value by decoding the underlying bytes using UTF-8. * When a contract returns the ABI type `bytes` (of any length), Web3.py v4 now returns a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)") value ### Personal API[](#personal-api "Link to this heading") `w3.personal.signAndSendTransaction` is no longer available. Use `w3.personal.sendTransaction()` instead. --- # Events and Logs — web3.py 7.6.1 documentation * [](index.html) * Events and Logs * [View page source](_sources/filters.rst.txt) * * * Events and Logs[](#events-and-logs "Link to this heading") ============================================================ If you’re on this page, you’re likely looking for an answer to this question: **How do I know when a specific contract is used?** You have several options: 1. Query blocks for transactions that include the contract address in the `"to"` field. This contrived example is searching the latest block for any transactions sent to the [WETH](https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code) contract. WETH\_ADDRESS \= '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' block \= w3.eth.get\_block('latest') for tx\_hash in block.transactions: tx \= w3.eth.get\_transaction(tx\_hash) if tx\['to'\] \== WETH\_ADDRESS: print(f'Found interaction with WETH contract! {tx}') 2. Query for logs emitted by a contract. After instantiating a web3.py Contract object, you can [fetch logs](web3.contract.html#contract-get-logs) for any event listed in the ABI. In this example, we query for `Transfer` events in the latest block and log out the results. WETH\_ADDRESS \= '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' WETH\_ABI \= '\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":\[{"name":"wad","type":"uint256"}\],"name":"withdraw","outputs":\[\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":\[{"name":"","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":\[\],"name":"deposit","outputs":\[\],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":\[{"name":"","type":"address"},{"name":"","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Approval","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"src","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Withdrawal","type":"event"}\]' weth\_contract \= w3.eth.contract(address\=WETH\_ADDRESS, abi\=WETH\_ABI) \# fetch transfer events in the last block logs \= weth\_contract.events.Transfer().get\_logs(from\_block\=w3.eth.block\_number) for log in logs: print(f"Transfer of {w3.from\_wei(log.args.wad, 'ether')} WETH from {log.args.src} to {log.args.dst}") See an advanced example of fetching log history [here](#advanced-token-fetch) . 3. Subscribe to events for real-time updates. When using a persistent connection provider ([`WebSocketProvider`](providers.html#web3.providers.persistent.WebSocketProvider "web3.providers.persistent.WebSocketProvider") or [`AsyncIPCProvider`](providers.html#web3.providers.persistent.AsyncIPCProvider "web3.providers.persistent.AsyncIPCProvider") ), the [`subscribe()`](web3.eth.html#web3.eth.Eth.subscribe "web3.eth.Eth.subscribe") method can be used to establish a new event subscription. This example subscribes to `Transfer` events of the WETH contract. > import asyncio > from web3 import AsyncWeb3, WebSocketProvider > from eth\_abi.abi import decode > > WETH\_ADDRESS \= "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" > > async def subscribe\_to\_transfer\_events(): > async with AsyncWeb3(WebSocketProvider("...")) as w3: > transfer\_event\_topic \= w3.keccak(text\="Transfer(address,address,uint256)") > filter\_params \= { > "address": WETH\_ADDRESS, > "topics": \[transfer\_event\_topic\], > } > subscription\_id \= await w3.eth.subscribe("logs", filter\_params) > print(f"Subscribing to transfer events for WETH at {subscription\_id}") > > async for payload in w3.socket.process\_subscriptions(): > result \= payload\["result"\] > > from\_addr \= decode(\["address"\], result\["topics"\]\[1\])\[0\] > to\_addr \= decode(\["address"\], result\["topics"\]\[2\])\[0\] > amount \= decode(\["uint256"\], result\["data"\])\[0\] > print(f"{w3.from\_wei(amount, 'ether')} WETH from {from\_addr} to {to\_addr}") > > asyncio.run(subscribe\_to\_transfer\_events()) > > For more usage examples see the docs on [Using Persistent Connection Providers](providers.html#subscription-examples) > . 4. Use a filter. Warning While filters can be a very convenient way to monitor for blocks, transactions, or events, they are notoriously unreliable. Both remote and locally hosted nodes have a reputation for occasionally dropping filters, and some remote node providers don’t support filter-related RPC calls at all. The [`web3.eth.Eth.filter()`](web3.eth.html#web3.eth.Eth.filter "web3.eth.Eth.filter") method can be used to set up filters for: * Pending Transactions: `w3.eth.filter("pending")` * New Blocks `w3.eth.filter("latest")` * Event Logs > Through the contract instance api: > > event\_filter \= my\_contract.events.myEvent.create\_filter(from\_block\='latest', argument\_filters\={'arg1':10}) > > Or built manually by supplying [valid filter params](https://github.com/ethereum/execution-apis/blob/bea0266c42919a2fb3ee524fb91e624a23bc17c5/src/schemas/filter.json#L28) > : > > event\_filter \= w3.eth.filter({"address": contract\_address}) * Attaching to an existing filter > existing\_filter \= w3.eth.filter(filter\_id\="0x0") Note Creating event filters requires that your Ethereum node has an API support enabled for filters. Note that Infura support for filters does not offer access to pending filters. To get event logs on other stateless nodes please see `web3.contract.ContractEvents`. Filter Class[](#filter-class "Link to this heading") ------------------------------------------------------ _class_ web3.utils.filters.Filter(_web3_, _filter\_id_)[](#web3.utils.filters.Filter "Link to this definition") Filter.filter\_id[](#web3.utils.filters.Filter.filter_id "Link to this definition") The `filter_id` for this filter as returned by the `eth_newFilter` RPC method when this filter was created. Filter.get\_new\_entries()[](#web3.utils.filters.Filter.get_new_entries "Link to this definition") Retrieve new entries for this filter. Logs will be retrieved using the [`web3.eth.Eth.get_filter_changes()`](web3.eth.html#web3.eth.Eth.get_filter_changes "web3.eth.Eth.get_filter_changes") which returns only new entries since the last poll. Filter.get\_all\_entries()[](#web3.utils.filters.Filter.get_all_entries "Link to this definition") Retrieve all entries for this filter. Logs will be retrieved using the [`web3.eth.Eth.get_filter_logs()`](web3.eth.html#web3.eth.Eth.get_filter_logs "web3.eth.Eth.get_filter_logs") which returns all entries that match the given filter. Filter.format\_entry(_entry_)[](#web3.utils.filters.Filter.format_entry "Link to this definition") Hook for subclasses to modify the format of the log entries this filter returns, or passes to its callback functions. By default this returns the `entry` parameter unmodified. Filter.is\_valid\_entry(_entry_)[](#web3.utils.filters.Filter.is_valid_entry "Link to this definition") Hook for subclasses to add additional programmatic filtering. The default implementation always returns `True`. Block and Transaction Filter Classes[](#block-and-transaction-filter-classes "Link to this heading") ------------------------------------------------------------------------------------------------------ _class_ web3.utils.filters.BlockFilter(_..._)[](#web3.utils.filters.BlockFilter "Link to this definition") `BlockFilter` is a subclass of [`Filter`](#web3.utils.filters.Filter "web3.utils.filters.Filter") . You can setup a filter for new blocks using `web3.eth.filter('latest')` which will return a new [`BlockFilter`](#web3.utils.filters.BlockFilter "web3.utils.filters.BlockFilter") object. > new\_block\_filter \= w3.eth.filter('latest') > new\_block\_filter.get\_new\_entries() > > Note > > `"safe"` and `"finalized"` block identifiers are not yet supported for `eth_newBlockFilter`. _class_ web3.utils.filters.TransactionFilter(_..._)[](#web3.utils.filters.TransactionFilter "Link to this definition") `TransactionFilter` is a subclass of [`Filter`](#web3.utils.filters.Filter "web3.utils.filters.Filter") . You can setup a filter for new blocks using `web3.eth.filter('pending')` which will return a new [`TransactionFilter`](#web3.utils.filters.TransactionFilter "web3.utils.filters.TransactionFilter") object. > new\_transaction\_filter \= w3.eth.filter('pending') > new\_transaction\_filter.get\_new\_entries() Event Log Filters[](#event-log-filters "Link to this heading") ---------------------------------------------------------------- You can set up a filter for event logs using the web3.py contract api: [`web3.contract.Contract.events.your_event_name.create_filter()`](web3.contract.html#web3.contract.Contract.events.your_event_name.create_filter "web3.contract.Contract.events.your_event_name.create_filter") , which provides some conveniences for creating event log filters. Refer to the following example: > event\_filter \= my\_contract.events..create\_filter(from\_block\="latest", argument\_filters\={'arg1':10}) > event\_filter.get\_new\_entries() See [`web3.contract.Contract.events.your_event_name.create_filter()`](web3.contract.html#web3.contract.Contract.events.your_event_name.create_filter "web3.contract.Contract.events.your_event_name.create_filter") documentation for more information. You can set up an event log filter like the one above with `web3.eth.filter` by supplying a dictionary containing the standard filter parameters. Assuming that `arg1` is indexed, the equivalent filter creation would look like: > event\_signature\_hash \= web3.keccak(text\="eventName(uint32)").hex() > event\_filter \= web3.eth.filter({ > "address": myContract\_address, > "topics": \[event\_signature\_hash,\ > "0x000000000000000000000000000000000000000000000000000000000000000a"\], > }) The `topics` argument is order-dependent. For non-anonymous events, the first item in the topic list is always the keccack hash of the event signature. Subsequent topic items are the hex encoded values for indexed event arguments. In the above example, the second item is the `arg1` value `10` encoded to its hex string representation. In addition to being order-dependent, there are a few more points to recognize when specifying topic filters: > Given a transaction log with topics \[A, B\], the following topic filters will yield a match: > > * \[\] “anything” > > * \[A\] “A in first position (and anything after)” > > * \[None, B\] “anything in first position AND B in second position (and anything after)” > > * \[A, B\] “A in first position AND B in second position (and anything after)” > > * \[\[A, B\], \[A, B\]\] “(A OR B) in first position AND (A OR B) in second position (and anything after)” > See the JSON-RPC documentation for [eth\_newFilter](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_newfilter) more information on the standard filter parameters. > Note > > Though `"finalized"` and `"safe"` block identifiers are not yet part of the specifications for `eth_newFilter`, they are supported by web3.py and may or may not yield expected results depending on the node being accessed. Creating a log filter by either of the above methods will return a [`LogFilter`](#web3.utils.filters.LogFilter "web3.utils.filters.LogFilter") instance. _class_ web3.utils.filters.LogFilter(_web3_, _filter\_id_, _log\_entry\_formatter\=None_, _data\_filter\_set\=None_)[](#web3.utils.filters.LogFilter "Link to this definition") The [`LogFilter`](#web3.utils.filters.LogFilter "web3.utils.filters.LogFilter") class is a subclass of [`Filter`](#web3.utils.filters.Filter "web3.utils.filters.Filter") . See the [`Filter`](#web3.utils.filters.Filter "web3.utils.filters.Filter") documentation for inherited methods. [`LogFilter`](#web3.utils.filters.LogFilter "web3.utils.filters.LogFilter") provides the following additional methods: LogFilter.set\_data\_filters(_data\_filter\_set_)[](#web3.utils.filters.LogFilter.set_data_filters "Link to this definition") Provides a means to filter on the log data, in other words the ability to filter on values from un-indexed event arguments. The parameter `data_filter_set` should be a list or set of 32-byte hex encoded values. Examples: Listening For Events[](#examples-listening-for-events "Link to this heading") ----------------------------------------------------------------------------------------- ### Synchronous[](#synchronous "Link to this heading") > 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() ### Asynchronous Filter Polling[](#asynchronous-filter-polling "Link to this heading") Starting with web3 version 4, the `watch` method was taken out of the web3 filter objects. There are many decisions to be made when designing a system regarding threading and concurrency. Rather than force a decision, web3 leaves these choices up to the user. Below are some example implementations of asynchronous filter-event handling that can serve as starting points. #### Single threaded concurrency with `async` and `await`[](#single-threaded-concurrency-with-async-and-await "Link to this heading") Beginning in python 3.5, the `async` and `await` built-in keywords were added. These provide a shared api for coroutines that can be utilized by modules such as the built-in [asyncio](https://docs.python.org/3/library/asyncio.html) . Below is an example event loop using [asyncio](https://docs.python.org/3/library/asyncio.html) , that polls multiple web3 filter object, and passes new entries to a handler. > > from web3 import Web3, IPCProvider > > import asyncio > > > > \# instantiate Web3 instance > > w3 \= Web3(IPCProvider(...)) > > > > def handle\_event(event): > > print(event) > > \# and whatever > > > > async def log\_loop(event\_filter, poll\_interval): > > while True: > > for event in event\_filter.get\_new\_entries(): > > handle\_event(event) > > await asyncio.sleep(poll\_interval) > > > > def main(): > > block\_filter \= w3.eth.filter('latest') > > tx\_filter \= w3.eth.filter('pending') > > loop \= asyncio.get\_event\_loop() > > try: > > loop.run\_until\_complete( > > asyncio.gather( > > log\_loop(block\_filter, 2), > > log\_loop(tx\_filter, 2))) > > finally: > > loop.close() > > > > if \_\_name\_\_ \== '\_\_main\_\_': > > main() > > Read the [asyncio](https://docs.python.org/3/library/asyncio.html) > documentation for more information. #### Running the event loop in a separate thread[](#running-the-event-loop-in-a-separate-thread "Link to this heading") Here is an extended version of above example, where the event loop is run in a separate thread, releasing the `main` function for other tasks. > 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() Here are some other libraries that provide frameworks for writing asynchronous python: > * [gevent](https://www.gevent.org/) > > * [twisted](https://twistedmatrix.com/) > > * [celery](https://www.celeryproject.org/) > Examples[](#examples "Link to this heading") ---------------------------------------------- ### Advanced example: Fetching all token transfer events[](#advanced-example-fetching-all-token-transfer-events "Link to this heading") In this example, we show how to fetch all events of a certain event type from the Ethereum blockchain. There are three challenges when working with a large set of events: * How to incrementally update an existing database of fetched events * How to deal with interruptions in long running processes * How to deal with eth\_getLogs JSON-RPC call query limitations * How to handle Ethereum minor chain reorganisations in (near) real-time data #### eth\_getLogs limitations[](#eth-getlogs-limitations "Link to this heading") Ethereum JSON-RPC API servers, like Geth, do not provide an easy way to paginate over events, only over blocks. There’s no request that can find the first block with an event or how many events occur within a range of blocks. The only feedback the JSON-RPC service will give you is whether the `eth_getLogs` call failed. In this example script, we provide two kinds of heuristics to deal with this issue. The script scans events in a chunk of blocks (start block number - end block number). Then it uses two methods to find how many events there are likely to be in a block window: * Dynamically set the block range window size, while never exceeding a threshold (e.g., 10,000 blocks). * In the case of `eth_getLogs`, the JSON-RPC call gives a timeout error, decrease the end block number and tries again with a smaller block range window. #### Example code[](#example-code "Link to this heading") The following example code is divided into a reusable `EventScanner` class and then a demo script that: * fetches all transfer events for [RCC token](https://etherscan.io/token/0x9b6443b0fb9c241a7fdac375595cea13e6b7807a) , * can incrementally run again to check if there are new events, * handles interruptions (e.g., CTRL+C abort) gracefully, * writes all `Transfer` events in a single file JSON database, so that other process can consume them, * uses the [tqdm](https://pypi.org/project/tqdm/) library for progress bar output in a console, * only supports `HTTPS` providers, because JSON-RPC retry logic depends on the implementation details of the underlying protocol, * disables the default exception retry configuration because it does not know how to handle the shrinking block range window for `eth_getLogs`, and * consumes around 20k JSON-RPC API calls. The script can be run with: `python ./eventscanner.py `. """A stateful event scanner for Ethereum-based blockchains using web3.py. With the stateful mechanism, you can do one batch scan or incremental scans, where events are added wherever the scanner left off. """ import datetime import time import logging from abc import ABC, abstractmethod from typing import Tuple, Optional, Callable, List, Iterable, Dict, Any from web3 import Web3 from web3.contract import Contract from web3.datastructures import AttributeDict from web3.exceptions import BlockNotFound from eth\_abi.codec import ABICodec \# Currently this method is not exposed over official web3 API, \# but we need it to construct eth\_getLogs parameters from web3.\_utils.filters import construct\_event\_filter\_params from web3.\_utils.events import get\_event\_data logger \= logging.getLogger(\_\_name\_\_) class EventScannerState(ABC): """Application state that remembers what blocks we have scanned in the case of crash. """ @abstractmethod def get\_last\_scanned\_block(self) \-> int: """Number of the last block we have scanned on the previous cycle. :return: 0 if no blocks scanned yet """ @abstractmethod def start\_chunk(self, block\_number: int): """Scanner is about to ask data of multiple blocks over JSON-RPC. Start a database session if needed. """ @abstractmethod def end\_chunk(self, block\_number: int): """Scanner finished a number of blocks. Persistent any data in your state now. """ @abstractmethod def process\_event(self, block\_when: datetime.datetime, event: AttributeDict) \-> object: """Process incoming events. This function takes raw events from Web3, transforms them to your application internal format, then saves them in a database or some other state. :param block\_when: When this block was mined :param event: Symbolic dictionary of the event data :return: Internal state structure that is the result of event transformation. """ @abstractmethod def delete\_data(self, since\_block: int) \-> int: """Delete any data since this block was scanned. Purges any potential minor reorg data. """ class EventScanner: """Scan blockchain for events and try not to abuse JSON-RPC API too much. Can be used for real-time scans, as it detects minor chain reorganisation and rescans. Unlike the easy web3.contract.Contract, this scanner can scan events from multiple contracts at once. For example, you can get all transfers from all tokens in the same scan. You \*should\* disable the default \`\`exception\_retry\_configuration\`\` on your provider for Web3, because it cannot correctly throttle and decrease the \`eth\_getLogs\` block number range. """ def \_\_init\_\_(self, w3: Web3, contract: Contract, state: EventScannerState, events: List, filters: Dict\[str, Any\], max\_chunk\_scan\_size: int \= 10000, max\_request\_retries: int \= 30, request\_retry\_seconds: float \= 3.0): """ :param contract: Contract :param events: List of web3 Event we scan :param filters: Filters passed to get\_logs :param max\_chunk\_scan\_size: JSON-RPC API limit in the number of blocks we query. (Recommendation: 10,000 for mainnet, 500,000 for testnets) :param max\_request\_retries: How many times we try to reattempt a failed JSON-RPC call :param request\_retry\_seconds: Delay between failed requests to let JSON-RPC server to recover """ self.logger \= logger self.contract \= contract self.w3 \= w3 self.state \= state self.events \= events self.filters \= filters \# Our JSON-RPC throttling parameters self.min\_scan\_chunk\_size \= 10 \# 12 s/block = 120 seconds period self.max\_scan\_chunk\_size \= max\_chunk\_scan\_size self.max\_request\_retries \= max\_request\_retries self.request\_retry\_seconds \= request\_retry\_seconds \# Factor how fast we increase the chunk size if results are found \# # (slow down scan after starting to get hits) self.chunk\_size\_decrease \= 0.5 \# Factor how fast we increase chunk size if no results found self.chunk\_size\_increase \= 2.0 @property def address(self): return self.token\_address def get\_block\_timestamp(self, block\_num) \-> datetime.datetime: """Get Ethereum block timestamp""" try: block\_info \= self.w3.eth.get\_block(block\_num) except BlockNotFound: \# Block was not mined yet, \# minor chain reorganisation? return None last\_time \= block\_info\["timestamp"\] return datetime.datetime.utcfromtimestamp(last\_time) def get\_suggested\_scan\_start\_block(self): """Get where we should start to scan for new token events. If there are no prior scans, start from block 1. Otherwise, start from the last end block minus ten blocks. We rescan the last ten scanned blocks in the case there were forks to avoid misaccounting due to minor single block works (happens once in an hour in Ethereum). These heuristics could be made more robust, but this is for the sake of simple reference implementation. """ end\_block \= self.get\_last\_scanned\_block() if end\_block: return max(1, end\_block \- self.NUM\_BLOCKS\_RESCAN\_FOR\_FORKS) return 1 def get\_suggested\_scan\_end\_block(self): """Get the last mined block on Ethereum chain we are following.""" \# Do not scan all the way to the final block, as this \# block might not be mined yet return self.w3.eth.block\_number \- 1 def get\_last\_scanned\_block(self) \-> int: return self.state.get\_last\_scanned\_block() def delete\_potentially\_forked\_block\_data(self, after\_block: int): """Purge old data in the case of blockchain reorganisation.""" self.state.delete\_data(after\_block) def scan\_chunk(self, start\_block, end\_block) \-> Tuple\[int, datetime.datetime, list\]: """Read and process events between to block numbers. Dynamically decrease the size of the chunk if the case JSON-RPC server pukes out. :return: tuple(actual end block number, when this block was mined, processed events) """ block\_timestamps \= {} get\_block\_timestamp \= self.get\_block\_timestamp \# Cache block timestamps to reduce some RPC overhead \# Real solution might include smarter models around block def get\_block\_when(block\_num): if block\_num not in block\_timestamps: block\_timestamps\[block\_num\] \= get\_block\_timestamp(block\_num) return block\_timestamps\[block\_num\] all\_processed \= \[\] for event\_type in self.events: \# Callable that takes care of the underlying web3 call def \_fetch\_events(\_start\_block, \_end\_block): return \_fetch\_events\_for\_all\_contracts(self.w3, event\_type, self.filters, from\_block\=\_start\_block, to\_block\=\_end\_block) \# Do \`n\` retries on \`eth\_getLogs\`, \# throttle down block range if needed end\_block, events \= \_retry\_web3\_call( \_fetch\_events, start\_block\=start\_block, end\_block\=end\_block, retries\=self.max\_request\_retries, delay\=self.request\_retry\_seconds) for evt in events: idx \= evt\["logIndex"\] \# Integer of the log index position in the block, null when its pending \# We cannot avoid minor chain reorganisations, but \# at least we must avoid blocks that are not mined yet assert idx is not None, "Somehow tried to scan a pending block" block\_number \= evt\["blockNumber"\] \# Get UTC time when this event happened (block mined timestamp) \# from our in-memory cache block\_when \= get\_block\_when(block\_number) logger.debug(f"Processing event {evt\['event'\]}, block: {evt\['blockNumber'\]} count: {evt\['blockNumber'\]}") processed \= self.state.process\_event(block\_when, evt) all\_processed.append(processed) end\_block\_timestamp \= get\_block\_when(end\_block) return end\_block, end\_block\_timestamp, all\_processed def estimate\_next\_chunk\_size(self, current\_chuck\_size: int, event\_found\_count: int): """Try to figure out optimal chunk size Our scanner might need to scan the whole blockchain for all events \* We want to minimize API calls over empty blocks \* We want to make sure that one scan chunk does not try to process too many entries once, as we try to control commit buffer size and potentially asynchronous busy loop \* Do not overload node serving JSON-RPC API by asking data for too many events at a time Currently Ethereum JSON-API does not have an API to tell when a first event occurred in a blockchain and our heuristics try to accelerate block fetching (chunk size) until we see the first event. These heuristics exponentially increase the scan chunk size depending on if we are seeing events or not. When any transfers are encountered, we are back to scanning only a few blocks at a time. It does not make sense to do a full chain scan starting from block 1, doing one JSON-RPC call per 20 blocks. """ if event\_found\_count \> 0: \# When we encounter first events, reset the chunk size window current\_chuck\_size \= self.min\_scan\_chunk\_size else: current\_chuck\_size \*= self.chunk\_size\_increase current\_chuck\_size \= max(self.min\_scan\_chunk\_size, current\_chuck\_size) current\_chuck\_size \= min(self.max\_scan\_chunk\_size, current\_chuck\_size) return int(current\_chuck\_size) def scan(self, start\_block, end\_block, start\_chunk\_size\=20, progress\_callback\=Optional\[Callable\]) \-> Tuple\[\ list, int\]: """Perform a token balances scan. Assumes all balances in the database are valid before start\_block (no forks sneaked in). :param start\_block: The first block included in the scan :param end\_block: The last block included in the scan :param start\_chunk\_size: How many blocks we try to fetch over JSON-RPC on the first attempt :param progress\_callback: If this is an UI application, update the progress of the scan :return: \[All processed events, number of chunks used\] """ assert start\_block <= end\_block current\_block \= start\_block \# Scan in chunks, commit between chunk\_size \= start\_chunk\_size last\_scan\_duration \= last\_logs\_found \= 0 total\_chunks\_scanned \= 0 \# All processed entries we got on this scan cycle all\_processed \= \[\] while current\_block <= end\_block: self.state.start\_chunk(current\_block, chunk\_size) \# Print some diagnostics to logs to try to fiddle with real world JSON-RPC API performance estimated\_end\_block \= min(current\_block + chunk\_size, end\_block) logger.debug( f"Scanning token transfers for blocks: {current\_block} - {estimated\_end\_block}, chunk size {chunk\_size}, last chunk scan took {last\_scan\_duration}, last logs found {last\_logs\_found}" ) start \= time.time() actual\_end\_block, end\_block\_timestamp, new\_entries \= self.scan\_chunk(current\_block, estimated\_end\_block) \# Where does our current chunk scan ends - are we out of chain yet? current\_end \= actual\_end\_block last\_scan\_duration \= time.time() \- start all\_processed += new\_entries \# Print progress bar if progress\_callback: progress\_callback(start\_block, end\_block, current\_block, end\_block\_timestamp, chunk\_size, len(new\_entries)) \# Try to guess how many blocks to fetch over \`eth\_getLogs\` API next time chunk\_size \= self.estimate\_next\_chunk\_size(chunk\_size, len(new\_entries)) \# Set where the next chunk starts current\_block \= current\_end + 1 total\_chunks\_scanned += 1 self.state.end\_chunk(current\_end) return all\_processed, total\_chunks\_scanned def \_retry\_web3\_call(func, start\_block, end\_block, retries, delay) \-> Tuple\[int, list\]: """A custom retry loop to throttle down block range. If our JSON-RPC server cannot serve all incoming \`eth\_getLogs\` in a single request, we retry and throttle down block range for every retry. For example, Go Ethereum does not indicate what is an acceptable response size. It just fails on the server-side with a "context was cancelled" warning. :param func: A callable that triggers Ethereum JSON-RPC, as func(start\_block, end\_block) :param start\_block: The initial start block of the block range :param end\_block: The initial start block of the block range :param retries: How many times we retry :param delay: Time to sleep between retries """ for i in range(retries): try: return end\_block, func(start\_block, end\_block) except Exception as e: \# Assume this is HTTPConnectionPool(host='localhost', port=8545): Read timed out. (read timeout=10) \# from Go Ethereum. This translates to the error "context was cancelled" on the server side: \# https://github.com/ethereum/go-ethereum/issues/20426 if i < retries \- 1: \# Give some more verbose info than the default middleware logger.warning( f"Retrying events for block range {start\_block} - {end\_block} ({end\_block\-start\_block}) failed with {e} , retrying in {delay} seconds") \# Decrease the \`eth\_getBlocks\` range end\_block \= start\_block + ((end\_block \- start\_block) // 2) \# Let the JSON-RPC to recover e.g. from restart time.sleep(delay) continue else: logger.warning("Out of retries") raise def \_fetch\_events\_for\_all\_contracts( w3, event, argument\_filters: Dict\[str, Any\], from\_block: int, to\_block: int) \-> Iterable: """Get events using eth\_getLogs API. This method is detached from any contract instance. This is a stateless method, as opposed to create\_filter. It can be safely called against nodes which do not provide \`eth\_newFilter\` API, like Infura. """ if from\_block is None: raise Web3TypeError("Missing mandatory keyword argument to get\_logs: from\_block") \# Currently no way to poke this using a public web3.py API. \# This will return raw underlying ABI JSON object for the event abi \= event.\_get\_event\_abi() \# Depending on the Solidity version used to compile \# the contract that uses the ABI, \# it might have Solidity ABI encoding v1 or v2. \# We just assume the default that you set on Web3 object here. \# More information here https://eth-abi.readthedocs.io/en/latest/index.html codec: ABICodec \= w3.codec \# Here we need to poke a bit into Web3 internals, as this \# functionality is not exposed by default. \# Construct JSON-RPC raw filter presentation based on human readable Python descriptions \# Namely, convert event names to their keccak signatures \# More information here: \# https://github.com/ethereum/web3.py/blob/e176ce0793dafdd0573acc8d4b76425b6eb604ca/web3/\_utils/filters.py#L71 data\_filter\_set, event\_filter\_params \= construct\_event\_filter\_params( abi, codec, address\=argument\_filters.get("address"), argument\_filters\=argument\_filters, from\_block\=from\_block, to\_block\=to\_block ) logger.debug(f"Querying eth\_getLogs with the following parameters: {event\_filter\_params}") \# Call JSON-RPC API on your Ethereum node. \# get\_logs() returns raw AttributedDict entries logs \= w3.eth.get\_logs(event\_filter\_params) \# Convert raw binary data to Python proxy objects as described by ABI all\_events \= \[\] for log in logs: \# Convert raw JSON-RPC log result to human readable event by using ABI data \# More information how process\_log works here \# https://github.com/ethereum/web3.py/blob/fbaf1ad11b0c7fac09ba34baff2c256cffe0a148/web3/\_utils/events.py#L200 evt \= get\_event\_data(codec, abi, log) \# Note: This was originally yield, \# but deferring the timeout exception caused the throttle logic not to work all\_events.append(evt) return all\_events if \_\_name\_\_ \== "\_\_main\_\_": \# Simple demo that scans all the token transfers of RCC token (11k). \# The demo supports persistent state by using a JSON file. \# You will need an Ethereum node for this. \# Running this script will consume around 20k JSON-RPC calls. \# With locally running Geth, the script takes 10 minutes. \# The resulting JSON state file is 2.9 MB. import sys import json from web3.providers.rpc import HTTPProvider \# We use tqdm library to render a nice progress bar in the console \# https://pypi.org/project/tqdm/ from tqdm import tqdm \# RCC has around 11k Transfer events \# https://etherscan.io/token/0x9b6443b0fb9c241a7fdac375595cea13e6b7807a RCC\_ADDRESS \= "0x9b6443b0fb9c241a7fdac375595cea13e6b7807a" \# Reduced ERC-20 ABI, only Transfer event ABI \= """\[\ {\ "anonymous": false,\ "inputs": \[\ {\ "indexed": true,\ "name": "from",\ "type": "address"\ },\ {\ "indexed": true,\ "name": "to",\ "type": "address"\ },\ {\ "indexed": false,\ "name": "value",\ "type": "uint256"\ }\ \],\ "name": "Transfer",\ "type": "event"\ }\ \] """ class JSONifiedState(EventScannerState): """Store the state of scanned blocks and all events. All state is an in-memory dict. Simple load/store massive JSON on start up. """ def \_\_init\_\_(self): self.state \= None self.fname \= "test-state.json" \# How many second ago we saved the JSON file self.last\_save \= 0 def reset(self): """Create initial state of nothing scanned.""" self.state \= { "last\_scanned\_block": 0, "blocks": {}, } def restore(self): """Restore the last scan state from a file.""" try: self.state \= json.load(open(self.fname, "rt")) print(f"Restored the state, previously {self.state\['last\_scanned\_block'\]} blocks have been scanned") except (IOError, json.decoder.JSONDecodeError): print("State starting from scratch") self.reset() def save(self): """Save everything we have scanned so far in a file.""" with open(self.fname, "wt") as f: json.dump(self.state, f) self.last\_save \= time.time() # \# EventScannerState methods implemented below # def get\_last\_scanned\_block(self): """The number of the last block we have stored.""" return self.state\["last\_scanned\_block"\] def delete\_data(self, since\_block): """Remove potentially reorganised blocks from the scan data.""" for block\_num in range(since\_block, self.get\_last\_scanned\_block()): if block\_num in self.state\["blocks"\]: del self.state\["blocks"\]\[block\_num\] def start\_chunk(self, block\_number, chunk\_size): pass def end\_chunk(self, block\_number): """Save at the end of each block, so we can resume in the case of a crash or CTRL+C""" \# Next time the scanner is started we will resume from this block self.state\["last\_scanned\_block"\] \= block\_number \# Save the database file for every minute if time.time() \- self.last\_save \> 60: self.save() def process\_event(self, block\_when: datetime.datetime, event: AttributeDict) \-> str: """Record a ERC-20 transfer in our database.""" \# Events are keyed by their transaction hash and log index \# One transaction may contain multiple events \# and each one of those gets their own log index \# event\_name = event.event # "Transfer" log\_index \= event.logIndex \# Log index within the block \# transaction\_index = event.transactionIndex # Transaction index within the block txhash \= event.transactionHash.hex() \# Transaction hash block\_number \= event.blockNumber \# Convert ERC-20 Transfer event to our internal format args \= event\["args"\] transfer \= { "from": args\["from"\], "to": args.to, "value": args.value, "timestamp": block\_when.isoformat(), } \# Create empty dict as the block that contains all transactions by txhash if block\_number not in self.state\["blocks"\]: self.state\["blocks"\]\[block\_number\] \= {} block \= self.state\["blocks"\]\[block\_number\] if txhash not in block: \# We have not yet recorded any transfers in this transaction \# (One transaction may contain multiple events if executed by a smart contract). \# Create a tx entry that contains all events by a log index self.state\["blocks"\]\[block\_number\]\[txhash\] \= {} \# Record ERC-20 transfer in our database self.state\["blocks"\]\[block\_number\]\[txhash\]\[log\_index\] \= transfer \# Return a pointer that allows us to look up this event later if needed return f"{block\_number}\-{txhash}\-{log\_index}" 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") else: formatted\_time \= "no block time available" progress\_bar.set\_description(f"Current block: {current} ({formatted\_time}), blocks in a scan batch: {chunk\_size}, events processed in a batch {events\_count}") progress\_bar.update(chunk\_size) \# Run the scan result, total\_chunks\_scanned \= scanner.scan(start\_block, end\_block, progress\_callback\=\_update\_progress) state.save() duration \= time.time() \- start print(f"Scanned total {len(result)} Transfer events, in {duration} seconds, total {total\_chunks\_scanned} chunk scans performed") run() --- # Net API — web3.py 7.6.1 documentation * [](index.html) * Net API * [View page source](_sources/web3.net.rst.txt) * * * Net API[](#module-web3.net "Link to this heading") ==================================================== The `web3.net` object exposes methods to interact with the RPC APIs under the `net_` namespace. Properties[](#properties "Link to this heading") -------------------------------------------------- The following properties are available on the `web3.net` namespace. web3.net.listening()[](#web3.net.listening "Link to this definition") ..py:property:: > * Delegates to `net_listening` RPC method > > > Returns true if client is actively listening for network connections. > > \>>> web3.net.listening > True web3.net.peer\_count()[](#web3.net.peer_count "Link to this definition") ..py:property:: > * Delegates to `net_peerCount` RPC method > > > Returns number of peers currently connected to the client. > > \>>> web3.net.peer\_count > 1 web3.net.version()[](#web3.net.version "Link to this definition") ..py:property:: > * Delegates to `net_version` RPC Method > > > Returns the current network id. > > \>>> web3.net.version > '8996' --- # Tracing API — web3.py 7.6.1 documentation * [](index.html) * Tracing API * [View page source](_sources/web3.tracing.rst.txt) * * * Tracing API[](#module-web3.tracing "Link to this heading") ============================================================ The `web3.tracing` object exposes modules that enable you to interact with the JSON-RPC `trace_` endpoints supported by Erigon and Nethermind. The following methods are available on the `web3.tracing` namespace: web3.tracing.trace\_replay\_transaction()[](#web3.tracing.trace_replay_transaction "Link to this definition") web3.tracing.trace\_replay\_block\_transactions()[](#web3.tracing.trace_replay_block_transactions "Link to this definition") web3.tracing.trace\_filter()[](#web3.tracing.trace_filter "Link to this definition") web3.tracing.trace\_block()[](#web3.tracing.trace_block "Link to this definition") web3.tracing.trace\_transaction()[](#web3.tracing.trace_transaction "Link to this definition") web3.tracing.trace\_call()[](#web3.tracing.trace_call "Link to this definition") web3.tracing.trace\_raw\_transaction()[](#web3.tracing.trace_raw_transaction "Link to this definition") --- # Gas Price API — web3.py 7.6.1 documentation * [](index.html) * Gas Price API * [View page source](_sources/gas_price.rst.txt) * * * Gas Price API[](#gas-price-api "Link to this heading") ======================================================== Warning Gas price strategy is only supported for legacy transactions. The London fork introduced `maxFeePerGas` and `maxPriorityFeePerGas` transaction parameters which should be used over `gasPrice` whenever possible. For Ethereum (legacy) transactions, gas price is a delicate property. For this reason, Web3 includes an API for configuring it. The Gas Price API allows you to define Web3’s behaviour for populating the gas price. This is done using a “Gas Price Strategy” - a method which takes the Web3 object and a transaction dictionary and returns a gas price (denominated in wei). Retrieving gas price[](#retrieving-gas-price "Link to this heading") ---------------------------------------------------------------------- To retrieve the gas price using the selected strategy simply call [`generate_gas_price()`](web3.eth.html#web3.eth.Eth.generate_gas_price "web3.eth.Eth.generate_gas_price") \>>> web3.eth.generate\_gas\_price() 20000000000 Creating a gas price strategy[](#creating-a-gas-price-strategy "Link to this heading") ---------------------------------------------------------------------------------------- A gas price strategy is implemented as a python method with the following signature: def gas\_price\_strategy(web3, transaction\_params\=None): ... The method must return a positive integer representing the gas price in wei. To demonstrate, here is a rudimentary example of a gas price strategy that returns a higher gas price when the value of the transaction is higher than 1 Ether. from web3 import Web3 def value\_based\_gas\_price\_strategy(web3, transaction\_params): if transaction\_params\['value'\] \> Web3.to\_wei(1, 'ether'): return Web3.to\_wei(20, 'gwei') else: return Web3.to\_wei(5, 'gwei') Selecting the gas price strategy[](#selecting-the-gas-price-strategy "Link to this heading") ---------------------------------------------------------------------------------------------- The gas price strategy can be set by calling [`set_gas_price_strategy()`](web3.eth.html#web3.eth.Eth.set_gas_price_strategy "web3.eth.Eth.set_gas_price_strategy") . from web3 import Web3 def value\_based\_gas\_price\_strategy(web3, transaction\_params): ... w3 \= Web3(...) w3.eth.set\_gas\_price\_strategy(value\_based\_gas\_price\_strategy) Available gas price strategies[](#module-web3.gas_strategies.rpc "Link to this heading") ------------------------------------------------------------------------------------------ web3.gas\_strategies.rpc.rpc\_gas\_price\_strategy(_web3_, _transaction\_params\=None_)[](#web3.gas_strategies.rpc.rpc_gas_price_strategy "Link to this definition") Makes a call to the [JSON-RPC eth\_gasPrice method](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gasprice) which returns the gas price configured by the connected Ethereum node. web3.gas\_strategies.time\_based.construct\_time\_based\_gas\_price\_strategy(_max\_wait\_seconds_, _sample\_size\=120_, _probability\=98_, _weighted\=False_)[](#web3.gas_strategies.time_based.construct_time_based_gas_price_strategy "Link to this definition") Constructs a strategy which will compute a gas price such that the transaction will be mined within a number of seconds defined by `max_wait_seconds` with a probability defined by `probability`. The gas price is computed by sampling `sample_size` of the most recently mined blocks. If `weighted=True`, the block time will be weighted towards more recently mined blocks. * `max_wait_seconds` The desired maximum number of seconds the transaction should take to mine. * `sample_size` The number of recent blocks to sample * `probability` An integer representation of the desired probability that the transaction will be mined within `max_wait_seconds`. 0 means 0% and 100 means 100%. The following ready to use versions of this strategy are available. * `web3.gas_strategies.time_based.fast_gas_price_strategy`: Transaction mined within 60 seconds. * `web3.gas_strategies.time_based.medium_gas_price_strategy`: Transaction mined within 5 minutes. * `web3.gas_strategies.time_based.slow_gas_price_strategy`: Transaction mined within 1 hour. * `web3.gas_strategies.time_based.glacial_gas_price_strategy`: Transaction mined within 24 hours. Warning Due to the overhead of sampling the recent blocks it is recommended that a caching solution be used to reduce the amount of chain data that needs to be re-fetched for each request. from web3 import Web3 from web3.gas\_strategies.time\_based import medium\_gas\_price\_strategy w3 \= Web3(...) w3.eth.set\_gas\_price\_strategy(medium\_gas\_price\_strategy) w3.provider.cache\_allowed\_requests \= True --- # Code of Conduct — web3.py 7.6.1 documentation * [](index.html) * Code of Conduct * [View page source](_sources/code_of_conduct.rst.txt) * * * Code of Conduct[](#code-of-conduct "Link to this heading") ============================================================ Our Pledge[](#our-pledge "Link to this heading") -------------------------------------------------- In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards[](#our-standards "Link to this heading") -------------------------------------------------------- Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others’ private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting Our Responsibilities[](#our-responsibilities "Link to this heading") ---------------------------------------------------------------------- Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope[](#scope "Link to this heading") ---------------------------------------- This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement[](#enforcement "Link to this heading") ---------------------------------------------------- Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [snakecharmers@ethereum.org](mailto:snakecharmers%40ethereum.org) . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership. Attribution[](#attribution "Link to this heading") ---------------------------------------------------- This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org) , version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html) --- # Utils — web3.py 7.6.1 documentation * [](index.html) * Utils * [View page source](_sources/web3.utils.rst.txt) * * * Utils[](#module-web3.utils "Link to this heading") ==================================================== The `utils` module houses public utility functions and classes. ABI[](#module-web3.utils.abi "Link to this heading") ------------------------------------------------------ web3.utils.abi.get\_abi\_element\_info(_abi: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[ABIFunction | ABIConstructor | ABIFallback | ABIReceive | ABIEvent | ABIError\]_, _abi\_element\_identifier: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") | [Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.13)") \[FallbackFn\] | [Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.13)") \[ReceiveFn\]_, _\*args: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\ \] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") _, _abi\_codec: [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_, _\*\*kwargs: [Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.13)") \[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\ , [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\ \] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") _) → ABIElementInfo[](#web3.utils.abi.get_abi_element_info "Link to this definition") Information about the function ABI, selector and input arguments. Returns the ABI which matches the provided identifier, named arguments (`args`) and keyword args (`kwargs`). Parameters: * **abi** (ABI) – Contract ABI. * **abi\_element\_identifier** (ABIElementIdentifier) – Find an element ABI with matching identifier. * **args** (Optional\[Sequence\[Any\]\]) – Find a function ABI with matching args. * **abi\_codec** (Optional\[Any\]) – Codec used for encoding and decoding. Default with strict\_bytes\_type\_checking enabled. * **kwargs** (Optional\[Dict\[str, Any\]\]) – Find an element ABI with matching kwargs. Returns: Element information including the ABI, selector and args. Return type: ABIElementInfo \>>> from web3.utils.abi import get\_abi\_element\_info \>>> abi \= \[\ ... {\ ... "constant": False,\ ... "inputs": \[\ ... {"name": "a", "type": "uint256"},\ ... {"name": "b", "type": "uint256"},\ ... \],\ ... "name": "multiply",\ ... "outputs": \[{"name": "result", "type": "uint256"}\],\ ... "payable": False,\ ... "stateMutability": "nonpayable",\ ... "type": "function",\ ... }\ ... \] \>>> fn\_info \= get\_abi\_element\_info(abi, "multiply", \*\[7, 3\]) \>>> fn\_info\["abi"\] {'constant': False, 'inputs': \[{'name': 'a', 'type': 'uint256'}, {'name': 'b', 'type': 'uint256'}\], 'name': 'multiply', 'outputs': \[{'name': 'result', 'type': 'uint256'}\], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'function'} \>>> fn\_info\["selector"\] '0x165c4a16' \>>> fn\_info\["arguments"\] (7, 3) web3.utils.abi.get\_abi\_element(_abi: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[ABIFunction | ABIConstructor | ABIFallback | ABIReceive | ABIEvent | ABIError\]_, _abi\_element\_identifier: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") | [Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.13)") \[FallbackFn\] | [Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.13)") \[ReceiveFn\]_, _\*args: [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") _, _abi\_codec: [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_, _\*\*kwargs: [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") _) → ABIFunction | ABIConstructor | ABIFallback | ABIReceive | ABIEvent | ABIError[](#web3.utils.abi.get_abi_element "Link to this definition") Return the interface for an `ABIElement` from the `abi` that matches the provided identifier and arguments. `abi` may be a list of all ABI elements in a contract or a subset of elements. Passing only functions or events can be useful when names are not deterministic. For example, if names overlap between functions and events. The `ABIElementIdentifier` value may be a function name, signature, or a `FallbackFn` or `ReceiveFn`. When named arguments (`args`) and/or keyword args (`kwargs`) are provided, they are included in the search filters. The abi\_codec may be overridden if custom encoding and decoding is required. The default is used if no codec is provided. More details about customizations are in the [eth-abi Codecs Doc](https://eth-abi.readthedocs.io/en/latest/codecs.html) . Parameters: * **abi** (ABI) – Contract ABI. * **abi\_element\_identifier** (ABIElementIdentifier) – Find an element ABI with matching identifier. The identifier may be a function name, signature, or `FallbackFn` or `ReceiveFn`. A function signature is in the form `name(arg1Type,arg2Type,...)`. * **args** (Optional\[Sequence\[Any\]\]) – Find an element ABI with matching args. * **abi\_codec** (Optional\[Any\]) – Codec used for encoding and decoding. Default with strict\_bytes\_type\_checking enabled. * **kwargs** (Optional\[Dict\[str, Any\]\]) – Find an element ABI with matching kwargs. Returns: ABI element for the specific ABI element. Return type: ABIElement \>>> from web3.utils.abi import get\_abi\_element \>>> abi \= \[\ ... {\ ... "constant": False,\ ... "inputs": \[\ ... {"name": "a", "type": "uint256"},\ ... {"name": "b", "type": "uint256"},\ ... \],\ ... "name": "multiply",\ ... "outputs": \[{"name": "result", "type": "uint256"}\],\ ... "payable": False,\ ... "stateMutability": "nonpayable",\ ... "type": "function",\ ... }\ ... \] \>>> get\_abi\_element(abi, "multiply", \*\[7, 3\]) {'constant': False, 'inputs': \[{'name': 'a', 'type': 'uint256'}, {'name': 'b', 'type': 'uint256'}\], 'name': 'multiply', 'outputs': \[{'name': 'result', 'type': 'uint256'}\], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'function'} web3.utils.abi.check\_if\_arguments\_can\_be\_encoded(_abi\_element: ABIFunction | ABIConstructor | ABIFallback | ABIReceive | ABIEvent | ABIError_, _\*args: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\ \] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") _, _abi\_codec: [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_, _\*\*kwargs: [Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.13)") \[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\ , [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.13)")\ \] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") _) → [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)") [](#web3.utils.abi.check_if_arguments_can_be_encoded "Link to this definition") Check if the provided arguments can be encoded with the element ABI. Parameters: * **abi\_element** (ABIElement) – The ABI element. * **args** (Optional\[Sequence\[Any\]\]) – Positional arguments. * **abi\_codec** (Optional\[Any\]) – Codec used for encoding and decoding. Default with strict\_bytes\_type\_checking enabled. * **kwargs** (Optional\[Dict\[str, Any\]\]) – Keyword arguments. Returns: True if the arguments can be encoded, False otherwise. Return type: bool \>>> from web3.utils.abi import check\_if\_arguments\_can\_be\_encoded \>>> abi \= { ... "constant": False, ... "inputs": \[\ ... {"name": "a", "type": "uint256"},\ ... {"name": "b", "type": "uint256"},\ ... \], ... "name": "multiply", ... "outputs": \[{"name": "result", "type": "uint256"}\], ... "payable": False, ... "stateMutability": "nonpayable", ... "type": "function", ... } \>>> check\_if\_arguments\_can\_be\_encoded(abi, \*\[7, 3\], \*\*{}) True web3.utils.abi.get\_event\_abi(_abi: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[ABIFunction | ABIConstructor | ABIFallback | ABIReceive | ABIEvent | ABIError\]_, _event\_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _argument\_names: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\ \] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_) → ABIEvent[](#web3.utils.abi.get_event_abi "Link to this definition") Warning This function is deprecated. It is unable to distinguish between overloaded events. Use `get_abi_element` instead. Find the event interface with the given name and/or arguments. Parameters: * **abi** (ABI) – Contract ABI. * **event\_name** (str) – Find an event abi with matching event name. * **argument\_names** (Optional\[Sequence\[str\]\]) – Find an event abi with matching arguments. Returns: ABI for the event interface. Return type: ABIEvent \>>> from web3.utils import get\_event\_abi \>>> abi \= \[\ ... {"type": "function", "name": "myFunction", "inputs": \[\], "outputs": \[\]},\ ... {"type": "function", "name": "myFunction2", "inputs": \[\], "outputs": \[\]},\ ... {"type": "event", "name": "MyEvent", "inputs": \[\]}\ ... \] \>>> get\_event\_abi(abi, 'MyEvent') {'type': 'event', 'name': 'MyEvent', 'inputs': \[\]} web3.utils.abi.get\_event\_log\_topics(_event\_abi: ABIEvent_, _topics: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[[HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)")\ \]_) → [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[[HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)")\ \][](#web3.utils.abi.get_event_log_topics "Link to this definition") Return topics for an event ABI. Parameters: * **event\_abi** (ABIEvent) – Event ABI. * **topics** (Sequence\[HexBytes\]) – Transaction topics from a LogReceipt. Returns: Event topics for the event ABI. Return type: Sequence\[HexBytes\] \>>> from web3.utils import get\_event\_log\_topics \>>> abi \= { ... 'type': 'event', ... 'anonymous': False, ... 'name': 'MyEvent', ... 'inputs': \[\ ... {\ ... 'name': 's',\ ... 'type': 'uint256'\ ... }\ ... \] ... } \>>> keccak\_signature \= b'l+Ff\\xba\\x8d\\xa5\\xa9W\\x17b\\x1d\\x87\\x9aw\\xder\_=\\x81g\\t\\xb9\\xcb\\xe9\\xf0Y\\xb8\\xf8u\\xe2\\x84' \# noqa: E501 \>>> get\_event\_log\_topics(abi, \[keccak\_signature, '0x1', '0x2'\]) \['0x1', '0x2'\] web3.utils.abi.log\_topic\_to\_bytes(_log\_topic: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)") | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") | [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.13)") | HexStr | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _) → [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.13)") [](#web3.utils.abi.log_topic_to_bytes "Link to this definition") Return topic signature as bytes. Parameters: **log\_topic** (Union\[Primitives, HexStr, str\]) – Event topic from a LogReceipt. Returns: Topic signature as bytes. Return type: bytes \>>> from web3.utils import log\_topic\_to\_bytes \>>> log\_topic\_to\_bytes('0xa12fd1') b'\\xa1/\\xd1' Address[](#address "Link to this heading") -------------------------------------------- utils.get\_create\_address(_sender_, _nonce_)[](#web3.utils.abi.utils.get_create_address "Link to this definition") Return the checksummed contract address generated by using the `CREATE` opcode by a sender address with a given nonce. utils.get\_create2\_address(_sender_, _salt_, _init\_code_)[](#web3.utils.abi.utils.get_create2_address "Link to this definition") Return the checksummed contract address generated by using the `CREATE2` opcode by a sender address with a given salt and contract bytecode. See [EIP-1014](https://eips.ethereum.org/EIPS/eip-1014) . Caching[](#caching "Link to this heading") -------------------------------------------- _class_ utils.SimpleCache[](#web3.utils.abi.utils.SimpleCache "Link to this definition") The main cache class being used internally by web3.py. In some cases, it may prove useful to set your own cache size and pass in your own instance of this class where supported. Exception Handling[](#exception-handling "Link to this heading") ------------------------------------------------------------------ utils.handle\_offchain\_lookup(_offchain\_lookup\_payload_, _transaction_)[](#web3.utils.abi.utils.handle_offchain_lookup "Link to this definition") Handle `OffchainLookup` reverts on contract function calls manually. For an example, see [CCIP Read support for offchain lookup](web3.contract.html#ccip-read-example) within the examples section. utils.async\_handle\_offchain\_lookup(_offchain\_lookup\_payload_, _transaction_)[](#web3.utils.abi.utils.async_handle_offchain_lookup "Link to this definition") The async version of the `handle_offchain_lookup()` utility method described above. --- # Constants — web3.py 7.6.1 documentation * [](index.html) * Constants * [View page source](_sources/constants.rst.txt) * * * Constants[](#constants "Link to this heading") ================================================ The web3.constants module contains commonly used values. Strings[](#strings "Link to this heading") -------------------------------------------- #The Address Zero, which is 20 bytes (40 nibbles) of zero. web3.constants.ADDRESS\_ZERO #The hexadecimal version of Max uint256. web3.constants.MAX\_INT #The Hash Zero, which is 32 bytes (64 nibbles) of zero. web3.constants.HASH\_ZERO Int[](#int "Link to this heading") ------------------------------------ #The amount of Wei in one Ether web3.constants.WEI\_PER\_ETHER --- # gm — web3.py 7.6.1 documentation * [](#) * gm * [View page source](_sources/index.rst.txt) * * * gm[](#gm "Link to this heading") ================================== ![Banner Image](_images/banner-snek.jpg) **web3.py** is a Python library for interacting with Ethereum. It’s commonly found in [decentralized apps (dapps)](https://ethereum.org/dapps/) to help with sending transactions, interacting with smart contracts, reading block data, and a variety of other use cases. For project updates, follow [@EthereumPython](https://twitter.com/EthereumPython) and sign up for new post notifications on the [blog](https://snakecharmers.ethereum.org/) . Getting Started[](#getting-started "Link to this heading") ------------------------------------------------------------ Note 👋 Brand new to Ethereum? 0. Don’t travel alone! Join the Ethereum Python Community [Discord](https://discord.gg/GHryRvPB84) . 1. Read this [blog post series](https://snakecharmers.ethereum.org/a-developers-guide-to-ethereum-pt-1) for a gentle introduction to Ethereum blockchain concepts. 2. The [Overview](overview.html#overview) page will give you a quick idea of what else web3.py can do. 3. Try building a little something! * Ready to code? → [Quickstart](quickstart.html#quickstart) * Quick tour? → [Overview](overview.html#overview) * Synchronous help? → [Discord](https://discord.gg/GHryRvPB84) * Asynchronous help? → [StackExchange](https://ethereum.stackexchange.com/questions/tagged/web3.py) * Report a bug? → [Github](https://github.com/ethereum/web3.py/issues) * Want to help us? → [Contribute](contributing.html#contributing) * Looking for inspiration? → [Resources and Learning Material](resources.html#resources) Table of Contents[](#table-of-contents "Link to this heading") ---------------------------------------------------------------- Intro * [Quickstart](quickstart.html) * [Overview](overview.html) * [Release Notes](release_notes.html) Guides * [Providers](providers.html) * [Accounts](web3.eth.account.html) * [Transactions](transactions.html) * [Contracts](web3.contract.html) * [Events and Logs](filters.html) * [Middleware](middleware.html) * [Web3 Internals](internals.html) * [Ethereum Name Service (ENS)](ens_overview.html) * [Troubleshooting](troubleshooting.html) * [Migration Guide](migration.html) API * [Web3 API](web3.main.html) * [web3.eth API](web3.eth.html) * [Beacon API](web3.beacon.html) * [Net API](web3.net.html) * [Geth API](web3.geth.html) * [Tracing API](web3.tracing.html) * [Utils](web3.utils.html) * [Gas Price API](gas_price.html) * [ENS API](ens.html) * [Constants](constants.html) Community * [Resources and Learning Material](resources.html) * [Contributing](contributing.html) * [Code of Conduct](code_of_conduct.html) Indices and tables[](#indices-and-tables "Link to this heading") ------------------------------------------------------------------ * [Index](genindex.html) * [Module Index](py-modindex.html) * [Search Page](search.html) --- # Unknown .. \_overview: Overview ======== The purpose of this page is to give you a sense of everything web3.py can do and to serve as a quick reference guide. You'll find a summary of each feature with links to learn more. Configuration ------------- After installing web3.py (via \`\`pip install web3\`\`), you'll need to configure a provider endpoint and any middleware you want to use beyond the defaults. Providers ~~~~~~~~~ :doc:\`providers\` are how web3.py connects to a blockchain. The library comes with the following built-in providers: - :class:\`~web3.providers.rpc.HTTPProvider\` for connecting to http and https based JSON-RPC servers. - :class:\`~web3.providers.ipc.IPCProvider\` for connecting to ipc socket based JSON-RPC servers. - :class:\`~web3.providers.legacy\_websocket.LegacyWebSocketProvider\` (deprecated) for connecting to websocket based JSON-RPC servers. - :class:\`~web3.providers.async\_rpc.AsyncHTTPProvider\` for connecting to http and https based JSON-RPC servers asynchronously. - :class:\`~web3.providers.persistent.AsyncIPCProvider\` for connecting to ipc socket based JSON-RPC servers asynchronously via a persistent connection. - :class:\`~web3.providers.persistent.WebSocketProvider\` for connecting to websocket based JSON-RPC servers asynchronously via a persistent connection. Examples \`\`\`\`\`\`\`\` .. code-block:: 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 For more context, see the :doc:\`providers\` documentation. Middleware ~~~~~~~~~~ Your web3.py instance may be further configured via :doc:\`middleware\`. web3.py middleware is described using an onion metaphor, where each layer of middleware may affect both the incoming request and outgoing response from your provider. The documentation includes a :ref:\`visualization \` of this idea. Several middleware are :ref:\`included by default \`. You may add to (:meth:\`add \`, :meth:\`inject \`, :meth:\`replace \`) or disable (:meth:\`remove \`, :meth:\`clear \`) any of these middleware. Accounts and Private Keys ------------------------- Private keys are required to approve any transaction made on your behalf. The manner in which your key is secured will determine how you create and send transactions in web3.py. A local node, like \`Geth \`\_, may manage your keys for you. You can reference those keys using the :attr:\`web3.eth.accounts \` property. A hosted node, like \`Infura \`\_, will have no knowledge of your keys. In this case, you'll need to have your private key available locally for signing transactions. Full documentation on the distinction between keys can be found :ref:\`here \`. The separate guide to :doc:\`transactions\` may also help clarify how to manage keys. Base API -------- The :ref:\`Web3 \` class includes a number of convenient utility functions: Encoding and Decoding Helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :meth:\`Web3.is\_encodable() \` - :meth:\`Web3.to\_bytes() \` - :meth:\`Web3.to\_hex() \` - :meth:\`Web3.to\_int() \` - :meth:\`Web3.to\_json() \` - :meth:\`Web3.to\_text() \` Address Helpers ~~~~~~~~~~~~~~~ - :meth:\`Web3.is\_address() \` - :meth:\`Web3.is\_checksum\_address() \` - :meth:\`Web3.to\_checksum\_address() \` Currency Conversions ~~~~~~~~~~~~~~~~~~~~ - :meth:\`Web3.from\_wei() \` - :meth:\`Web3.to\_wei() \` Cryptographic Hashing ~~~~~~~~~~~~~~~~~~~~~ - :meth:\`Web3.keccak() \` - :meth:\`Web3.solidity\_keccak() \` web3.eth API ------------ The most commonly used APIs for interacting with Ethereum can be found under the :ref:\`web3-eth\` namespace. Fetching Data ~~~~~~~~~~~~~ Viewing account balances (:meth:\`get\_balance \`), transactions (:meth:\`get\_transaction \`), and block data (:meth:\`get\_block \`) are some of the most common starting points in web3.py. API \`\`\` - :meth:\`web3.eth.get\_balance() \` - :meth:\`web3.eth.get\_block() \` - :meth:\`web3.eth.get\_block\_transaction\_count() \` - :meth:\`web3.eth.get\_code() \` - :meth:\`web3.eth.get\_proof() \` - :meth:\`web3.eth.get\_storage\_at() \` - :meth:\`web3.eth.get\_transaction() \` - :meth:\`web3.eth.get\_transaction\_by\_block() \` - :meth:\`web3.eth.get\_transaction\_count() \` - :meth:\`web3.eth.get\_uncle\_by\_block() \` - :meth:\`web3.eth.get\_uncle\_count() \` Sending Transactions ~~~~~~~~~~~~~~~~~~~~ The most common use cases will be satisfied with :meth:\`send\_transaction \` or the combination of :meth:\`sign\_transaction \` and :meth:\`send\_raw\_transaction \`. For more context, see the full guide to :doc:\`transactions\`. .. note:: If interacting with a smart contract, a dedicated API exists. See the next section, :ref:\`Contracts \`. API \`\`\` - :meth:\`web3.eth.send\_transaction() \` - :meth:\`web3.eth.sign\_transaction() \` - :meth:\`web3.eth.send\_raw\_transaction() \` - :meth:\`web3.eth.replace\_transaction() \` - :meth:\`web3.eth.modify\_transaction() \` - :meth:\`web3.eth.wait\_for\_transaction\_receipt() \` - :meth:\`web3.eth.get\_transaction\_receipt() \` - :meth:\`web3.eth.sign() \` - :meth:\`web3.eth.sign\_typed\_data() \` - :meth:\`web3.eth.estimate\_gas() \` - :meth:\`web3.eth.generate\_gas\_price() \` - :meth:\`web3.eth.set\_gas\_price\_strategy() \` .. \_overview\_contracts: Contracts --------- web3.py can help you deploy, read from, or execute functions on a deployed contract. Deployment requires that the contract already be compiled, with its bytecode and ABI available. This compilation step can be done within \`Remix \`\_ or one of the many contract development frameworks, such as \`Ape \`\_. Once the contract object is instantiated, calling \`\`transact\`\` on the :meth:\`constructor \` method will deploy an instance of the contract: .. code-block:: python >>> ExampleContract = w3.eth.contract(abi=abi, bytecode=bytecode) >>> tx\_hash = ExampleContract.constructor().transact() >>> tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) >>> tx\_receipt.contractAddress '0x8a22225eD7eD460D7ee3842bce2402B9deaD23D3' Once a deployed contract is loaded into a Contract object, the functions of that contract are available on the \`\`functions\`\` namespace: .. code-block:: python >>> deployed\_contract = w3.eth.contract(address=tx\_receipt.contractAddress, abi=abi) >>> deployed\_contract.functions.myFunction(42).transact() If you want to read data from a contract (or see the result of transaction locally, without executing it on the network), you can use the :meth:\`ContractFunction.call \` method, or the more concise :attr:\`ContractCaller \` syntax: .. code-block:: python # Using ContractFunction.call >>> deployed\_contract.functions.getMyValue().call() 42 # Using ContractCaller >>> deployed\_contract.caller().getMyValue() 42 For more, see the full :ref:\`Contracts\` documentation. API ~~~ - :meth:\`web3.eth.contract() \` - :attr:\`Contract.address \` - :attr:\`Contract.abi \` - :attr:\`Contract.bytecode \` - :attr:\`Contract.bytecode\_runtime \` - :attr:\`Contract.functions \` - :attr:\`Contract.events \` - :attr:\`Contract.fallback \` - :meth:\`Contract.constructor() \` - :meth:\`Contract.encode\_abi() \` - :attr:\`web3.contract.ContractFunction \` - :attr:\`web3.contract.ContractEvents \` Events, Logs, and Filters ------------------------- If you want to react to new blocks being mined or specific events being emitted by a contract, you can leverage \`\`get\_logs\`\`, subscriptions, or filters. See the :doc:\`filters\` guide for more information. API ~~~ - :meth:\`web3.eth.subscribe() \` - :meth:\`web3.eth.filter() \` - :meth:\`web3.eth.get\_filter\_changes() \` - :meth:\`web3.eth.get\_filter\_logs() \` - :meth:\`web3.eth.uninstall\_filter() \` - :meth:\`web3.eth.get\_logs() \` - :meth:\`Contract.events.your\_event\_name.create\_filter() \` - :meth:\`Contract.events.your\_event\_name.build\_filter() \` - :meth:\`Filter.get\_new\_entries() \` - :meth:\`Filter.get\_all\_entries() \` - :meth:\`Filter.format\_entry() \` - :meth:\`Filter.is\_valid\_entry() \` Net API ------- Some basic network properties are available on the \`\`web3.net\`\` object: - :attr:\`web3.net.listening\` - :attr:\`web3.net.peer\_count\` - :attr:\`web3.net.version\` ENS --- \`Ethereum Name Service (ENS) \`\_ provides the infrastructure for human-readable addresses. If an address is registered with the ENS registry, the domain name can be used in place of the address itself. For example, the registered domain name \`\`ethereum.eth\`\` will resolve to the address \`\`0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe\`\`. web3.py has support for ENS, documented :ref:\`here \`. --- # Unknown Transactions ============ There are a handful of ways to interact with transactions in web3.py. See the :ref:\`Web3.eth module \` for a full list of transaction-related methods. Note that you may also :ref:\`batch requests \` that read transaction data, but not send new transactions in a batch request. The rest of this guide covers the decision tree for how to send a transaction. .. note:: Prefer to view this code in a Jupyter Notebook? View the repo \`here \`\_. There are two methods for sending transactions using web3.py: :meth:\`~web3.eth.Eth.send\_transaction\` and :meth:\`~web3.eth.Eth.send\_raw\_transaction\`. A brief guide: #. Want to sign a transaction offline or send pre-signed transactions? \* use :meth:\`sign\_transaction \` + :meth:\`~web3.eth.Eth.send\_raw\_transaction\` #. Are you primarily using the same account for all transactions and would you prefer to save a few lines of code? \* configure the \`\`build\`\` method for :class:\`~web3.middleware.SignAndSendRawMiddlewareBuilder\`, then \* use :meth:\`~web3.eth.Eth.send\_transaction\` #. Otherwise: \* load account via eth-account (:meth:\`w3.eth.account.from\_key(pk) \`), then \* use :meth:\`~web3.eth.Eth.send\_transaction\` Interacting with or deploying a contract? \* Option 1: :meth:\`~web3.contract.ContractFunction.transact\` uses :meth:\`~web3.eth.Eth.send\_transaction\` under the hood \* Option 2: :meth:\`~web3.contract.ContractFunction.build\_transaction\` + :meth:\`sign\_transaction \` + :meth:\`~web3.eth.Eth.send\_raw\_transaction\` An example for each can be found below. Chapter 0: \`\`w3.eth.send\_transaction\`\` with \`\`eth-tester\`\` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Many tutorials use \`\`eth-tester\`\` (via EthereumTesterProvider) for convenience and speed of conveying ideas/building a proof of concept. Transactions sent by test accounts are auto-signed. .. code-block:: python from web3 import Web3, EthereumTesterProvider w3 = Web3(EthereumTesterProvider()) # eth-tester populates accounts with test ether: acct1 = w3.eth.accounts\[0\] some\_address = "0x0000000000000000000000000000000000000000" # when using one of its generated test accounts, # eth-tester signs the tx (under the hood) before sending: tx\_hash = w3.eth.send\_transaction({ "from": acct1, "to": some\_address, "value": 123123123123123 }) tx = w3.eth.get\_transaction(tx\_hash) assert tx\["from"\] == acct1 Chapter 1: \`\`w3.eth.send\_transaction\`\` + signer middleware ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The :meth:\`~web3.eth.Eth.send\_transaction\` method is convenient and to-the-point. If you want to continue using the pattern after graduating from \`\`eth-tester\`\`, you can utilize web3.py middleware to sign transactions from a particular account: .. code-block:: python from web3.middleware import SignAndSendRawMiddlewareBuilder import os # Note: Never commit your key in your code! Use env variables instead: pk = os.environ.get('PRIVATE\_KEY') # Instantiate an Account object from your key: acct2 = w3.eth.account.from\_key(pk) # For the sake of this example, fund the new account: w3.eth.send\_transaction({ "from": acct1, "value": w3.to\_wei(3, 'ether'), "to": acct2.address }) # Add acct2 as auto-signer: w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(acct2), layer=0) # pk also works: w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(pk), layer=0) # Transactions from \`acct2\` will then be signed, under the hood, in the middleware: tx\_hash = w3.eth.send\_transaction({ "from": acct2.address, "value": 3333333333, "to": some\_address }) tx = w3.eth.get\_transaction(tx\_hash) assert tx\["from"\] == acct2.address # Optionally, you can set a default signer as well: # w3.eth.default\_account = acct2.address # Then, if you omit a "from" key, acct2 will be used. Chapter 2: \`\`w3.eth.send\_raw\_transaction\`\` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if you don't opt for the middleware, you'll need to: - build each transaction, - :meth:\`sign\_transaction \`, and - then use :meth:\`~web3.eth.Eth.send\_raw\_transaction\`. .. code-block:: python # 1. Build a new tx transaction = { 'from': acct2.address, 'to': some\_address, 'value': 1000000000, 'nonce': w3.eth.get\_transaction\_count(acct2.address), 'gas': 200000, 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, } # 2. Sign tx with a private key signed = w3.eth.account.sign\_transaction(transaction, pk) # 3. Send the signed transaction tx\_hash = w3.eth.send\_raw\_transaction(signed.raw\_transaction) tx = w3.eth.get\_transaction(tx\_hash) assert tx\["from"\] == acct2.address Chapter 3: Contract transactions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The same concepts apply for contract interactions, at least under the hood. Executing a function on a smart contract requires sending a transaction, which is typically done in one of two ways: - executing the :meth:\`~web3.contract.ContractFunction.transact\` function, or - :meth:\`~web3.contract.ContractFunction.build\_transaction\`, then signing and sending the raw transaction. .. code-block:: python ######################################### #### SMOL CONTRACT FOR THIS EXAMPLE: #### ######################################### # // SPDX-License-Identifier: MIT # pragma solidity 0.8.17; # # contract Billboard { # string public message; # # constructor(string memory \_message) { # message = \_message; # } # # function writeBillboard(string memory \_message) public { # message = \_message; # } # } # 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" --- # Unknown .. \_web3\_base: Web3 API ======== .. contents:: :local: .. py:module:: web3 .. py:currentmodule:: web3 .. py:class:: Web3(provider) Each \`\`Web3\`\` instance exposes the following APIs. Providers ~~~~~~~~~ .. py:attribute:: Web3.HTTPProvider Convenience API to access :py:class:\`web3.providers.rpc.HTTPProvider\` .. py:attribute:: Web3.IPCProvider Convenience API to access :py:class:\`web3.providers.ipc.IPCProvider\` Attributes ~~~~~~~~~~ .. py:attribute:: Web3.api Returns the current Web3 version. .. code-block:: python >>> web3.api "4.7.0" .. py:attribute:: Web3.client\_version \* Delegates to \`\`web3\_clientVersion\`\` RPC Method Returns the current client version. .. code-block:: python >>> web3.client\_version 'Geth/v1.4.11-stable-fed692f6/darwin/go1.7' .. \_batch\_requests: Batch Requests ~~~~~~~~~~~~~~ .. py:method:: Web3.batch\_requests() The JSON-RPC API allows for batch requests, meaning you can send a single request that contains an array of request objects. Generally, this may be useful when you want to limit the number of requests you send to a node. You can choose to build a batch of requests within or outside of a context manager: .. code-block:: python with w3.batch\_requests() as batch: batch.add(w3.eth.get\_block(6)) batch.add(w3.eth.get\_block(4)) batch.add(w3.eth.get\_block(2)) responses = batch.execute() assert len(responses) == 3 Using the batch object directly: .. code-block:: python batch = w3.batch\_requests() batch.add(w3.eth.get\_block(1)) batch.add(w3.eth.get\_block(2)) responses = batch.execute() assert len(responses) == 2 Contract interactions can be included in batch requests by omitting the \`\`call()\`\` method: .. code-block:: python batch.add(math\_contract.functions.multiply7(0)) Additionally, if you need to make multiple calls of the same function, you can add a mapping of the function to its arguments: .. code-block:: python batch = w3.batch\_requests() batch.add\_mapping( { math\_contract.functions.multiply7: \[1, 2\], w3.eth.get\_block: \[3, 4\], } ) responses = batch.execute() assert len(responses) == 4 The \`\`execute\`\` method returns a list of responses in the order they were included in the batch. If you need to abandon or rebuild a batch request, utilize the \`\`clear\`\` method: .. code-block:: python batch = w3.batch\_requests() batch.add(w3.eth.get\_block(1)) batch.add(w3.eth.get\_block(2)) assert len(batch.\_requests\_info) == 2 batch.clear() assert batch.\_requests\_info == \[\] .. note:: Only read-only operations that exist within modules on the \`\`Web3\`\` class (e.g. \`\`w3.eth\`\`, \`\`w3.net\`\`) are supported by \`\`batch\_requests\`\`. Unsupported methods include: - :meth:\`subscribe \` - :meth:\`unsubscribe \` - :meth:\`send\_raw\_transaction \` - :meth:\`send\_transaction \` - :meth:\`sign\_transaction \` - :meth:\`sign \` - :meth:\`sign\_typed\_data \` - \`\`w3.provider.make\_request()\`\`. Async Batch Requests \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` If using one of the asynchronous providers, you'll need to make use of the \`\`async\_execute\`\` method and the \`\`async\`\` and \`\`await\`\` keywords as appropriate. .. note:: If performance is a concern, consider using \`\`asyncio.gather()\`\` with single concurrent requests instead of an asynchronous batch request. It will generally be the faster option due to the overhead of batching. .. code-block:: python # context manager: async with w3.batch\_requests() as batch: batch.add(w3.eth.get\_block(6)) batch.add(w3.eth.get\_block(4)) batch.add(w3.eth.get\_block(2)) responses = await batch.async\_execute() assert len(responses) == 3 # object: batch = w3.batch\_requests() batch.add(w3.eth.get\_block(1)) batch.add(w3.eth.get\_block(2)) responses = await batch.async\_execute() assert len(responses) == 2 .. \_overview\_type\_conversions: Encoding and Decoding Helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:method:: Web3.to\_hex(primitive=None, hexstr=None, text=None) Takes a variety of inputs and returns it in its hexadecimal representation. It follows the rules for converting to hex in the \`JSON-RPC spec\`\_ .. code-block:: python >>> Web3.to\_hex(0) '0x0' >>> Web3.to\_hex(1) '0x1' >>> Web3.to\_hex(0x0) '0x0' >>> Web3.to\_hex(0x000F) '0xf' >>> Web3.to\_hex(b'') '0x' >>> Web3.to\_hex(b'\\x00\\x0F') '0x000f' >>> Web3.to\_hex(False) '0x0' >>> Web3.to\_hex(True) '0x1' >>> Web3.to\_hex(hexstr='0x000F') '0x000f' >>> Web3.to\_hex(hexstr='000F') '0x000f' >>> Web3.to\_hex(text='') '0x' >>> Web3.to\_hex(text='cowmö') '0x636f776dc3b6' .. \_JSON-RPC spec: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding .. py:method:: Web3.to\_text(primitive=None, hexstr=None, text=None) Takes a variety of inputs and returns its string equivalent. Text gets decoded as UTF-8. .. code-block:: python >>> Web3.to\_text(0x636f776dc3b6) 'cowmö' >>> Web3.to\_text(b'cowm\\xc3\\xb6') 'cowmö' >>> Web3.to\_text(hexstr='0x636f776dc3b6') 'cowmö' >>> Web3.to\_text(hexstr='636f776dc3b6') 'cowmö' >>> Web3.to\_text(text='cowmö') 'cowmö' .. py:method:: Web3.to\_bytes(primitive=None, hexstr=None, text=None) Takes a variety of inputs and returns its bytes equivalent. Text gets encoded as UTF-8. .. code-block:: python >>> Web3.to\_bytes(0) b'\\x00' >>> Web3.to\_bytes(0x000F) b'\\x0f' >>> Web3.to\_bytes(b'') b'' >>> Web3.to\_bytes(b'\\x00\\x0F') b'\\x00\\x0f' >>> Web3.to\_bytes(False) b'\\x00' >>> Web3.to\_bytes(True) b'\\x01' >>> Web3.to\_bytes(hexstr='0x000F') b'\\x00\\x0f' >>> Web3.to\_bytes(hexstr='000F') b'\\x00\\x0f' >>> Web3.to\_bytes(text='') b'' >>> Web3.to\_bytes(text='cowmö') b'cowm\\xc3\\xb6' .. py:method:: Web3.to\_int(primitive=None, hexstr=None, text=None) Takes a variety of inputs and returns its integer equivalent. .. code-block:: python >>> Web3.to\_int(0) 0 >>> Web3.to\_int(0x000F) 15 >>> Web3.to\_int(b'\\x00\\x0F') 15 >>> Web3.to\_int(False) 0 >>> Web3.to\_int(True) 1 >>> Web3.to\_int(hexstr='0x000F') 15 >>> Web3.to\_int(hexstr='000F') 15 .. py:method:: Web3.to\_json(obj) Takes a variety of inputs and returns its JSON equivalent. .. code-block:: python >>> Web3.to\_json(3) '3' >>> Web3.to\_json({'one': 1}) '{"one": 1}' .. \_overview\_currency\_conversions: Currency Conversions ~~~~~~~~~~~~~~~~~~~~~ .. py:method:: Web3.to\_wei(value, currency) Returns the value in the denomination specified by the \`\`currency\`\` argument converted to wei. .. code-block:: python >>> Web3.to\_wei(1, 'ether') 1000000000000000000 .. py:method:: Web3.from\_wei(value, currency) Returns the value in wei converted to the given currency. The value is returned as a \`\`Decimal\`\` to ensure precision down to the wei. .. code-block:: python >>> Web3.from\_wei(1000000000000000000, 'ether') Decimal('1') .. \_overview\_addresses: Addresses ~~~~~~~~~ .. py:method:: Web3.is\_address(value) Returns \`\`True\`\` if the value is one of the recognized address formats. \* Allows for both \`\`0x\`\` prefixed and non-prefixed values. \* If the address contains mixed upper and lower cased characters this function also checks if the address checksum is valid according to \`EIP55\`\_ .. code-block:: python >>> Web3.is\_address('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') True .. py:method:: Web3.is\_checksum\_address(value) Returns \`\`True\`\` if the value is a valid \`EIP55\`\_ checksummed address .. code-block:: python >>> Web3.is\_checksum\_address('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') True >>> Web3.is\_checksum\_address('0xd3cda913deb6f67967b99d67acdfa1712c293601') False .. py:method:: Web3.to\_checksum\_address(value) Returns the given address with an \`EIP55\`\_ checksum. .. code-block:: python >>> Web3.to\_checksum\_address('0xd3cda913deb6f67967b99d67acdfa1712c293601') '0xd3CdA913deB6f67967B99D67aCDFa1712C293601' .. \_EIP55: https://github.com/ethereum/EIPs/issues/55 .. \_overview\_hashing: Cryptographic Hashing ~~~~~~~~~~~~~~~~~~~~~ .. py:classmethod:: Web3.keccak(primitive=None, hexstr=None, text=None) Returns the Keccak-256 of the given value. Text is encoded to UTF-8 before computing the hash, just like Solidity. Any of the following are valid and equivalent: .. code-block:: python >>> Web3.keccak(0x747874) >>> Web3.keccak(b'\\x74\\x78\\x74') >>> Web3.keccak(hexstr='0x747874') >>> Web3.keccak(hexstr='747874') >>> Web3.keccak(text='txt') HexBytes('0xd7278090a36507640ea6b7a0034b69b0d240766fa3f98e3722be93c613b29d2e') .. py:classmethod:: Web3.solidity\_keccak(abi\_types, value) Returns the Keccak-256 as it would be computed by the solidity \`\`keccak\`\` function on a \*packed\* ABI encoding of the \`\`value\`\` list contents. The \`\`abi\_types\`\` argument should be a list of solidity type strings which correspond to each of the provided values. .. code-block:: python >>> Web3.solidity\_keccak(\['bool'\], \[True\]) HexBytes("0x5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2") >>> Web3.solidity\_keccak(\['uint8', 'uint8', 'uint8'\], \[97, 98, 99\]) HexBytes("0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45") >>> Web3.solidity\_keccak(\['uint8\[\]'\], \[\[97, 98, 99\]\]) HexBytes("0x233002c671295529bcc50b76a2ef2b0de2dac2d93945fca745255de1a9e4017e") >>> Web3.solidity\_keccak(\['address'\], \["0x49EdDD3769c0712032808D86597B84ac5c2F5614"\]) HexBytes("0x2ff37b5607484cd4eecf6d13292e22bd6e5401eaffcc07e279583bc742c68882") >>> Web3.solidity\_keccak(\['address'\], \["ethereumfoundation.eth"\]) HexBytes("0x913c99ea930c78868f1535d34cd705ab85929b2eaaf70fcd09677ecd6e5d75e9") Comparable solidity usage: .. code-block:: solidity bytes32 data1 = keccak256(abi.encodePacked(true)); assert(data1 == hex"5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2"); bytes32 data2 = keccak256(abi.encodePacked(uint8(97), uint8(98), uint8(99))); assert(data2 == hex"4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45"); Check Encodability ~~~~~~~~~~~~~~~~~~~~ .. py:method:: w3.is\_encodable(\_type, value) Returns \`\`True\`\` if a value can be encoded as the given type. Otherwise returns \`\`False\`\`. .. code-block:: python >>> from web3.auto.gethdev import w3 >>> w3.is\_encodable('bytes2', b'12') True >>> w3.is\_encodable('bytes2', '0x1234') True >>> w3.is\_encodable('bytes2', '1234') # not 0x-prefixed, no assumptions will be made False >>> w3.is\_encodable('bytes2', b'1') # does not match specified bytes size False >>> w3.is\_encodable('bytes2', b'123') # does not match specified bytes size False .. py:attribute:: w3.strict\_bytes\_type\_checking Disable the stricter bytes type checking that is loaded by default. For more examples, see :ref:\`disable-strict-byte-check\` .. doctest:: >>> from web3.auto.gethdev import w3 >>> w3.is\_encodable('bytes2', b'12') True >>> # not of exact size bytes2 >>> w3.is\_encodable('bytes2', b'1') False >>> w3.strict\_bytes\_type\_checking = False >>> # zero-padded, so encoded to: b'1\\x00' >>> w3.is\_encodable('bytes2', b'1') True >>> # re-enable it >>> w3.strict\_bytes\_type\_checking = True >>> w3.is\_encodable('bytes2', b'1') False RPC API Modules ~~~~~~~~~~~~~~~ Each \`\`Web3\`\` instance also exposes these namespaced API modules. .. py:attribute:: Web3.eth See :doc:\`./web3.eth\` .. py:attribute:: Web3.geth See :doc:\`./web3.geth\` These internal modules inherit from the \`\`web3.module.Module\`\` class which give them some configurations internal to the web3.py library. Custom Methods ~~~~~~~~~~~~~~ You may add or overwrite methods within any module using the \`\`attach\_methods\`\` function. To create a property instead, set \`\`is\_property\`\` to \`\`True\`\`. .. code-block:: python >>> w3.eth.attach\_methods({ ... 'example\_method': Method( ... 'eth\_example', ... mungers=\[...\], ... request\_formatters=\[...\], ... result\_formatters=\[...\], ... is\_property=False, ... ), ... }) >>> w3.eth.example\_method() External Modules ~~~~~~~~~~~~~~~~ External modules can be used to introduce custom or third-party APIs to your \`\`Web3\`\` instance. External modules are simply classes whose methods and properties can be made available within the \`\`Web3\`\` instance. Optionally, the external module may make use of the parent \`\`Web3\`\` instance by accepting it as the first argument within the \`\`\_\_init\_\_\`\` function: .. code-block:: python >>> class ExampleModule: ... def \_\_init\_\_(self, w3): ... self.w3 = w3 ... ... def print\_balance\_of\_shaq(self): ... print(self.w3.eth.get\_balance('shaq.eth')) .. warning:: Given the flexibility of external modules, use caution and only import modules from trusted third parties and open source code you've vetted! Configuring external modules can occur either at instantiation of the \`\`Web3\`\` instance or by making use of the \`\`attach\_modules()\`\` method. To instantiate the \`\`Web3\`\` instance with external modules use the \`\`external\_modules\`\` keyword argument: .. code-block:: python >>> from web3 import Web3, HTTPProvider >>> from external\_module\_library import ( ... ModuleClass1, ... ModuleClass2, ... ModuleClass3, ... ModuleClass4, ... ModuleClass5, ... ) >>> w3 = Web3( ... HTTPProvider(provider\_uri), ... external\_modules={ ... 'module1': ModuleClass1, ... 'module2': (ModuleClass2, { ... 'submodule1': ModuleClass3, ... 'submodule2': (ModuleClass4, { ... 'submodule2a': ModuleClass5, # submodule children may be nested further if necessary ... }) ... }) ... } ... ) # \`return\_zero\`, in this case, is an example attribute of the \`ModuleClass1\` object >>> w3.module1.return\_zero() 0 >>> w3.module2.submodule1.return\_one() 1 >>> w3.module2.submodule2.submodule2a.return\_two() 2 .. py:method:: w3.attach\_modules(modules) The \`\`attach\_modules()\`\` method can be used to attach external modules after the \`\`Web3\`\` instance has been instantiated. Modules are attached via a \`dict\` with module names as the keys. The values can either be the module classes themselves, if there are no submodules, or two-item tuples with the module class as the 0th index and a similarly built \`dict\` containing the submodule information as the 1st index. This pattern may be repeated as necessary. .. code-block:: python >>> from web3 import Web3, HTTPProvider >>> from external\_module\_library import ( ... ModuleClass1, ... ModuleClass2, ... ModuleClass3, ... ModuleClass4, ... ModuleClass5, ... ) >>> w3 = Web3(HTTPProvider(provider\_uri)) >>> w3.attach\_modules({ ... 'module1': ModuleClass1, # the module class itself may be used for a single module with no submodules ... 'module2': (ModuleClass2, { # a tuple with module class and corresponding submodule dict may be used for modules with submodules ... 'submodule1': ModuleClass3, ... 'submodule2': (ModuleClass4, { # this pattern may be repeated as necessary ... 'submodule2a': ModuleClass5, ... }) ... }) ... }) >>> w3.module1.return\_zero() 0 >>> w3.module2.submodule1.return\_one() 1 >>> w3.module2.submodule2.submodule2a.return\_two() 2 --- # Unknown .. \_providers: Providers ========= Using Ethereum requires access to an Ethereum node. If you have the means, you're encouraged to \`run your own node\`\_. (Note that you do not need to stake ether to run a node.) If you're unable to run your own node, you can use a \`remote node\`\_. Once you have access to a node, you can connect to it using a \*\*provider\*\*. Providers generate \`JSON-RPC\`\_ requests and return the response. This is done by submitting the request to an HTTP, WebSocket, or IPC socket-based server. .. note:: web3.py supports one provider per instance. If you have an advanced use case that requires multiple providers, create and configure a new web3 instance per connection. If you are already happily connected to your Ethereum node, then you can skip the rest of this providers section. .. \_run your own node: https://ethereum.org/en/developers/docs/nodes-and-clients/run-a-node/ .. \_remote node: https://ethereum.org/en/developers/docs/nodes-and-clients/nodes-as-a-service/ .. \_JSON-RPC: https://ethereum.org/en/developers/docs/apis/json-rpc/ .. \_choosing\_provider: Choosing a Provider ------------------- Most nodes have a variety of ways to connect to them. Most commonly: 1. IPC (uses local filesystem: fastest and most secure) 2. WebSocket (works remotely, faster than HTTP) 3. HTTP (more nodes support it) If you're not sure how to decide, choose this way: - If you have the option of running web3.py on the same machine as the node, choose IPC. - If you must connect to a node on a different computer, use WebSocket. - If your node does not support WebSocket, use HTTP. Once you have decided how to connect, you'll select and configure the appropriate provider class: - :class:\`~web3.providers.rpc.HTTPProvider\` - :class:\`~web3.providers.ipc.IPCProvider\` - :class:\`~web3.providers.async\_rpc.AsyncHTTPProvider\` - :class:\`~web3.providers.persistent.AsyncIPCProvider\` (Persistent Connection Provider) - :class:\`~web3.providers.persistent.WebSocketProvider\` (Persistent Connection Provider) Each provider above links to the documentation on how to properly initialize that provider. Once you have reviewed the relevant documentation for the provider of your choice, you are ready to :ref:\`get started with web3.py\`. Provider via Environment Variable ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Alternatively, you can set the environment variable \`\`WEB3\_PROVIDER\_URI\`\` before starting your script, and web3 will look for that provider first. Valid formats for this environment variable are: - \`\`file:///path/to/node/rpc-json/file.ipc\`\` - \`\`http://192.168.1.2:8545\`\` - \`\`https://node.ontheweb.com\`\` - \`\`ws://127.0.0.1:8546\`\` Auto-initialization Provider Shortcuts -------------------------------------- Geth dev Proof of Authority ~~~~~~~~~~~~~~~~~~~~~~~~~~~ To connect to a \`\`geth --dev\`\` Proof of Authority instance with the POA middleware loaded by default: .. code-block:: python >>> from web3.auto.gethdev import w3 # confirm that the connection succeeded >>> w3.is\_connected() True Or, connect to an async web3 instance: .. code-block:: python >>> from web3.auto.gethdev import async\_w3 >>> await async\_w3.provider.connect() # confirm that the connection succeeded >>> await async\_w3.is\_connected() True Built In Providers ------------------ Web3 ships with the following providers which are appropriate for connecting to local and remote JSON-RPC servers. HTTPProvider ~~~~~~~~~~~~ .. py:class:: web3.providers.rpc.HTTPProvider(endpoint\_uri, request\_kwargs={}, session=None, exception\_retry\_configuration=ExceptionRetryConfiguration()) This provider handles interactions with an HTTP or HTTPS based JSON-RPC server. \* \`\`endpoint\_uri\`\` should be the full URI to the RPC endpoint such as \`\`'https://localhost:8545'\`\`. For RPC servers behind HTTP connections running on port 80 and HTTPS connections running on port 443 the port can be omitted from the URI. \* \`\`request\_kwargs\`\` should be a dictionary of keyword arguments which will be passed onto each http/https POST request made to your node. \* \`\`session\`\` allows you to pass a \`\`requests.Session\`\` object initialized as desired. \* \`\`exception\_retry\_configuration\`\` is an instance of the :class:\`~web3.providers.rpc.utils.ExceptionRetryConfiguration\` class which allows you to configure how the provider should handle exceptions when making certain requests. Setting this to \`\`None\`\` will disable exception retries. .. code-block:: python >>> from web3 import Web3 >>> w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545")) Note that you should create only one HTTPProvider with the same provider URL per python process, as the HTTPProvider recycles underlying TCP/IP network connections, for better performance. Multiple HTTPProviders with different URLs will work as expected. Under the hood, the \`\`HTTPProvider\`\` uses the python requests library for making requests. If you would like to modify how requests are made, you can use the \`\`request\_kwargs\`\` to do so. A common use case for this is increasing the timeout for each request. .. code-block:: python >>> from web3 import Web3 >>> w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545", request\_kwargs={'timeout': 60})) To tune the connection pool size, you can pass your own \`\`requests.Session\`\`. .. code-block:: python >>> from web3 import Web3 >>> adapter = requests.adapters.HTTPAdapter(pool\_connections=20, pool\_maxsize=20) >>> session = requests.Session() >>> session.mount('http://', adapter) >>> session.mount('https://', adapter) >>> w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545", session=session)) IPCProvider ~~~~~~~~~~~ .. py:class:: web3.providers.ipc.IPCProvider(ipc\_path=None, timeout=10) This provider handles interaction with an IPC Socket based JSON-RPC server. \* \`\`ipc\_path\`\` is the filesystem path to the IPC socket: .. code-block:: python >>> from web3 import Web3 >>> w3 = Web3(Web3.IPCProvider("~/Library/Ethereum/geth.ipc")) If no \`\`ipc\_path\`\` is specified, it will use a default depending on your operating system. - On Linux and FreeBSD: \`\`~/.ethereum/geth.ipc\`\` - On Mac OS: \`\`~/Library/Ethereum/geth.ipc\`\` - On Windows: \`\`\\\\.\\pipe\\geth.ipc\`\` AsyncHTTPProvider ~~~~~~~~~~~~~~~~~ .. py:class:: web3.providers.rpc.AsyncHTTPProvider(endpoint\_uri, request\_kwargs={}, exception\_retry\_configuration=ExceptionRetryConfiguration()) This provider handles interactions with an HTTP or HTTPS based JSON-RPC server asynchronously. \* \`\`endpoint\_uri\`\` should be the full URI to the RPC endpoint such as \`\`'https://localhost:8545'\`\`. For RPC servers behind HTTP connections running on port 80 and HTTPS connections running on port 443 the port can be omitted from the URI. \* \`\`request\_kwargs\`\` should be a dictionary of keyword arguments which will be passed onto each http/https POST request made to your node. \* \`\`exception\_retry\_configuration\`\` is an instance of the :class:\`~web3.providers.rpc.utils.ExceptionRetryConfiguration\` class which allows you to configure how the provider should handle exceptions when making certain requests. Setting this to \`\`None\`\` will disable exception retries. The \`\`cache\_async\_session()\`\` method allows you to use your own \`\`aiohttp.ClientSession\`\` object. .. code-block:: python >>> from aiohttp import ClientSession >>> from web3 import AsyncWeb3, AsyncHTTPProvider >>> w3 = AsyncWeb3(AsyncHTTPProvider(endpoint\_uri)) >>> # If you want to pass in your own session: >>> custom\_session = ClientSession() >>> await w3.provider.cache\_async\_session(custom\_session) # This method is an async method so it needs to be handled accordingly Under the hood, the \`\`AsyncHTTPProvider\`\` uses the python \`aiohttp \`\_ library for making requests. Persistent Connection Providers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Persistent Connection Base Class ++++++++++++++++++++++++++++++++ .. note:: This class is not meant to be used directly. If your provider class inherits from this class, look to these docs for additional configuration options. .. py:class:: web3.providers.persistent.PersistentConnectionProvider(\\ request\_timeout: float = 50.0, \\ subscription\_response\_queue\_size: int = 500, \\ silence\_listener\_task\_exceptions: bool = False\\ ) This is a base provider class, inherited by the following providers: - :class:\`~web3.providers.persistent.WebSocketProvider\` - :class:\`~web3.providers.persistent.AsyncIPCProvider\` It handles interactions with a persistent connection to a JSON-RPC server. Among its configuration, it houses all of the :class:\`~web3.providers.persistent.request\_processor.RequestProcessor\` logic for handling the asynchronous sending and receiving of requests and responses. See the :ref:\`internals\_\_persistent\_connection\_providers\` section for more details on the internals of persistent connection providers. \* \`\`request\_timeout\`\` is the timeout in seconds, used when sending data over the connection and waiting for a response to be received from the listener task. Defaults to \`\`50.0\`\`. \* \`\`subscription\_response\_queue\_size\`\` is the size of the queue used to store subscription responses, defaults to \`\`500\`\`. While messages are being consumed, this queue should never fill up as it is a transient queue and meant to handle asynchronous receiving and processing of responses. When in sync with the socket stream, this queue should only ever store 1 to a few messages at a time. \* \`\`silence\_listener\_task\_exceptions\`\` is a boolean that determines whether exceptions raised by the listener task are silenced. Defaults to \`\`False\`\`, raising any exceptions that occur in the listener task. AsyncIPCProvider ++++++++++++++++ .. py:class:: web3.providers.persistent.AsyncIPCProvider(ipc\_path=None, max\_connection\_retries=5) This provider handles asynchronous, persistent interaction with an IPC Socket based JSON-RPC server. \* \`\`ipc\_path\`\` is the filesystem path to the IPC socket: \* \`\`read\_buffer\_limit\`\` is the maximum size of data, in bytes, that can be read from the socket at one time. Defaults to 20MB (20 \* 1024 \* 1024). Raises \`\`ReadBufferLimitReached\`\` if the limit is reached, suggesting that the buffer limit be increased. This provider inherits from the :class:\`~web3.providers.persistent.PersistentConnectionProvider\` class. Refer to the :class:\`~web3.providers.persistent.PersistentConnectionProvider\` documentation for details on additional configuration options available for this provider. If no \`\`ipc\_path\`\` is specified, it will use a default depending on your operating system. - On Linux and FreeBSD: \`\`~/.ethereum/geth.ipc\`\` - On Mac OS: \`\`~/Library/Ethereum/geth.ipc\`\` - On Windows: \`\`\\\\.\\pipe\\geth.ipc\`\` WebSocketProvider +++++++++++++++++ .. py:class:: web3.providers.persistent.WebSocketProvider(endpoint\_uri: str, websocket\_kwargs: Dict\[str, Any\] = {}) This provider handles interactions with an WS or WSS based JSON-RPC server. \* \`\`endpoint\_uri\`\` should be the full URI to the RPC endpoint such as \`\`'ws://localhost:8546'\`\`. \* \`\`websocket\_kwargs\`\` this should be a dictionary of keyword arguments which will be passed onto the ws/wss websocket connection. This provider inherits from the :class:\`~web3.providers.persistent.PersistentConnectionProvider\` class. Refer to the :class:\`~web3.providers.persistent.PersistentConnectionProvider\` documentation for details on additional configuration options available for this provider. Under the hood, the \`\`WebSocketProvider\`\` uses the python websockets library for making requests. If you would like to modify how requests are made, you can use the \`\`websocket\_kwargs\`\` to do so. See the \`websockets documentation\`\_ for available arguments. .. \_subscription-examples: Using Persistent Connection Providers +++++++++++++++++++++++++++++++++++++ The \`\`AsyncWeb3\`\` class may be used as a context manager, utilizing the \`\`async with\`\` syntax, when instantiating with a :class:\`~web3.providers.persistent.PersistentConnectionProvider\`. This will automatically close the connection when the context manager exits and is the recommended way to initiate a persistent connection to the provider. A similar example using a \`\`websockets\`\` connection as an asynchronous context manager can be found in the \`websockets connection\`\_ docs. .. code-block:: 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("web3.providers.AsyncIPCProvider") # for the AsyncIPCProvider ... logger = logging.getLogger("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(): ... print(f"{response}\\n") ... # handle responses here ... ... if some\_condition: ... # unsubscribe from new block headers and break out of ... # iterator ... await w3.eth.unsubscribe(subscription\_id) ... break ... ... # still an open connection, make any other requests and get ... # responses via send / receive ... latest\_block = await w3.eth.get\_block("latest") ... print(f"Latest block: {latest\_block}") ... ... # the connection closes automatically when exiting the context ... # manager (the \`async with\` block) >>> asyncio.run(context\_manager\_subscription\_example()) The \`\`AsyncWeb3\`\` class may also be used as an asynchronous iterator, utilizing the \`\`async for\`\` syntax, when instantiating with a :class:\`~web3.providers.persistent.PersistentConnectionProvider\`. This may be used to set up an indefinite websocket connection and reconnect automatically if the connection is lost. A similar example using a \`\`websockets\`\` connection as an asynchronous iterator can be found in the \`websockets connection\`\_ docs. .. \_\`websockets connection\`: https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#websockets.client.connect .. code-block:: python >>> import asyncio >>> import websockets >>> from web3 import AsyncWeb3 >>> from web3.providers.persistent import ( ... AsyncIPCProvider, ... WebSocketProvider, ... ) >>> async def subscription\_iterator\_example(): ... # async for w3 in AsyncWeb3(AsyncIPCProvider("./path/to/filename.ipc")): # for the AsyncIPCProvider ... async for w3 in AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")): # for the WebSocketProvider ... try: ... ... ... except websockets.ConnectionClosed: ... continue # run the example >>> asyncio.run(subscription\_iterator\_example()) Awaiting the instantiation with a :class:\`~web3.providers.persistent.PersistentConnectionProvider\`, or instantiating and awaiting the \`\`connect()\`\` method is also possible. Both of these examples are shown below. .. code-block:: python >>> async def await\_instantiation\_example(): ... # w3 = await AsyncWeb3(AsyncIPCProvider("./path/to/filename.ipc")) # for the AsyncIPCProvider ... w3 = await AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")) # for the WebSocketProvider ... ... # some code here ... ... # manual cleanup ... await w3.provider.disconnect() # run the example >>> asyncio.run(await\_instantiation\_example) .. code-block:: python >>> async def await\_provider\_connect\_example(): ... # w3 = AsyncWeb3(AsyncIPCProvider("./path/to/filename.ipc")) # for the AsyncIPCProvider ... w3 = AsyncWeb3(WebSocketProvider(f"ws://127.0.0.1:8546")) # for the WebSocketProvider ... await w3.provider.connect() ... ... # some code here ... ... # manual cleanup ... await w3.provider.disconnect() # run the example >>> asyncio.run(await\_provider\_connect\_example) :class:\`~web3.providers.persistent.PersistentConnectionProvider\` classes use the :class:\`~web3.providers.persistent.request\_processor.RequestProcessor\` class under the hood to sync up the receiving of responses and response processing for one-to-one and one-to-many request-to-response requests. Refer to the :class:\`~web3.providers.persistent.request\_processor.RequestProcessor\` documentation for details. AsyncWeb3 with Persistent Connection Providers ++++++++++++++++++++++++++++++++++++++++++++++ When an \`\`AsyncWeb3\`\` class is connected to a :class:\`~web3.providers.persistent.PersistentConnectionProvider\`, some attributes and methods become available. .. py:attribute:: socket The public API for interacting with the websocket connection is available via the \`\`socket\`\` attribute of the \`\`Asyncweb3\`\` class. This attribute is an instance of the :class:\`~web3.providers.persistent.persistent\_connection.PersistentConnection\` class and is the main interface for interacting with the socket connection. Interacting with the Persistent Connection ++++++++++++++++++++++++++++++++++++++++++ .. py:class:: web3.providers.persistent.persistent\_connection.PersistentConnection This class handles interactions with a persistent socket connection. It is available via the \`\`socket\`\` attribute on the \`\`AsyncWeb3\`\` class. The \`\`PersistentConnection\`\` class has the following methods and attributes: .. py:attribute:: subscriptions This attribute returns the current active subscriptions as a dict mapping the subscription \`\`id\`\` to a dict of metadata about the subscription request. .. py:method:: process\_subscriptions() This method is available for listening to websocket subscriptions indefinitely. It is an asynchronous iterator that yields strictly one-to-many (e.g. \`\`eth\_subscription\`\` responses) request-to-response messages from the websocket connection. To receive responses for one-to-one request-to-response calls, use the standard API for making requests via the appropriate module (e.g. \`\`block\_num = await w3.eth.block\_number\`\`) The responses from this method are formatted by \*web3.py\* formatters and run through the middleware that were present at the time of subscription. Examples on how to use this method can be seen above in the \`Using Persistent Connection Providers\`\_ section. .. py:method:: send(method: RPCEndpoint, params: Sequence\[Any\]) This method is available strictly for sending raw requests to the socket, if desired. It is not recommended to use this method directly, as the responses will not be formatted by \*web3.py\* formatters or run through the middleware. Instead, use the methods available on the respective web3 module. For example, use \`\`w3.eth.get\_block("latest")\`\` instead of \`\`w3.socket.send("eth\_getBlockByNumber", \["latest", True\])\`\`. .. py:method:: recv() The \`\`recv()\`\` method can be used to receive the next response for a request from the socket. The response from this method is the raw response. This is not the recommended way to receive a response for a request, as it is not formatted by \*web3.py\* formatters or run through the middleware. Instead, use the methods available on the respective web3 module (e.g. \`\`block\_num = await w3.eth.block\_number\`\`) for retrieving responses for one-to-one request-to-response calls. .. py:method:: make\_request(method: RPCEndpoint, params: Sequence\[Any\]) This method is available for making requests to the socket and retrieving the response. It is not recommended to use this method directly, as the responses will not be properly formatted by \*web3.py\* formatters or run through the middleware. Instead, use the methods available on the respective web3 module. For example, use \`\`w3.eth.get\_block("latest")\`\` instead of \`\`w3.socket.make\_request("eth\_getBlockByNumber", \["latest", True\])\`\`. LegacyWebSocketProvider ~~~~~~~~~~~~~~~~~~~~~~~ .. warning:: \`\`LegacyWebSocketProvider\`\` is deprecated and is likely to be removed in a future major release. Please use \`\`WebSocketProvider\`\` instead. .. py:class:: web3.providers.legacy\_websocket.LegacyWebSocketProvider(endpoint\_uri\[, websocket\_timeout, websocket\_kwargs\]) This provider handles interactions with an WS or WSS based JSON-RPC server. \* \`\`endpoint\_uri\`\` should be the full URI to the RPC endpoint such as \`\`'ws://localhost:8546'\`\`. \* \`\`websocket\_timeout\`\` is the timeout in seconds, used when receiving or sending data over the connection. Defaults to 10. \* \`\`websocket\_kwargs\`\` this should be a dictionary of keyword arguments which will be passed onto the ws/wss websocket connection. .. code-block:: python >>> from web3 import Web3 >>> w3 = Web3(Web3.LegacyWebSocketProvider("ws://127.0.0.1:8546")) Under the hood, \`\`LegacyWebSocketProvider\`\` uses the python \`\`websockets\`\` library for making requests. If you would like to modify how requests are made, you can use the \`\`websocket\_kwargs\`\` to do so. See the \`websockets documentation\`\_ for available arguments. .. \_\`websockets documentation\`: https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#websockets.client.WebSocketClientProtocol Unlike HTTP connections, the timeout for WS connections is controlled by a separate \`\`websocket\_timeout\`\` argument, as shown below. .. code-block:: python >>> from web3 import Web3 >>> w3 = Web3(Web3.LegacyWebSocketProvider("ws://127.0.0.1:8546", websocket\_timeout=60)) AutoProvider ~~~~~~~~~~~~ :class:\`~web3.providers.auto.AutoProvider\` is the default used when initializing :class:\`web3.Web3\` without any providers. There's rarely a reason to use it explicitly. .. py:currentmodule:: web3.providers.eth\_tester EthereumTesterProvider ~~~~~~~~~~~~~~~~~~~~~~ .. warning:: Experimental: This provider is experimental. There are still significant gaps in functionality. However it is being actively developed and supported. .. py:class:: EthereumTesterProvider(ethereum\_tester=None, api\_endpoints=None) .. py:class:: AsyncEthereumTesterProvider(ethereum\_tester=None, api\_endpoints=None) This provider integrates with the \`\`eth-tester\`\` library. The \`\`ethereum\_tester\`\` constructor argument should be an instance of the :class:\`~eth\_tester.EthereumTester\` or a subclass of :class:\`~eth\_tester.backends.base.BaseChainBackend\` class provided by the \`\`eth-tester\`\` library. The \`\`api\_endpoints\`\` argument should be a \`\`dict\`\` of RPC endpoints. You can see the structure and defaults \`here \`\_. If you would like a custom \`\`eth-tester\`\` instance to test with, see the \`\`eth-tester\`\` library \`documentation \`\_ for details. .. code-block:: python >>> from web3 import Web3, EthereumTesterProvider >>> w3 = Web3(EthereumTesterProvider()) .. NOTE:: To install the needed dependencies to use EthereumTesterProvider, you can install the pip extras package that has the correct interoperable versions of the \`\`eth-tester\`\` and \`\`py-evm\`\` dependencies needed: e.g. \`\`pip install "web3\[tester\]"\`\` --- # Unknown .. \_quickstart: Quickstart ========== .. contents:: :local: .. NOTE:: All code starting with a \`\`$\`\` is meant to run on your terminal. All code starting with a \`\`>>>\`\` is meant to run in a python interpreter, like \`ipython \`\_. Installation ------------ web3.py can be installed (preferably in a :ref:\`virtualenv \`) using \`\`pip\`\` as follows: .. code-block:: shell $ pip install web3 .. NOTE:: If you run into problems during installation, you might have a broken environment. See the troubleshooting guide to :ref:\`setting up a clean environment \`. Using Web3 ---------- This library depends on a connection to an Ethereum node. We call these connections \*Providers\* and there are several ways to configure them. The full details can be found in the :ref:\`Providers\` documentation. This Quickstart guide will highlight a couple of the most common use cases. Test Provider \*\*\*\*\*\*\*\*\*\*\*\*\* If you're just learning the ropes or doing some quick prototyping, you can use a test provider, \`eth-tester \`\_. This provider includes some accounts prepopulated with test ether and instantly includes each transaction into a block. web3.py makes this test provider available via \`\`EthereumTesterProvider\`\`. .. note:: The \`\`EthereumTesterProvider\`\` requires additional dependencies. Install them via \`\`pip install "web3\[tester\]"\`\`, then import and instantiate the provider as seen below. .. code-block:: python >>> from web3 import Web3, EthereumTesterProvider >>> w3 = Web3(EthereumTesterProvider()) >>> w3.is\_connected() True Local Providers \*\*\*\*\*\*\*\*\*\*\*\*\*\*\* The hardware requirements are \`steep \`\_, but the safest way to interact with Ethereum is to run an Ethereum client on your own hardware. For locally run nodes, an IPC connection is the most secure option, but HTTP and websocket configurations are also available. By default, the popular \`Geth client \`\_ exposes port \`\`8545\`\` to serve HTTP requests and \`\`8546\`\` for websocket requests. Connecting to this local node can be done as follows: .. code-block:: 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 Remote Providers \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* The quickest way to interact with the Ethereum blockchain is to use a \`remote node provider \`\_. You can connect to a remote node by specifying the endpoint, just like the previous local node example: .. code-block:: python >>> from web3 import Web3, AsyncWeb3 >>> w3 = Web3(Web3.HTTPProvider('https://')) >>> w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider('https://')) >>> w3 = await AsyncWeb3(AsyncWeb3.WebSocketProvider('wss://')) This endpoint is provided by the remote node service, typically after you create an account. .. \_first\_w3\_use: Getting Blockchain Info ----------------------- It's time to start using web3.py! Once properly configured, the \`\`w3\`\` instance will allow you to interact with the Ethereum blockchain. Try getting all the information about the latest block: .. code-block:: 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'), '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': \[\]} web3.py can help you read block data, sign and send transactions, deploy and interact with contracts, and a number of other features. A few suggestions from here: - The :doc:\`overview\` page provides a summary of web3.py's features. - The :class:\`w3.eth \` API contains the most frequently used methods. - A guide to :ref:\`contracts\` includes deployment and usage examples. - The nuances of :doc:\`transactions\` are explained in another guide. .. NOTE:: It is recommended that your development environment have the \`\`PYTHONWARNINGS=default\`\` environment variable set. Some deprecation warnings will not show up without this variable being set. --- # Unknown Web3 Internals ============== .. warning:: This section of the documentation is for advanced users. You should probably stay away from these APIs if you don't know what you are doing. The Web3 library has multiple layers of abstraction between the public api exposed by the web3 object and the backend or node that web3 is connecting to. \* \*\*Providers\*\* are responsible for the actual communication with the blockchain such as sending JSON-RPC requests over HTTP or an IPC socket. \* \*\*Middleware\*\* provide hooks for monitoring and modifying requests and responses to and from the provider. \* \*\*Managers\*\* provide thread safety and primitives to allow for asynchronous usage of web3. Here are some common things you might want to do with these APIs. \* Redirect certain RPC requests to different providers such as sending all \*read\* operations to a provider backed by a remote node and all \*write\* operations to a local node that you control. \* Transparently intercept transactions sent over \`\`eth\_sendTransaction\`\`, sign them locally, and then send them through \`\`eth\_sendRawTransaction\`\`. \* Modify the response from an RPC request so that it is returned in different format such as converting all integer values to their hexadecimal representation. \* Validate the inputs to RPC requests Request Lifecycle ----------------- Each web3 RPC call passes through these layers in the following manner. .. code-block:: none \*\*\*\*\*\*\*\*\*\*\* \*\*\*\*\*\*\*\*\*\*\*\* | Request | | Response | \*\*\*\*\*\*\*\*\*\*\* \*\*\*\*\*\*\*\*\*\*\*\* | ^ v | +-----------------------------+ | Manager | +-----------------------------+ | ^ v | +-----------------------------+ | Middleware | +-----------------------------+ | ^ v | +-----------------------------+ | Provider | +-----------------------------+ You can visualize this relationship like an onion, with the Provider at the center. The request originates from the \`\`Manager\`\`, outside of the onion, passing down through each layer of the onion until it reaches the \`\`Provider\`\` at the center. The \`\`Provider\`\` then handles the request, producing a response which will then pass back out from the center of the onion, through each layer until it is finally returned by the \`\`Manager\`\`. Providers --------- A provider is responsible for all direct blockchain interactions. In most cases this means interacting with the JSON-RPC server for an ethereum node over HTTP or an IPC socket. There is however nothing which requires providers to be RPC based, allowing for providers designed for testing purposes which use an in-memory EVM to fulfill requests. Writing your own Provider ~~~~~~~~~~~~~~~~~~~~~~~~~ Writing your own provider requires implementing two required methods as well as setting the middleware the provider should use. .. py:method:: BaseProvider.make\_request(method, params) Each provider class \*\*must\*\* implement this method. This method \*\*should\*\* return a JSON object with either a \`\`'result'\`\` key in the case of success, or an \`\`'error'\`\` key in the case of failure. \* \`\`method\`\` This will be a string representing the JSON-RPC method that is being called such as \`\`'eth\_sendTransaction'\`\`. \* \`\`params\`\` This will be a list or other iterable of the parameters for the JSON-RPC method being called. .. py:method:: BaseProvider.is\_connected(show\_traceback=False) This function should return \`\`True\`\` or \`\`False\`\` depending on whether the provider should be considered \*connected\*. For example, an IPC socket based provider should return \`\`True\`\` if the socket is open and \`\`False\`\` if the socket is closed. If set to \`\`True\`\`, the optional \`\`show\_traceback\`\` boolean will raise a \`\`ProviderConnectionError\`\` and provide information on why the provider should not be considered \*connected\*. .. py:attribute:: BaseProvider.middleware This should be an iterable of middleware. You can set a new list of middleware by assigning to \`\`provider.middleware\`\`, with the first middleware that processes the request at the beginning of the list. Provider Configurations ~~~~~~~~~~~~~~~~~~~~~~~ .. \_request\_caching: Request Caching \`\`\`\`\`\`\`\`\`\`\`\`\`\`\` .. important:: Familiarize yourself with the validation logic for request caching before enabling it. Since this feature often requires making additional requests under the hood to try to guarantee the validity of the data, it may create unnecessary overhead for your use case. Validation can be turned off by setting the \`\`request\_cache\_validation\_threshold\`\` option to \`\`None\`\`, caching all allowed requests, or configured for adjusting performance to your needs. Request caching can be configured at the provider level via the following configuration options on the provider instance: - \`\`cache\_allowed\_requests: bool = False\`\` - \`\`cacheable\_requests: Optional\[Set\[RPCEndpoint\]\]\`\` - \`\`request\_cache\_validation\_threshold: Optional\[Union\[RequestCacheValidationThreshold, int\]\]\`\` For requests that don't rely on block data (e.g., \`\`eth\_chainId\`\`), enabling request caching by setting the \`\`cache\_allowed\_requests\`\` option to \`\`True\`\` will cache all responses. This is safe to do. However, for requests that rely on block data (e.g., \`\`eth\_getBlockByNumber\`\`), it is not safe to always cache their responses because block data can change - during a chain reorganization or while finality has not been reached, for example. The \`\`request\_cache\_validation\_threshold\`\` option allows configuring a safe threshold for caching responses that depend on block data. By default, this option is configured to internal values deemed "safe" for the chain id you are connected to. If you are connected to mainnet Ethereum, this value is set to the \`\`finalized\`\` block number. If you are connected to another chain, this value is set to a time interval in seconds, from the current time, that is deemed "safe" for that chain's finality mechanism. \*\*It's important to understand that, in order to perform these validations, extra requests are sometimes made to the node to get the appropriate information. For a transaction request, for example, it is necessary to get the block information to validate the transaction is beyond the safe threshold. This can create overhead, especially for high-frequency requests. For this reason, it is important to understand when to turn on caching and how to configure the validation appropriately for your use case in order to avoid unnecessary overhead.\*\* We keep a list of some reasonable values for bigger chains and use the time interval of 1 hour for everything else. Below is a list of the default values for internally configured chains: - ETH: RequestCacheValidationThreshold.FINALIZED ("finalized" block) - ARB1: 7 days - ZKSYNC: 1 hour - OETH: 3 minutes - MATIC: 30 minutes - ZKEVM: 1 hour - BASE: 7 days - SCR: 1 hour - GNO: 5 minutes - AVAX: 2 minutes - BNB: 2 minutes - FTM: 1 minute For Ethereum mainnet, for example, this means that a request's response will be cached if the block number the request relies on is less than or equal to the \`\`finalized\`\` block number. If the block number exceeds the \`\`finalized\`\` block number, the response won't be cached. For all others, the response will be cached if the block timestamp related to the data that is being requested is older than or equal to the time interval configured for that chain. For any chain not on this list, the default value is set to 1 hour (this includes all testnets). This behavior can be modified by setting the \`\`request\_cache\_validation\_threshold\`\` option to \`\`RequestCacheValidationThreshold.SAFE\`\`, which uses the \`\`safe\`\` block as the threshold (Ethereum mainnet only), to your own time interval in seconds (for any chain, including mainnet Ethereum), or to \`\`None\`\`, which disables any validation and caches all requests (this is not recommended for non testnet chains). The \`\`RequestCacheValidationThreshold\`\` enum, for mainnet \`\`finalized\`\` and \`\`safe\`\` values, is imported from the \`\`web3.utils\`\` module. Note that the \`\`cacheable\_requests\`\` option can be used to specify a set of RPC endpoints that are allowed to be cached. By default, this option is set to an internal list of deemed-safe-to-cache endpoints, excluding endpoints such as \`\`eth\_call\`\`, whose responses can vary and are not safe to cache. The default list of cacheable requests is below, with requests validated by the \`\`request\_cache\_validation\_threshold\`\` option in bold: - eth\_chainId - web3\_clientVersion - net\_version - \*\*eth\_getBlockByNumber\*\* - \*\*eth\_getRawTransactionByBlockNumberAndIndex\*\* - \*\*eth\_getBlockTransactionCountByNumber\*\* - \*\*eth\_getUncleByBlockNumberAndIndex\*\* - \*\*eth\_getUncleCountByBlockNumber\*\* - \*\*eth\_getBlockByHash\*\* - \*\*eth\_getTransactionByHash\*\* - \*\*eth\_getTransactionByBlockNumberAndIndex\*\* - \*\*eth\_getTransactionByBlockHashAndIndex\*\* - \*\*eth\_getBlockTransactionCountByHash\*\* - \*\*eth\_getRawTransactionByBlockHashAndIndex\*\* - \*\*eth\_getUncleByBlockHashAndIndex\*\* - \*\*eth\_getUncleCountByBlockHash\*\* .. code-block:: python from web3 import Web3, HTTPProvider from web3.utils import RequestCacheValidationThreshold w3 = Web3(HTTPProvider( endpoint\_uri="...", # optional flag to turn on cached requests, defaults to \`\`False\`\` cache\_allowed\_requests=True, # optional, defaults to an internal list of deemed-safe-to-cache endpoints (see above) cacheable\_requests={"eth\_chainId", "eth\_getBlockByNumber"}, # optional, defaults to a value that is based on the chain id (see above) request\_cache\_validation\_threshold=60 \* 60, # 1 hour # request\_cache\_validation\_threshold=RequestCacheValidationThreshold.SAFE, # Ethereum mainnet only )) .. \_http\_retry\_requests: Retry Requests for HTTP Providers \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` \`\`HTTPProvider\`\` and \`\`AsyncHTTPProvider\`\` instances retry certain requests by default on exceptions. This can be configured via the \`\`exception\_retry\_configuration\`\` property on the provider instance, which takes a :class:\`~web3.providers.rpc.utils.ExceptionRetryConfiguration\` class as its value. The retry mechanism employs an exponential backoff strategy, starting from the initial value determined by the \`\`backoff\_factor\`\`, and doubling the delay with each attempt, up to the \`\`retries\`\` value. Below is an example showing the default options for the retry configuration and how to override them. .. py:class:: web3.providers.rpc.utils.ExceptionRetryConfiguration .. py:attribute:: errors A tuple of exceptions that the provider should retry on. The default is \`\`HTTPProvider\`\`: \`\`(ConnectionError, requests.HTTPError, requests.Timeout)\`\` and \`\`AsyncHTTPProvider\`\`: \`\`(aiohttp.ClientError, asyncio.TimeoutError)\`\`. .. py:attribute:: retries The number of retries to attempt. The default is 5. .. py:attribute:: backoff\_factor The initial delay multiplier, which doubles with each retry attempt. The default is 0.125. .. py:attribute:: method\_allowlist A list of retryable methods. The default is an in-house list of deemed-safe-to- retry methods. .. code-block:: python from web3 import Web3, HTTPProvider from web3.providers.rpc.utils import ( REQUEST\_RETRY\_ALLOWLIST, ExceptionRetryConfiguration, ) w3 = Web3(HTTPProvider( endpoint\_uri="...", exception\_retry\_configuration=ExceptionRetryConfiguration( errors=DEFAULT\_EXCEPTIONS, # number of retries to attempt retries=5, # initial delay multiplier, doubles with each retry attempt backoff\_factor=0.125, # an in-house default list of retryable methods method\_allowlist=REQUEST\_RETRY\_ALLOWLIST, ), )) For the different http providers, \`\`DEFAULT\_EXCEPTIONS\`\` is defined as: - \`\`HTTPProvider\`\`: \`\`(ConnectionError, requests.HTTPError, requests.Timeout)\`\` - \`\`AsyncHTTPProvider\`\`: \`\`(ConnectionError, aiohttp.ClientError, asyncio.TimeoutError)\`\` Setting \`\`retry\_configuration\`\` to \`\`None\`\` will disable retries on exceptions for the provider instance. .. code-block:: python from web3 import Web3, HTTPProvider w3 = Web3(HTTPProvider(endpoint\_uri="...", retry\_configuration=None) Managers -------- The Manager acts as a gatekeeper for the request/response lifecycle. It is unlikely that you will need to change the Manager as most functionality can be implemented in the Middleware layer. .. \_internals\_\_persistent\_connection\_providers: Request Processing for Persistent Connection Providers ------------------------------------------------------ .. py:class:: web3.providers.persistent.request\_processor.RequestProcessor The \`\`RequestProcessor\`\` class is responsible for the storing and syncing up of asynchronous requests to responses for a \`\`PersistentConnectionProvider\`\`. The :class:\`~web3.providers.persistent.WebSocketProvider\` and the :class:\`~web3.providers.persistent.AsyncIPCProvider\` are two persistent connection providers. In order to send a request and receive a response to that same request, \`\`PersistentConnectionProvider\`\` instances have to match request \*id\* values to response \*id\* values coming back from the socket connection. Any provider that does not adhere to the \`JSON-RPC 2.0 specification \`\_ in this way will not work with \`\`PersistentConnectionProvider\`\` instances. The specifics of how the request processor handles this are outlined below. Listening for Responses ~~~~~~~~~~~~~~~~~~~~~~~ Implementations of the \`\`PersistentConnectionProvider\`\` class have a message listener background task that is called when the socket connection is established. This task is responsible for listening for any and all messages coming in over the socket connection and storing them in the \`\`RequestProcessor\`\` instance internal to the \`\`PersistentConnectionProvider\`\` instance. The \`\`RequestProcessor\`\` instance is responsible for storing the messages in the correct cache, either the one-to-one cache or the one-to-many (subscriptions) queue, depending on whether the message has a JSON-RPC \*id\* value or not. One-To-One Requests ~~~~~~~~~~~~~~~~~~~ One-to-one requests can be summarized as any request that expects only one response back. An example is using the \`\`eth\`\` module API to request the latest block number. .. code-block:: 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()) With persistent socket connections, we have to call \`\`send()\`\` and asynchronously receive responses via another means, generally by calling \`\`recv()\`\` or by iterating on the socket connection for messages. As outlined above, the \`\`PersistentConnectionProvider\`\` class has a message listener background task that handles the receiving of messages. Due to this asynchronous nature of sending and receiving, in order to make one-to-one request-to-response calls work, we have to save the request information somewhere so that, when the response is received, we can match it to the original request that was made (i.e. the request with a matching \*id\* to the response that was received). The stored request information is then used to process the response when it is received, piping it through the response formatters and middleware internal to the \*web3.py\* library. In order to store the request information, the \`\`RequestProcessor\`\` class has an internal \`\`RequestInformation\`\` cache. The \`\`RequestInformation\`\` class saves important information about a request. .. py:class:: web3.\_utils.caching.RequestInformation .. py:attribute:: method The name of the method - e.g. "eth\_subscribe". .. py:attribute:: params The params used when the call was made - e.g. ("newPendingTransactions", True). .. py:attribute:: response\_formatters The formatters that will be used to process the response. .. py:attribute:: middleware\_response\_processors Any middleware that processes responses that is present on the instance at the time of the request is appended here, in order, so the response may be piped through that logic when it comes in. .. py:attribute:: subscription\_id If the request is an \`\`eth\_subscribe\`\` request, rather than popping this information from the cache when the response to the subscription call comes in (i.e. the subscription \*id\*), we save the subscription id with the request information so that we can correctly process all subscription messages that come in with that subscription \*id\*. For one-to-one request-to-response calls, this value is always \`\`None\`\`. One-to-one responses, those that include a JSON-RPC \*id\* in the response object, are stored in an internal \`\`SimpleCache\`\` class, isolated from any one-to-many responses. When the \`\`PersistentConnectionProvider\`\` is looking for a response internally, it will expect the message listener task to store the response in this cache. Since the request \*id\* is used in the cache key generation, it will then look for a cache key that matches the response \*id\* with that of the request \*id\*. If the cache key is found, the response is processed and returned to the user. If the cache key is not found, the operation will time out and raise a \`\`TimeExhausted\`\` exception. This timeout can be configured by the user when instantiating the \`\`PersistentConnectionProvider\`\` instance via the \`\`response\_timeout\`\` keyword argument. One-To-Many Requests ~~~~~~~~~~~~~~~~~~~~ One-to-many requests can be summarized by any request that expects many responses as a result of the initial request. The only current example is the \`\`eth\_subscribe\`\` request. The initial \`\`eth\_subscribe\`\` request expects only one response, the subscription \*id\* value, but it also expects to receive many \`\`eth\_subscription\`\` messages if and when the request is successful. For this reason, the original request is considered a one-to-one request so that a subscription \*id\* can be returned to the user on the same line, but the \`\`process\_subscriptions()\`\` method on the :class:\`~web3.providers.persistent.PersistentConnection\` class, the public API for interacting with the active persistent socket connection, is set up to receive \`\`eth\_subscription\`\` responses over an asynchronous interator pattern. .. code-block:: 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()) One-to-many responses, those that do not include a JSON-RPC \*id\* in the response object, are stored in an internal \`\`asyncio.Queue\`\` instance, isolated from any one-to-one responses. When the \`\`PersistentConnectionProvider\`\` is looking for one-to-many responses internally, it will expect the message listener task to store these messages in this queue. Since the order of the messages is important, the queue is a FIFO queue. The \`\`process\_subscriptions()\`\` method on the \`\`PersistentConnection\`\` class is set up to pop messages from this queue as FIFO over an asynchronous iterator pattern. If the stream of messages from the socket is not being interrupted by any other tasks, the queue will generally be in sync with the messages coming in over the socket. That is, the message listener will put a message in the queue and the \`\`process\_subscriptions()\`\` method will pop that message from the queue and yield control of the loop back to the listener. This will continue until the socket connection is closed or the user unsubscribes from the subscription. If the stream of messages lags a bit, or the provider is not consuming messages but has subscribed to a subscription, this internal queue may fill up with messages until it reaches its max size and then trigger a waiting \`\`asyncio.Event\`\` until the provider begins consuming messages from the queue again. For this reason, it's important to begin consuming messages from the queue, via the \`\`process\_subscriptions()\`\` method, as soon as a subscription is made. --- # Unknown .. meta:: :description: Python Web3 SDK for Ethereum and EVM blockchains gm == .. image:: \_static/banner/banner-snek.jpg :alt: Banner Image \*\*web3.py\*\* is a Python library for interacting with Ethereum. It's commonly found in \`decentralized apps (dapps)\`\_ to help with sending transactions, interacting with smart contracts, reading block data, and a variety of other use cases. For project updates, follow \`@EthereumPython\`\_ and sign up for new post notifications on the \`blog\`\_. Getting Started --------------- .. NOTE:: 👋 Brand new to Ethereum? 0. Don't travel alone! Join the Ethereum Python Community \`Discord\`\_. 1. Read this \`blog post series\`\_ for a gentle introduction to Ethereum blockchain concepts. 2. The :ref:\`Overview\` page will give you a quick idea of what else web3.py can do. 3. Try building a little something! - Ready to code? → :ref:\`quickstart\` - Quick tour? → :ref:\`overview\` - Synchronous help? → \`Discord\`\_ - Asynchronous help? → \`StackExchange\`\_ - Report a bug? → \`Github\`\_ - Want to help us? → :ref:\`Contribute \` - Looking for inspiration? → :ref:\`resources\` .. include:: toc.rst .. \_decentralized apps (dapps): https://ethereum.org/dapps/ .. \_@EthereumPython: https://twitter.com/EthereumPython .. \_blog: https://snakecharmers.ethereum.org/ .. \_blog post series: https://snakecharmers.ethereum.org/a-developers-guide-to-ethereum-pt-1 .. \_StackExchange: https://ethereum.stackexchange.com/questions/tagged/web3.py .. \_Discord: https://discord.gg/GHryRvPB84 .. \_Github: https://github.com/ethereum/web3.py/issues --- # Unknown .. \_middleware\_internals: Middleware ========== \`\`Web3\`\` is instantiated with layers of middleware by default. They sit between the public \`\`Web3\`\` methods and the :doc:\`providers\`, and are used to perform sanity checks, convert data types, enable ENS support, and more. Each layer can modify the request and/or response. While several middleware are enabled by default, others are available for optional use, and you're free to create your own! Each middleware layer gets invoked before the request reaches the provider, and then processes the result after the provider returns, in reverse order. However, it is possible for a middleware to return early from a call without the request ever getting to the provider (or even reaching the middleware that are in deeper layers). .. \_Modifying\_Middleware: Configuring Middleware ----------------------- Middleware can be added, removed, replaced, and cleared at runtime. To make that easier, you can name the middleware for later reference. Middleware Order ~~~~~~~~~~~~~~~~ Think of the middleware as being layered in an onion, where you initiate a web3.py request at the outermost layer of the onion, and the Ethereum node (like geth) receives and responds to the request inside the innermost layer of the onion. Here is a (simplified) diagram: .. code-block:: none New request from web3.py | | v \`\`\`\`\`Layer 2\`\`\`\`\`\` \`\`\`\`\`\`\` \`\`\`\`\`\`\` \`\`\`\`\` | \`\`\`\` \`\`\`\` v \`\`\`\` \`\`\` \`\`\` \`. \`\`\`\`\`\`\`\`Layer 1\`\`\`\`\`\`\` \`.\` \`\` \`\`\`\` \`\`\`\`\` .\` \`. \`\`\` | \`\`\` \`.\` .\` \`\`\` v \`\`\` \`. \`. \`.\` \`\`\` .\` \`\` .\` \`Layer 0\` \`\` .\` \`\` \`. \`\`\`\`\` \`\`\`\`\`\` . .\` \`. \`\` \`\`\` | \`\`\` .\` . . \`\` \`.\` | \`\` . . . \`. \`\` JSON-RPC call .\` . .\` . . \`\` | . \`\` . \`\` . . v . . . . .\` . . . \`\` . . . Ethereum node .\` . . . . . . . . . \`\` \`. | . . . . . .\` | .\` . . \`. .\` .\` Response .\` .\` . . . \`.\` | \`.\` \`. . \`. . \`\`\` | \`\`\`\` \`. . . \`. \`\`\`\`\` v \`\`\`\` \`. \`\` . .\` \`\`\`Layer 0\`\` \`\` \`. . \`. \`.\` \`. . \`. | \`.\` \`. .\` \`\`\` | \`\`\` .\` \`. \`\`\` v \`\`\`\` \`.\` \`\` \`\`\`\`\`\` \`\`\`\`\` .\` \`\` \`\`\`\`\`Layer 1\`\`\`\`\` \`.\` \`\`\` \`\`\` \`\`\`\` | \`\`\` \`\`\`\`\` v \`\`\`\` \`\`\`\`\`\` \`\`\`\`\` \`\`\`\`\`\`\`\`\`Layer 2\`\`\`\`\`\`\`\`\`\` | v Returned value in web3.py The middleware are maintained in \`\`Web3.middleware\_onion\`\`. See below for the API. When specifying middleware in a list, or retrieving the list of middleware, they will be returned in the order of outermost layer first and innermost layer last. In the above example, that means that \`\`w3.middleware\_onion.middleware\`\` would return the middleware in the order of: \`\`\[2, 1, 0\]\`\`. .. \_middleware\_stack\_api: Middleware Stack API ~~~~~~~~~~~~~~~~~~~~ To add or remove items in different layers, use the following API: .. py:method:: Web3.middleware\_onion.add(middleware, name=None) Middleware will be added to the outermost layer. That means the new middleware will modify the request first, and the response last. You can optionally name it with any hashable object, typically a string. .. code-block:: python >>> w3 = Web3(...) >>> w3.middleware\_onion.add(web3.middleware.GasPriceStrategyMiddleware) # or >>> w3.middleware\_onion.add(web3.middleware.GasPriceStrategyMiddleware, 'gas\_price\_strategy') .. py:method:: Web3.middleware\_onion.inject(middleware, name=None, layer=None) Inject a named middleware to an arbitrary layer. The current implementation only supports injection at the innermost or outermost layers. Note that injecting to the outermost layer is equivalent to calling :meth:\`Web3.middleware\_onion.add\` . .. code-block:: python # Either of these will put the gas\_price\_strategy middleware at the innermost layer >>> w3 = Web3(...) >>> w3.middleware\_onion.inject(web3.middleware.GasPriceStrategyMiddleware, layer=0) # or >>> w3.middleware\_onion.inject(web3.middleware.GasPriceStrategyMiddleware, 'gas\_price\_strategy', layer=0) .. py:method:: Web3.middleware\_onion.remove(middleware) Middleware will be removed from whatever layer it was in. If you added the middleware with a name, use the name to remove it. If you added the middleware as an object, use the object again later to remove it: .. code-block:: python >>> w3 = Web3(...) >>> w3.middleware\_onion.remove(web3.middleware.GasPriceStrategyMiddleware) # or >>> w3.middleware\_onion.remove('gas\_price\_strategy') .. py:method:: Web3.middleware\_onion.replace(old\_middleware, new\_middleware) Middleware will be replaced from whatever layer it was in. If the middleware was named, it will continue to have the same name. If it was un-named, then you will now reference it with the new middleware object. .. code-block:: python >>> from web3.middleware import GasPriceStrategyMiddleware, AttributeDictMiddleware >>> w3 = Web3(provider, middleware=\[GasPriceStrategyMiddleware, AttributeDictMiddleware\]) >>> w3.middleware\_onion.replace(GasPriceStrategyMiddleware, AttributeDictMiddleware) # this is now referenced by the new middleware object, so to remove it: >>> w3.middleware\_onion.remove(AttributeDictMiddleware) # or, if it was named >>> w3.middleware\_onion.replace('gas\_price\_strategy', AttributeDictMiddleware) # this is still referenced by the original name, so to remove it: >>> w3.middleware\_onion.remove('gas\_price\_strategy') .. py:method:: Web3.middleware\_onion.clear() Empty all the middleware, including the default ones. .. code-block:: python >>> w3 = Web3(...) >>> w3.middleware\_onion.clear() >>> assert len(w3.middleware\_onion) == 0 .. py:attribute:: Web3.middleware\_onion.middleware Return all the current middleware for the \`\`Web3\`\` instance in the appropriate order for importing into a new \`\`Web3\`\` instance. .. code-block:: python >>> w3\_1 = Web3(...) # add uniquely named middleware: >>> w3\_1.middleware\_onion.add(web3.middleware.GasPriceStrategyMiddleware, 'test\_middleware') # export middleware from first w3 instance >>> middleware = w3\_1.middleware\_onion.middleware # import into second instance >>> w3\_2 = Web3(..., middleware=middleware) >>> assert w3\_1.middleware\_onion.middleware == w3\_2.middleware\_onion.middleware >>> assert w3\_2.middleware\_onion.get('test\_middleware') Instantiate with Custom Middleware ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Instead of working from the default list, you can specify a custom list of middleware when initializing Web3: .. code-block:: python Web3(middleware=\[my\_middleware1, my\_middleware2\]) .. warning:: This will \*replace\* the default middleware. To keep the default functionality, either use \`\`middleware\_onion.add()\`\` from above, or add the default middleware to your list of new middleware. .. \_default\_middleware: Default Middleware ------------------ The following middleware are included by default: \* \`\`gas\_price\_strategy\`\` \* \`\`ens\_name\_to\_address\`\` \* \`\`attrdict\`\` \* \`\`validation\`\` \* \`\`gas\_estimate\`\` The defaults are defined in the \`\`get\_default\_middleware()\`\` method in \`\`web3/manager.py\`\`. AttributeDict ~~~~~~~~~~~~~ .. py:class:: web3.middleware.AttributeDictMiddleware This middleware recursively converts any dictionary type in the result of a call to an \`\`AttributeDict\`\`. This enables dot-syntax access, like \`\`eth.get\_block('latest').number\`\` in addition to \`\`eth.get\_block('latest')\['number'\]\`\`. .. note:: Accessing a property via attribute breaks type hinting. For this reason, this feature is available as a middleware, which may be removed if desired. ENS Name to Address Resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:class:: web3.middleware.ENSNameToAddressMiddleware This middleware converts Ethereum Name Service (ENS) names into the address that the name points to. For example :meth:\`w3.eth.send\_transaction \` will accept .eth names in the 'from' and 'to' fields. .. note:: This middleware only converts ENS names on chains where the proper ENS contracts are deployed to support this functionality. All other cases will result in a \`\`NameNotFound\`\` error. Gas Price Strategy ~~~~~~~~~~~~~~~~~~ .. py:class:: web3.middleware.GasPriceStrategyMiddleware .. warning:: Gas price strategy is only supported for legacy transactions. The London fork introduced \`\`maxFeePerGas\`\` and \`\`maxPriorityFeePerGas\`\` transaction parameters which should be used over \`\`gasPrice\`\` whenever possible. This adds a \`\`gasPrice\`\` to transactions if applicable and when a gas price strategy has been set. See :ref:\`Gas\_Price\` for information about how gas price is derived. Buffered Gas Estimate ~~~~~~~~~~~~~~~~~~~~~ .. py:class:: web3.middleware.BufferedGasEstimateMiddleware This adds a gas estimate to transactions if \`\`gas\`\` is not present in the transaction parameters. Sets gas to: \`\`min(w3.eth.estimate\_gas + gas\_buffer, gas\_limit)\`\` where the gas\_buffer default is 100,000 Validation ~~~~~~~~~~ .. py:class:: web3.middleware.ValidationMiddleware This middleware includes block and transaction validators which perform validations for transaction parameters. Optional Middleware ------------------- \`\`Web3\`\` includes optional middleware for common use cases. Below is a list of available middleware which are not enabled by default. Stalecheck ~~~~~~~~~~~~ .. py:method:: web3.middleware.StalecheckMiddlewareBuilder This middleware checks how stale the blockchain is, and interrupts calls with a failure if the blockchain is too old. \* \`\`allowable\_delay\`\` is the length in seconds that the blockchain is allowed to be behind of \`\`time.time()\`\` Because this middleware takes an argument, you must create the middleware with a method call. .. code-block:: python two\_day\_stalecheck = StalecheckMiddlewareBuilder.build(60 \* 60 \* 24 \* 2) web3.middleware\_onion.add(two\_day\_stalecheck) If the latest block in the blockchain is older than 2 days in this example, then the middleware will raise a \`\`StaleBlockchain\`\` exception on every call except \`\`web3.eth.get\_block()\`\`. .. \_geth-poa: Proof of Authority ~~~~~~~~~~~~~~~~~~ .. py:class:: web3.middleware.ExtraDataToPOAMiddleware .. important:: It is \*\*crucial\*\* that this middleware is injected at the 0th layer of the middleware onion, using \`\`w3.middleware\_onion.inject(ExtraDataToPOAMiddleware, layer=0)\`\`, to guarantee it is the \*first\* middleware to process the response and modify the \`\`extraData\`\` field. This ensures it processes the field before any other middleware attempts to validate it. \`\`ExtraDataToPOAMiddleware\`\` is required to connect to \`\`geth --dev\`\` and may also be needed for other EVM compatible blockchains like Polygon or BNB Chain (Binance Smart Chain). If the middleware is not injected at the 0th layer of the middleware onion, you may get errors like the example below when interacting with your EVM node. .. code-block:: shell web3.exceptions.ExtraDataLengthError: The field extraData is 97 bytes, but should be 32. It is quite likely that you are connected to a POA chain. Refer to http://web3py.readthedocs.io/en/stable/middleware.html#proof-of-authority for more details. The full extraData is: HexBytes('...') The easiest way to connect to a default \`\`geth --dev\`\` instance which loads the middleware is: .. code-block:: python >>> from web3.auto.gethdev import w3 # confirm that the connection succeeded >>> w3.client\_version 'Geth/v1.14.12-stable-4bb3c89d/linux-amd64/go1.22.4' This example connects to a local \`\`geth --dev\`\` instance on Linux with a unique IPC location and loads the middleware: .. code-block:: python >>> from web3 import Web3, IPCProvider # connect to the IPC location started with 'geth --dev --datadir ~/mynode' >>> w3 = Web3(IPCProvider('~/mynode/geth.ipc')) >>> from web3.middleware import ExtraDataToPOAMiddleware # inject the poa compatibility middleware to the innermost layer (0th layer) >>> w3.middleware\_onion.inject(ExtraDataToPOAMiddleware, layer=0) # confirm that the connection succeeded >>> w3.client\_version 'Geth/v1.14.12-stable-4bb3c89d/linux-amd64/go1.22.4' Why is \`\`ExtraDataToPOAMiddleware\`\` necessary? '''''''''''''''''''''''''''''''''''''''''''''' There is no strong community consensus on a single Proof-of-Authority (PoA) standard yet. Some nodes have successful experiments running though. One is go-ethereum (geth), which uses a prototype PoA for its development mode and the Goerli test network. Unfortunately, it does deviate from the yellow paper specification, which constrains the \`\`extraData\`\` field in each block to a maximum of 32-bytes. Geth is one such example where PoA uses more than 32 bytes, so this middleware modifies the block data a bit before returning it. .. \_local-filter: Locally Managed Log and Block Filters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:method:: web3.middleware.LocalFilterMiddleware This middleware provides an alternative to ethereum node managed filters. When used, Log and Block filter logic are handled locally while using the same web3 filter api. Filter results are retrieved using JSON-RPC endpoints that don't rely on server state. .. doctest:: >>> from web3 import Web3, EthereumTesterProvider >>> w3 = Web3(EthereumTesterProvider()) >>> from web3.middleware import LocalFilterMiddleware >>> w3.middleware\_onion.add(LocalFilterMiddleware) .. code-block:: python # Normal block and log filter apis behave as before. >>> block\_filter = w3.eth.filter("latest") >>> log\_filter = myContract.events.myEvent.build\_filter().deploy() Signing ~~~~~~~ .. py:method:: web3.middleware.SignAndSendRawMiddlewareBuilder This middleware automatically captures transactions, signs them, and sends them as raw transactions. The \`\`from\`\` field on the transaction, or \`\`w3.eth.default\_account\`\` must be set to the address of the private key for this middleware to have any effect. The \`\`build\`\` method for this middleware builder takes a single argument: \* \`\`private\_key\_or\_account\`\` A single private key or a tuple, list or set of private keys. Keys can be in any of the following formats: \* An \`\`eth\_account.LocalAccount\`\` object \* An \`\`eth\_keys.PrivateKey\`\` object \* A raw private key as a hex string or byte string .. important:: Since this middleware signs transactions, it must always run after any middleware that modifies the transaction. Therefore, it is recommended to inject the signing middleware at the 0th layer of the middleware onion using \`\`w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(...), layer=0)\`\`. Ensure that any transaction-modifying middleware exists in a higher layer within the onion so that it runs before the signing middleware. .. note:: If used with \`\`ExtraDataToPOAMiddleware\`\`, the injection order doesn't matter, as the \`\`extraData\`\` field isn't involved in transaction signing. The key is ensuring \`\`SignAndSendRawMiddlewareBuilder\`\` runs after any middleware that modifies the transaction. .. code-block:: python >>> from web3 import Web3, EthereumTesterProvider >>> w3 = Web3(EthereumTesterProvider) >>> from web3.middleware import SignAndSendRawMiddlewareBuilder >>> from eth\_account import Account >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530') >>> w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(acct), layer=0) >>> w3.eth.default\_account = acct.address :ref:\`Hosted nodes\` (like Infura or Alchemy) only support signed transactions. This often results in \`\`send\_raw\_transaction\`\` being used repeatedly. Instead, we can automate this process with \`\`SignAndSendRawMiddlewareBuilder.build(private\_key\_or\_account)\`\`. .. code-block:: python >>> from web3 import Web3 >>> w3 = Web3(Web3.HTTPProvider('HTTP\_ENDPOINT')) >>> from web3.middleware import SignAndSendRawMiddlewareBuilder >>> from eth\_account import Account >>> import os >>> acct = w3.eth.account.from\_key(os.environ.get('PRIVATE\_KEY')) >>> w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(acct), layer=0) >>> w3.eth.default\_account = acct.address >>> # use \`eth\_sendTransaction\` to automatically sign and send the raw transaction >>> w3.eth.send\_transaction(tx\_dict) HexBytes('0x09511acf75918fd03de58141d2fd409af4fd6d3dce48eb3aa1656c8f3c2c5c21') Similarly, with AsyncWeb3: .. code-block:: python >>> from web3 import AsyncWeb3 >>> async\_w3 = AsyncWeb3(AsyncHTTPProvider('HTTP\_ENDPOINT')) >>> from web3.middleware import SignAndSendRawMiddlewareBuilder >>> 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 >>> # use \`eth\_sendTransaction\` to automatically sign and send the raw transaction >>> await async\_w3.eth.send\_transaction(tx\_dict) HexBytes('0x09511acf75918fd03de58141d2fd409af4fd6d3dce48eb3aa1656c8f3c2c5c21') Now you can send a transaction from acct.address without having to build and sign each raw transaction. When making use of this signing middleware, when sending dynamic fee transactions (recommended over legacy transactions), the transaction \`\`type\`\` of \`\`2\`\` (or \`\`'0x2'\`\`) is necessary. This is because transaction signing is validated based on the transaction \`\`type\`\` parameter. This value defaults to \`\`'0x2'\`\` when \`\`maxFeePerGas\`\` and / or \`\`maxPriorityFeePerGas\`\` are present as parameters in the transaction as these params imply a dynamic fee transaction. Since these values effectively replace the legacy \`\`gasPrice\`\` value, do not set a \`\`gasPrice\`\` for dynamic fee transactions. Doing so will lead to validation issues. .. code-block:: python # dynamic fee transaction, introduced by EIP-1559: >>> dynamic\_fee\_transaction = { ... 'type': '0x2', # optional - defaults to '0x2' when dynamic fee transaction params are present ... 'from': acct.address, # optional if w3.eth.default\_account was set with acct.address ... 'to': receiving\_account\_address, ... 'value': 22, ... 'maxFeePerGas': 2000000000, # required for dynamic fee transactions ... 'maxPriorityFeePerGas': 1000000000, # required for dynamic fee transactions ... } >>> w3.eth.send\_transaction(dynamic\_fee\_transaction) A legacy transaction still works in the same way as it did before EIP-1559 was introduced: .. code-block:: python >>> legacy\_transaction = { ... 'to': receiving\_account\_address, ... 'value': 22, ... 'gasPrice': 123456, # optional - if not provided, gas\_price\_strategy (if exists) or eth\_gasPrice is used ... } >>> w3.eth.send\_transaction(legacy\_transaction) Creating Custom Middleware -------------------------- To write your own middleware, create a class and extend from the base \`\`Web3Middleware\`\` class, then override only the parts of the middleware that make sense for your use case. .. note:: The Middleware API borrows from the Django middleware API introduced in version 1.10.0. If all you need is to modify the params before a request is made, you can override the \`\`request\_processor\`\` method, make the necessary tweaks to the params, and pass the arguments to the next element in the middleware stack. Need to do some processing on the response? Override the \`\`response\_processor\`\` method and return the modified response. The pattern: .. code-block:: python from web3.middleware import Web3Middleware class CustomMiddleware(Web3Middleware): def request\_processor(self, method, params): # Pre-request processing goes here before passing to the next middleware. return (method, params) def response\_processor(self, method, response): # Response processing goes here before passing to the next middleware. return response # If your provider is asynchronous, override the async methods instead: async def async\_request\_processor(self, method, params): # Pre-request processing goes here before passing to the next middleware. return (method, params) async def async\_response\_processor(self, method, response): # Response processing goes here before passing to the next middleware. return response If you wish to prevent making a call under certain conditions, you can override the \`\`wrap\_make\_request\`\` method. This allows for defining pre-request processing, skipping or making the request under certain conditions, as well as response processing before passing it to the next middleware. .. code-block:: python from web3.middleware import Web3Middleware class CustomMiddleware(Web3Middleware): def wrap\_make\_request(self, make\_request): def middleware(method, params): # pre-request processing goes here response = make\_request(method, params) # make the request # response processing goes here return response return middleware # If your provider is asynchronous, override the async method instead: async def async\_wrap\_make\_request(self, make\_request): async def middleware(method, params): # pre-request processing goes here response = await make\_request(method, params) # response processing goes here return response return middleware Custom middleware can be added to the stack via the class itself, using the :ref:\`middleware\_stack\_api\`. The \`\`name\`\` kwarg is optional. For example: .. code-block:: python from web3 import Web3 from my\_module import ( CustomMiddleware, ) w3 = Web3(HTTPProvider(endpoint\_uri="...")) # add the middleware to the stack as the class w3.middleware\_onion.add(CustomMiddleware, name="custom\_middleware") --- # Beacon API — web3.py 7.6.1 documentation * [](index.html) * Beacon API * [View page source](_sources/web3.beacon.rst.txt) * * * Beacon API[](#beacon-api "Link to this heading") ================================================== Warning This API Is experimental. Client support is incomplete and the API itself is still evolving. To use this API, you’ll need a beacon node running locally or remotely. To set that up, refer to the documentation of your specific client. Once you have a running beacon node, import and configure your beacon instance: \>>> from web3.beacon import Beacon \>>> beacon \= Beacon("http://localhost:5051") Methods[](#methods "Link to this heading") -------------------------------------------- Beacon.get\_genesis()[](#Beacon.get_genesis "Link to this definition") \>>> beacon.get\_genesis() { 'data': { 'genesis\_time': '1605700807', 'genesis\_validators\_root': '0x9436e8a630e3162b7ed4f449b12b8a5a368a4b95bc46b941ae65c11613bfa4c1', 'genesis\_fork\_version': '0x00002009' } } Beacon.get\_hash\_root(_state\_id\='head'_)[](#Beacon.get_hash_root "Link to this definition") \>>> beacon.get\_hash\_root() { "data": { "root":"0xbb399fda70617a6f198b3d9f1c1cdbd70077677231b84f34e58568c9dc903558" } } Beacon.get\_fork\_data(_state\_id\='head'_)[](#Beacon.get_fork_data "Link to this definition") \>>> beacon.get\_fork\_data() { 'data': { 'previous\_version': '0x00002009', 'current\_version': '0x00002009', 'epoch': '0' } } Beacon.get\_finality\_checkpoint(_state\_id\='head'_)[](#Beacon.get_finality_checkpoint "Link to this definition") \>>> beacon.get\_finality\_checkpoint() { 'data': { 'previous\_justified': { 'epoch': '5024', 'root': '0x499ba555e8e8be639dd84be1be6d54409738facefc662f37d97065aa91a1a8d4' }, 'current\_justified': { 'epoch': '5025', 'root': '0x34e8a230f11536ab2ec56a0956e1f3b3fd703861f96d4695877eaa48fbacc241' }, 'finalized': { 'epoch': '5024', 'root': '0x499ba555e8e8be639dd84be1be6d54409738facefc662f37d97065aa91a1a8d4' } } } Beacon.get\_validators(_state\_id\='head'_)[](#Beacon.get_validators "Link to this definition") \>>> beacon.get\_validators() { 'data': \[\ {\ 'index': '110280',\ 'balance': '32000000000',\ 'status': 'pending\_queued',\ 'validator': {\ 'pubkey': '0x99d37d1f7dd15859995330f75c158346f86d298e2ffeedfbf1b38dcf3df89a7dbd1b34815f3bcd1b2a5588592a35b783',\ 'withdrawal\_credentials': '0x00f338cfdb0c22bb85beed9042bd19fff58ad6421c8a833f8bc902b7cca06f5f',\ 'effective\_balance': '32000000000',\ 'slashed': False,\ 'activation\_eligibility\_epoch': '5029',\ 'activation\_epoch': '18446744073709551615',\ 'exit\_epoch': '18446744073709551615',\ 'withdrawable\_epoch': '18446744073709551615'\ }\ },\ ...\ \] } Beacon.get\_validator(_validator\_id_, _state\_id\='head'_)[](#Beacon.get_validator "Link to this definition") \>>> beacon.get\_validator(110280) { 'data': { 'index': '110280', 'balance': '32000000000', 'status': 'pending\_queued', 'validator': { 'pubkey': '0x99d37d1f7dd15859995330f75c158346f86d298e2ffeedfbf1b38dcf3df89a7dbd1b34815f3bcd1b2a5588592a35b783', 'withdrawal\_credentials': '0x00f338cfdb0c22bb85beed9042bd19fff58ad6421c8a833f8bc902b7cca06f5f', 'effective\_balance': '32000000000', 'slashed': False, 'activation\_eligibility\_epoch': '5029', 'activation\_epoch': '18446744073709551615', 'exit\_epoch': '18446744073709551615', 'withdrawable\_epoch': '18446744073709551615' } } } Beacon.get\_validator\_balances(_state\_id\='head'_)[](#Beacon.get_validator_balances "Link to this definition") \>>> beacon.get\_validator\_balances() { 'data': \[\ {\ 'index': '110278',\ 'balance': '32000000000'\ },\ ...\ \] } Beacon.get\_epoch\_committees(_state\_id\='head'_)[](#Beacon.get_epoch_committees "Link to this definition") \>>> beacon.get\_epoch\_committees() { 'data': \[\ {\ 'slot': '162367',\ 'index': '25',\ 'validators': \['50233', '36829', '84635', ...\],\ },\ ...\ \] } Beacon.get\_block\_headers()[](#Beacon.get_block_headers "Link to this definition") \>>> beacon.get\_block\_headers() { 'data': \[\ {\ 'root': '0xa3873e7b1e0bcc7c59013340cfea59dff16e42e79825e7b8ab6c243dbafd4fe0',\ 'canonical': True,\ 'header': {\ 'message': {\ 'slot': '163587',\ 'proposer\_index': '69198',\ 'parent\_root': '0xc32558881dbb791ef045c48e3709a0978dc445abee4ae34d30df600eb5fbbb3d',\ 'state\_root': '0x4dc0a72959803a84ee0231160b05dda76a91b8f8b77220b4cfc7db160840b8a8',\ 'body\_root': '0xa3873e7b1e0bcc7c59013340cfea59dff16e42e79825e7b8ab6c243dbafd4fe0'\ },\ 'signature': '0x87b549448d36e5e8b1783944b5511a05f34bb78ad3fcbf71a1adb346eed363d46e50d51ac53cd23bd03d0107d064e05913a6ef10f465f9171aba3b2b8a7a4d621c9e18d5f148813295a2d5aa5053029ccbd88cec72130833de2b4b7addf7faca'\ }\ }\ \] } Beacon.get\_block\_header(_block\_id_)[](#Beacon.get_block_header "Link to this definition") \>>> 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' } } } Beacon.get\_block(_block\_id_)[](#Beacon.get_block "Link to this definition") \>>> beacon.get\_block(1) { 'data': { 'message': { 'slot': '1', 'proposer\_index': '61090', 'parent\_root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87', 'state\_root': '0x7773ed5a7e944c6238cd0a5c32170663ef2be9efc594fb43ad0f07ecf4c09d2b', 'body': { 'randao\_reveal': '0x8e245a52a0a680fcfe789013e123880c321f237de10cad108dc55dd47290d7cfe50cdaa003c6f783405efdac48cef44e152493abba40d9f9815a060dd6151cb0635906c9e3c1ad4859cada73ccd2d6b8747e4aeeada7d75d454bcc8672afa813', 'eth1\_data': { 'deposit\_root': '0x4e910ac762815c13e316e72506141f5b6b441d58af8e0a049cd3341c25728752', 'deposit\_count': '100596', 'block\_hash': '0x89cb78044843805fb4dab8abd743fc96c2b8e955c58f9b7224d468d85ef57130' }, 'graffiti': '0x74656b752f76302e31322e31342b34342d673863656562663600000000000000', 'proposer\_slashings': \[\], 'attester\_slashings': \[\], 'attestations': \[\ {\ 'aggregation\_bits': '0x0080020004000000008208000102000905',\ 'data': {\ 'slot': '0',\ 'index': '7',\ 'beacon\_block\_root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87',\ 'source': {\ 'epoch': '0',\ 'root': '0x0000000000000000000000000000000000000000000000000000000000000000'\ },\ 'target': {\ 'epoch': '0',\ 'root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87'\ }\ },\ 'signature': '0x967dd2946358db7e426ed19d4576bc75123520ef6a489ca50002222070ee4611f9cef394e5e3071236a93b825f18a4ad07f1d5a1405e6c984f1d71e03f535d13a2156d6ba22cb0c2b148df23a7b8a7293315d6e74b9a26b64283e8393f2ad4c5'\ }\ \], 'deposits': \[\], 'voluntary\_exits': \[\] } }, 'signature': '0xa30d70b3e62ff776fe97f7f8b3472194af66849238a958880510e698ec3b8a470916680b1a82f9d4753c023153fbe6db10c464ac532c1c9c8919adb242b05ef7152ba3e6cd08b730eac2154b9802203ead6079c8dfb87f1e900595e6c00b4a9a' } } Beacon.get\_block\_root(_block\_id_)[](#Beacon.get_block_root "Link to this definition") \>>> beacon.get\_block\_root(1) { 'data': { 'root': '0x30c04689dd4f6cd4d56eb78f72727d2d16d8b6346724e4a88f546875f11b750d' } } Beacon.get\_block\_attestations(_block\_id_)[](#Beacon.get_block_attestations "Link to this definition") \>>> beacon.get\_block\_attestations(1) { 'data': \[\ {\ 'aggregation\_bits': '0x0080020004000000008208000102000905',\ 'data': {\ 'slot': '0',\ 'index': '7',\ 'beacon\_block\_root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87',\ 'source': {\ 'epoch': '0',\ 'root': '0x0000000000000000000000000000000000000000000000000000000000000000'\ },\ 'target': {\ 'epoch': '0',\ 'root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87'\ }\ },\ 'signature': '0x967dd2946358db7e426ed19d4576bc75123520ef6a489ca50002222070ee4611f9cef394e5e3071236a93b825f18a4ad07f1d5a1405e6c984f1d71e03f535d13a2156d6ba22cb0c2b148df23a7b8a7293315d6e74b9a26b64283e8393f2ad4c5'\ },\ ...\ \] } Beacon.get\_attestations()[](#Beacon.get_attestations "Link to this definition") \>>> beacon.get\_attestations() {'data': \[\]} Beacon.get\_attester\_slashings()[](#Beacon.get_attester_slashings "Link to this definition") \>>> beacon.get\_attester\_slashings() {'data': \[\]} Beacon.get\_proposer\_slashings()[](#Beacon.get_proposer_slashings "Link to this definition") \>>> beacon.get\_proposer\_slashings() {'data': \[\]} Beacon.get\_voluntary\_exits()[](#Beacon.get_voluntary_exits "Link to this definition") \>>> beacon.get\_voluntary\_exits() {'data': \[\]} Beacon.get\_fork\_schedule()[](#Beacon.get_fork_schedule "Link to this definition") \>>> beacon.get\_fork\_schedule() { 'data': \[\ {\ 'previous\_version': '0x00002009',\ 'current\_version': '0x00002009',\ 'epoch': '0'\ }\ \] } Beacon.get\_spec()[](#Beacon.get_spec "Link to this definition") \>>> beacon.get\_spec() { 'data': { 'DEPOSIT\_CONTRACT\_ADDRESS': '0x8c5fecdC472E27Bc447696F431E425D02dd46a8c', 'MIN\_ATTESTATION\_INCLUSION\_DELAY': '1', 'SLOTS\_PER\_EPOCH': '32', 'SHUFFLE\_ROUND\_COUNT': '90', 'MAX\_EFFECTIVE\_BALANCE': '32000000000', 'DOMAIN\_BEACON\_PROPOSER': '0x00000000', 'MAX\_ATTESTER\_SLASHINGS': '2', 'DOMAIN\_SELECTION\_PROOF': '0x05000000', ... } } Beacon.get\_deposit\_contract()[](#Beacon.get_deposit_contract "Link to this definition") \>>> beacon.get\_deposit\_contract() { 'data': { 'chain\_id': '5', 'address': '0x8c5fecdC472E27Bc447696F431E425D02dd46a8c' } } Beacon.get\_beacon\_state(_state\_id\='head'_)[](#Beacon.get_beacon_state "Link to this definition") \>>> beacon.get\_beacon\_state() { 'data': { 'genesis\_time': '1', 'genesis\_validators\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'slot': '1', 'fork': { 'previous\_version': '0x00000000', 'current\_version': '0x00000000', 'epoch': '1' }, 'latest\_block\_header': { 'slot': '1', 'proposer\_index': '1', 'parent\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'state\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'body\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2' }, 'block\_roots': \['0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2'\], 'state\_roots': \['0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2'\], 'historical\_roots': \['0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2'\], 'eth1\_data': { 'deposit\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'deposit\_count': '1', 'block\_hash': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2' }, 'eth1\_data\_votes': \[...\], 'eth1\_deposit\_index': '1', 'validators': \[...\], 'balances': \[...\], 'randao\_mixes': \[...\], 'slashings': \[...\], 'previous\_epoch\_attestations': \[...\], 'current\_epoch\_attestations': \[...\], 'justification\_bits': '0x0f', 'previous\_justified\_checkpoint': { 'epoch': '5736', 'root': '0xec7ef54f1fd81bada8170dd0cb6be8216f8ee2f445e6936f95f5c6894a4a3b38' }, 'current\_justified\_checkpoint': { 'epoch': '5737', 'root': '0x781f0166e34c361ce2c88070c1389145abba2836edcb446338a2ca2b0054826e' }, 'finalized\_checkpoint': { 'epoch': '5736', 'root': '0xec7ef54f1fd81bada8170dd0cb6be8216f8ee2f445e6936f95f5c6894a4a3b38' } } } Beacon.get\_beacon\_heads()[](#Beacon.get_beacon_heads "Link to this definition") \>>> beacon.get\_beacon\_heads() { 'data': \[\ {\ 'slot': '221600',\ 'root': '0x9987754077fe6100a60c75d81a51b1ef457d019404d1546a66f4f5d6c23fae45'\ }\ \] } Beacon.get\_blob\_sidecars(_block\_id_, _indices\=\[\]_)[](#Beacon.get_blob_sidecars "Link to this definition") \>>> beacon.get\_blob\_sidecars(1, indices\=\[1\]) { "data": \[\ {\ "index": "1",\ "blob": ..., # ommitted\ "kzg\_commitment": "0x93247f2209abcacf57b75a51dafae777f9dd38bc7053d1af526f220a7489a6d3a2753e5f3e8b1cfe39b56f43611df74a",\ "kzg\_proof": "0x7FB0A12D11Ffe8A48c2fF80dCA17adbCC1da5F6aADaAEF2b338717dcDEECf6DaB9FD7C4e4265CfBc097cD31dCB19E836",\ "signed\_block\_header": {\ "message": {\ "slot": "1",\ "proposer\_index": "1",\ "parent\_root": "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "state\_root": "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "body\_root": "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2"\ },\ "signature": "0x1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505cc411d61252fb6cb3fa0017b679f8bb2305b26a285fa2737f175668d0dff91cc1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505"\ },\ "kzg\_commitment\_inclusion\_proof": \[\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2",\ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2"\ \]\ }\ \] } Beacon.get\_node\_identity()[](#Beacon.get_node_identity "Link to this definition") \>>> beacon.get\_node\_identity() { 'data': { 'peer\_id': '16Uiu2HAmLZ1CYVFKpa3wwn4cnknZqosum8HX3GHDhUpEULQc9ixE', 'enr': 'enr:-KG4QCIp6eCZ6hG\_fd93qsw12qmbfsl2rUTfQvwVP4FOTlWeNXYo0Gg9y3WVYIdF6FQC6R0E8CbK0Ywq\_6TKMx1BpGlAhGV0aDKQOwiHlQAAIAn\_\_\_\_\_\_\_\_\_\_4JpZIJ2NIJpcIR\_AAABiXNlY3AyNTZrMaEDdVT4g1gw86BfbrtLCq2fRBlG0AnMxsXtAQgA327S5FeDdGNwgiMog3VkcIIjKA', 'p2p\_addresses': \['/ip4/127.0.0.1/tcp/9000/p2p/16Uiu2HAmLZ1CYVFKpa3wwn4cnknZqosum8HX3GHDhUpEULQc9ixE'\], 'discovery\_addresses': \['/ip4/127.0.0.1/udp/9000/p2p/16Uiu2HAmLZ1CYVFKpa3wwn4cnknZqosum8HX3GHDhUpEULQc9ixE'\], 'metadata': {'seq\_number': '0', 'attnets': '0x0000000000000000'} } } Beacon.get\_peers()[](#Beacon.get_peers "Link to this definition") \>>> beacon.get\_peers() { 'data': \[\ {\ 'peer\_id': '16Uiu2HAkw1yVqF3RtMCBHMbkLZbNhfGcTUdD6Uo4X3wfzPhGVnqv',\ 'address': '/ip4/3.127.23.51/tcp/9000',\ 'state': 'connected',\ 'direction': 'outbound'\ },\ {\ 'peer\_id': '16Uiu2HAmEJHiCzgS8GwiEYLyM3d148mzvZ9iZzsz8yqayWVPANMG',\ 'address': '/ip4/3.88.7.240/tcp/9000',\ 'state': 'connected',\ 'direction': 'outbound'\ }\ \] } Beacon.get\_peer(_peer\_id_)[](#Beacon.get_peer "Link to this definition") \>>> beacon.get\_peer('16Uiu2HAkw1yVqF3RtMCBHMbkLZbNhfGcTUdD6Uo4X3wfzPhGVnqv') { 'data': { 'peer\_id': '16Uiu2HAkw1yVqF3RtMCBHMbkLZbNhfGcTUdD6Uo4X3wfzPhGVnqv', 'address': '/ip4/3.127.23.51/tcp/9000', 'state': 'connected', 'direction': 'outbound' } } Beacon.get\_health()[](#Beacon.get_health "Link to this definition") \>>> beacon.get\_health() 200 Beacon.get\_version()[](#Beacon.get_version "Link to this definition") \>>> beacon.get\_version() { 'data': { 'version': 'teku/v20.12.0+9-g9392008/osx-x86\_64/adoptopenjdk-java-15' } } Beacon.get\_syncing()[](#Beacon.get_syncing "Link to this definition") \>>> beacon.get\_syncing() { 'data': { 'head\_slot': '222270', 'sync\_distance': '190861' } } --- # Geth API — web3.py 7.6.1 documentation * [](index.html) * Geth API * [View page source](_sources/web3.geth.rst.txt) * * * Geth API[](#module-web3.geth "Link to this heading") ====================================================== The `web3.geth` object exposes modules that enable you to interact with the JSON-RPC endpoints supported by [Geth](https://github.com/ethereum/go-ethereum/wiki/Management-APIs) that are not defined in the standard set of Ethereum JSONRPC endpoints according to [EIP 1474](https://github.com/ethereum/EIPs/pull/1474) . GethAdmin API[](#gethadmin-api "Link to this heading") -------------------------------------------------------- The following methods are available on the `web3.geth.admin` namespace. The `web3.geth.admin` object exposes methods to interact with the RPC APIs under the `admin_` namespace that are supported by the Geth client. web3.geth.admin.datadir()[](#web3.geth.admin.datadir "Link to this definition") * Delegates to `admin_datadir` RPC Method Returns the system path of the node’s data directory. \>>> web3.geth.admin.datadir() '/Users/snakecharmers/Library/Ethereum' web3.geth.admin.node\_info()[](#web3.geth.admin.node_info "Link to this definition") * Delegates to `admin_nodeInfo` RPC Method Returns information about the currently running node. \>>> web3.geth.admin.node\_info() { 'enode': 'enode://e54eebad24dce1f6d246bea455ffa756d97801582420b9ed681a2ea84bf376d0bd87ae8dd6dc06cdb862a2ca89ecabe1be1050be35b4e70d62bc1a092cb7e2d3@\[::\]:30303', 'id': 'e54eebad24dce1f6d246bea455ffa756d97801582420b9ed681a2ea84bf376d0bd87ae8dd6dc06cdb862a2ca89ecabe1be1050be35b4e70d62bc1a092cb7e2d3', 'ip': '::', 'listenAddr': '\[::\]:30303', 'name': 'Geth/v1.4.11-stable-fed692f6/darwin/go1.7', 'ports': {'discovery': 30303, 'listener': 30303}, 'protocols': { 'eth': { 'difficulty': 57631175724744612603, 'genesis': '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3', 'head': '0xaaef6b9dd0d34088915f4c62b6c166379da2ad250a88f76955508f7cc81fb796', 'network': 1, }, }, } web3.geth.admin.peers()[](#web3.geth.admin.peers "Link to this definition") * Delegates to `admin_peers` RPC Method Returns the current peers the node is connected to. \>>> web3.geth.admin.peers() \[\ {\ 'caps': \['eth/63'\],\ 'id': '146e8e3e2460f1e18939a5da37c4a79f149c8b9837240d49c7d94c122f30064e07e4a42ae2c2992d0f8e7e6f68a30e7e9ad31d524349ec9d17effd2426a37b40',\ 'name': 'Geth/v1.4.10-stable/windows/go1.6.2',\ 'network': {\ 'localAddress': '10.0.3.115:64478',\ 'remoteAddress': '72.208.167.127:30303',\ },\ 'protocols': {\ 'eth': {\ 'difficulty': 17179869184,\ 'head': '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3',\ 'version': 63,\ },\ }\ },\ {\ 'caps': \['eth/62', 'eth/63'\],\ 'id': '76cb6cd3354be081923a90dfd4cda40aa78b307cc3cf4d5733dc32cc171d00f7c08356e9eb2ea47eab5aad7a15a3419b859139e3f762e1e1ebf5a04f530dcef7',\ 'name': 'Geth/v1.4.10-stable-5f55d95a/linux/go1.5.1',\ 'network': {\ 'localAddress': '10.0.3.115:64784',\ 'remoteAddress': '60.205.92.119:30303',\ },\ 'protocols': {\ 'eth': {\ 'difficulty': 57631175724744612603,\ 'head': '0xaaef6b9dd0d34088915f4c62b6c166379da2ad250a88f76955508f7cc81fb796',\ 'version': 63,\ },\ },\ },\ ...\ \] web3.geth.admin.add\_peer(_node\_url_)[](#web3.geth.admin.add_peer "Link to this definition") * Delegates to `admin_addPeer` RPC Method Requests adding a new remote node to the list of tracked static nodes. \>>> web3.geth.admin.add\_peer('enode://e54eebad24dce1f6d246bea455ffa756d97801582420b9ed681a2ea84bf376d0bd87ae8dd6dc06cdb862a2ca89ecabe1be1050be35b4e70d62bc1a092cb7e2d3@52.71.255.237:30303') True web3.geth.admin.start\_http(_host\='localhost'_, _port\=8545_, _cors\=''_, _apis\='eth,net,web3'_)[](#web3.geth.admin.start_http "Link to this definition") * 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. \>>> web3.geth.admin.start\_http() True web3.geth.admin.start\_ws(_host\='localhost'_, _port\=8546_, _cors\=''_, _apis\='eth,net,web3'_)[](#web3.geth.admin.start_ws "Link to this definition") * 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. \>>> web3.geth.admin.start\_ws() True web3.geth.admin.stop\_http()[](#web3.geth.admin.stop_http "Link to this definition") * Delegates to `admin_stopHTTP` RPC Method Stops the HTTP based JSON RPC server. \>>> web3.geth.admin.stop\_http() True web3.geth.admin.stop\_ws()[](#web3.geth.admin.stop_ws "Link to this definition") * Delegates to `admin_stopWS` RPC Method Stops the WebSocket based JSON RPC server. \>>> web3.geth.admin.stop\_ws() True GethTxPool API[](#gethtxpool-api "Link to this heading") ---------------------------------------------------------- The `web3.geth.txpool` object exposes methods to interact with the RPC APIs under the `txpool_` namespace. These methods are only exposed under the `geth` namespace since they are not standard. The following methods are available on the `web3.geth.txpool` namespace. TxPool.inspect()[](#web3.geth.txpool.TxPool.inspect "Link to this definition") * Delegates to `txpool_inspect` RPC Method Returns a textual summary of all transactions currently pending for inclusion in the next block(s) as well as ones that are scheduled for future execution. \>>> web3.geth.txpool.inspect() { 'pending': { '0x26588a9301b0428d95e6Fc3A5024fcE8BEc12D51': { 31813: \["0x3375Ee30428b2A71c428afa5E89e427905F95F7e: 0 wei + 500000 × 20000000000 gas"\] }, '0x2a65Aca4D5fC5B5C859090a6c34d164135398226': { 563662: \["0x958c1Fa64B34db746925c6F8a3Dd81128e40355E: 1051546810000000000 wei + 90000 × 20000000000 gas"\], 563663: \["0x77517B1491a0299A44d668473411676f94e97E34: 1051190740000000000 wei + 90000 × 20000000000 gas"\], 563664: \["0x3E2A7Fe169c8F8eee251BB00d9fb6d304cE07d3A: 1050828950000000000 wei + 90000 × 20000000000 gas"\], 563665: \["0xAF6c4695da477F8C663eA2D8B768Ad82Cb6A8522: 1050544770000000000 wei + 90000 × 20000000000 gas"\], 563666: \["0x139B148094C50F4d20b01cAf21B85eDb711574dB: 1048598530000000000 wei + 90000 × 20000000000 gas"\], 563667: \["0x48B3Bd66770b0D1EeceFCe090daFeE36257538aE: 1048367260000000000 wei + 90000 × 20000000000 gas"\], 563668: \["0x468569500925D53e06Dd0993014aD166fD7Dd381: 1048126690000000000 wei + 90000 × 20000000000 gas"\], 563669: \["0x3DcB4C90477a4b8Ff7190b79b524773CbE3bE661: 1047965690000000000 wei + 90000 × 20000000000 gas"\], 563670: \["0x6DfeF5BC94b031407FFe71ae8076CA0FbF190963: 1047859050000000000 wei + 90000 × 20000000000 gas"\] }, '0x9174E688d7dE157C5C0583Df424EAAB2676aC162': { 3: \["0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413: 30000000000000000000 wei + 85000 × 21000000000 gas"\] }, '0xb18F9d01323e150096650ab989CfecD39D757Aec': { 777: \["0xcD79c72690750F079ae6AB6ccd7e7aEDC03c7720: 0 wei + 1000000 × 20000000000 gas"\] }, '0xB2916C870Cf66967B6510B76c07E9d13a5D23514': { 2: \["0x576f25199D60982A8f31A8DfF4da8aCB982e6ABa: 26000000000000000000 wei + 90000 × 20000000000 gas"\] }, '0xBc0CA4f217E052753614d6B019948824d0d8688B': { 0: \["0x2910543Af39abA0Cd09dBb2D50200b3E800A63D2: 1000000000000000000 wei + 50000 × 1171602790622 gas"\] }, '0xea674fdde714fd979de3edf0f56aa9716b898ec8': { 70148: \["0xe39c55ead9f997f7fa20ebe40fb4649943d7db66: 1000767667434026200 wei + 90000 × 20000000000 gas"\] } }, 'queued': { '0x0F6000De1578619320aBA5e392706b131FB1dE6f': { 6: \["0x8383534d0bcd0186d326C993031311c0Ac0D9B2d: 9000000000000000000 wei + 21000 × 20000000000 gas"\] }, '0x5b30608c678e1ac464A8994C3B33E5CdF3497112': { 6: \["0x9773547e27f8303C87089dc42D9288aa2B9d8F06: 50000000000000000000 wei + 90000 × 50000000000 gas"\] }, '0x976A3Fc5d6f7d259EBfb4cc2Ae75115475E9867C': { 3: \["0x346FB27dE7E7370008f5da379f74dd49F5f2F80F: 140000000000000000 wei + 90000 × 20000000000 gas"\] }, '0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A': { 2: \["0x24a461f25eE6a318BDef7F33De634A67bb67Ac9D: 17000000000000000000 wei + 90000 × 50000000000 gas"\], 6: \["0x6368f3f8c2B42435D6C136757382E4A59436a681: 17990000000000000000 wei + 90000 × 20000000000 gas", "0x8db7b4e0ecb095fbd01dffa62010801296a9ac78: 16998950000000000000 wei + 90000 × 20000000000 gas"\], 7: \["0x6368f3f8c2B42435D6C136757382E4A59436a681: 17900000000000000000 wei + 90000 × 20000000000 gas"\] } } } TxPool.status()[](#web3.geth.txpool.TxPool.status "Link to this definition") * Delegates to `txpool_status` RPC Method Returns a textual summary of all transactions currently pending for inclusion in the next block(s) as well as ones that are scheduled for future execution. { pending: 10, queued: 7, } TxPool.content()[](#web3.geth.txpool.TxPool.content "Link to this definition") * Delegates to `txpool_content` RPC Method Returns the exact details of all transactions that are pending or queued. \>>> web3.geth.txpool.content() { 'pending': { '0x0216D5032f356960Cd3749C31Ab34eEFF21B3395': { 806: \[{\ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000",\ 'blockNumber': None,\ 'from': "0x0216D5032f356960Cd3749C31Ab34eEFF21B3395",\ 'gas': "0x5208",\ 'gasPrice': None,\ 'hash': "0xaf953a2d01f55cfe080c0c94150a60105e8ac3d51153058a1f03dd239dd08586",\ 'input': "0x",\ 'maxFeePerGas': '0x77359400',\ 'maxPriorityFeePerGas': '0x3b9aca00',\ 'nonce': "0x326",\ 'to': "0x7f69a91A3CF4bE60020fB58B893b7cbb65376db8",\ 'transactionIndex': None,\ 'value': "0x19a99f0cf456000"\ }\] }, '0x24d407e5A0B506E1Cb2fae163100B5DE01F5193C': { 34: \[{\ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000",\ 'blockNumber': None,\ 'from': "0x24d407e5A0B506E1Cb2fae163100B5DE01F5193C",\ 'gas': "0x44c72",\ 'gasPrice': None,\ 'hash': "0xb5b8b853af32226755a65ba0602f7ed0e8be2211516153b75e9ed640a7d359fe",\ 'input': "0xb61d27f600000000000000000000000024d407e5a0b506e1cb2fae163100b5de01f5193c00000000000000000000000000000000000000000000000053444835ec580000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",\ 'maxFeePerGas': '0x77359400',\ 'maxPriorityFeePerGas': '0x3b9aca00',\ 'nonce': "0x22",\ 'to': "0x7320785200f74861B69C49e4ab32399a71b34f1a",\ 'transactionIndex': None,\ 'value': "0x0"\ }\] } }, 'queued': { '0x976A3Fc5d6f7d259EBfb4cc2Ae75115475E9867C': { 3: \[{\ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000",\ 'blockNumber': None,\ 'from': "0x976A3Fc5d6f7d259EBfb4cc2Ae75115475E9867C",\ 'gas': "0x15f90",\ 'gasPrice': None,\ 'hash': "0x57b30c59fc39a50e1cba90e3099286dfa5aaf60294a629240b5bbec6e2e66576",\ 'input': "0x",\ 'maxFeePerGas': '0x77359400',\ 'maxPriorityFeePerGas': '0x3b9aca00',\ 'nonce': "0x3",\ 'to': "0x346FB27dE7E7370008f5da379f74dd49F5f2F80F",\ 'transactionIndex': None,\ 'value': "0x1f161421c8e0000"\ }\] }, '0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A': { 2: \[{\ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000",\ 'blockNumber': None,\ 'from': "0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A",\ 'gas': "0x15f90",\ 'gasPrice': None,\ 'hash': "0x3a3c0698552eec2455ed3190eac3996feccc806970a4a056106deaf6ceb1e5e3",\ 'input': "0x",\ 'maxFeePerGas': '0x77359400',\ 'maxPriorityFeePerGas': '0x3b9aca00',\ 'nonce': "0x2",\ 'to': "0x24a461f25eE6a318BDef7F33De634A67bb67Ac9D",\ 'transactionIndex': None,\ 'value': "0xebec21ee1da40000"\ }\], 6: \[{\ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000",\ 'blockNumber': None,\ 'from': "0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A",\ 'gas': "0x15f90",\ 'gasPrice': None,\ 'hash': "0xbbcd1e45eae3b859203a04be7d6e1d7b03b222ec1d66dfcc8011dd39794b147e",\ 'input': "0x",\ 'maxFeePerGas': '0x77359400',\ 'maxPriorityFeePerGas': '0x3b9aca00',\ 'nonce': "0x6",\ 'to': "0x6368f3f8c2B42435D6C136757382E4A59436a681",\ 'transactionIndex': None,\ 'value': "0xf9a951af55470000"\ }, {\ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000",\ 'blockNumber': None,\ 'from': "0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A",\ 'gas': "0x15f90",\ 'gasPrice': None,\ 'hash': "0x60803251d43f072904dc3a2d6a084701cd35b4985790baaf8a8f76696041b272",\ 'input': "0x",\ 'maxFeePerGas': '0x77359400',\ 'maxPriorityFeePerGas': '0x3b9aca00',\ 'nonce': "0x6",\ 'to': "0x8DB7b4e0ECB095FBD01Dffa62010801296a9ac78",\ 'transactionIndex': None,\ 'value': "0xebe866f5f0a06000"\ }\], } } } GethDebug API[](#gethdebug-api "Link to this heading") -------------------------------------------------------- The `web3.geth.debug` object exposes methods to interact with the RPC APIs under the `debug_` namespace. These methods are only exposed under the `geth` namespace. Full documentation around options can be found in the [Geth docs](https://geth.ethereum.org/docs/developers/evm-tracing/built-in-tracers) . Debug.trace\_transaction(_transaction\_hash_)[](#web3.geth.debug.Debug.trace_transaction "Link to this definition") * Delegates to `debug_traceTransaction` RPC Method Returns the trace of the transaction with the given `transaction_hash` and `trace_config`. \>>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3') AttributeDict({ 'gas': 21000, 'failed': False, 'returnValue': '', 'structLogs': \[\] }) \>>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3', { "tracer": "prestateTracer", }) AttributeDict({ '0x0000000000000000000000000000000000000000': AttributeDict({'balance': 0}), '0x7fE3e4C21bDE162214B715AabcE05391301e9F5B': AttributeDict({'balance': 115792089237316195423570985008687907853269984665640564039457584007913129639927}), '0x91fe3039271d43d3f8479f60Cc5293Bc8A461b75': AttributeDict({'balance': 0}) }) \>>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3', { "tracer": "prestateTracer", "traceConfig": {"diffMode": True} }) AttributeDict({ 'post': AttributeDict({ '0x0000000000000000000000000000000000000000': AttributeDict({'balance': 63000}), '0xcF888Cc4FAe8a3D774e574Ef8C6a261958287d04': AttributeDict({ 'balance': 115792089237316195423570985008687907853269984665640564039457583959368602105927, 'nonce': 3 }), '0xD2593D3445a9F0f4c776715f5206FBf4CA6A0475': AttributeDict({'balance': 100000})}), 'pre': AttributeDict({ '0x0000000000000000000000000000000000000000': AttributeDict({'balance': 42000}), '0xcF888Cc4FAe8a3D774e574Ef8C6a261958287d04': AttributeDict({ 'balance': 115792089237316195423570985008687907853269984665640564039457583973451623990927, 'nonce': 2 }), '0xD2593D3445a9F0f4c776715f5206FBf4CA6A0475': AttributeDict({'balance': 0}) }) }) \>>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3', { "tracer": "callTracer", "tracerConfig": {"withLog": False}, }) AttributeDict({'calls': \[AttributeDict({'from': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11',\ 'gas': 154003,\ 'gasUsed': 275,\ 'input': HexBytes('0xad5c4648'),\ 'output': HexBytes('0x000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'),\ 'to': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'type': 'STATICCALL'}),\ AttributeDict({'from': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11',\ 'gas': 150633,\ 'gasUsed': 24678,\ 'input': HexBytes('0x095ea7b30000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d000000000000000000000000000000000000007e37be2022c0914b2680000000'),\ 'output': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001'),\ 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B',\ 'type': 'CALL',\ 'value': 0}),\ AttributeDict({'calls': \[AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'gas': 121167,\ 'gasUsed': 27504,\ 'input': HexBytes('0x23b872dd000000000000000000000000a0457775a08b175cbb444ed923556dc67ec5dc1100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d000000000000000000000000000000000000007e37be2022c0914b2680000000'),\ 'output': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001'),\ 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B',\ 'type': 'CALL',\ 'value': 0}),\ AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'gas': 89911,\ 'gasUsed': 2504,\ 'input': HexBytes('0x0902f1ac'),\ 'output': HexBytes('0x00000000000000000000000000000000000000000000000053f54ccde429ceb70000000000000000000000000000000000000000001635eb93ecdb339a7dc022000000000000000000000000000000000000000000000000000000006641f6cf'),\ 'to': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d',\ 'type': 'STATICCALL'}),\ AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'gas': 86926,\ 'gasUsed': 621,\ 'input': HexBytes('0x70a0823100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d'),\ 'output': HexBytes('0x000000000000000000000000000000000000007e37d4560e547e265a1a7dc022'),\ 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B',\ 'type': 'STATICCALL'}),\ AttributeDict({'calls': \[AttributeDict({'from': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d',\ 'gas': 70279,\ 'gasUsed': 29962,\ 'input': HexBytes('0xa9059cbb0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d00000000000000000000000000000000000000000000000053f53dfc545d56a6'),\ 'output': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001'),\ 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\ 'type': 'CALL',\ 'value': 0}),\ AttributeDict({'from': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d',\ 'gas': 40164,\ 'gasUsed': 534,\ 'input': HexBytes('0x70a0823100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d'),\ 'output': HexBytes('0x00000000000000000000000000000000000000000000000000000ed18fcc7811'),\ 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\ 'type': 'STATICCALL'}),\ AttributeDict({'from': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d',\ 'gas': 39233,\ 'gasUsed': 621,\ 'input': HexBytes('0x70a0823100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d'),\ 'output': HexBytes('0x000000000000000000000000000000000000007e37d4560e547e265a1a7dc022'),\ 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B',\ 'type': 'STATICCALL'})\],\ 'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'gas': 84769,\ 'gasUsed': 64940,\ 'input': HexBytes('0x022c0d9f00000000000000000000000000000000000000000000000053f53dfc545d56a600000000000000000000000000000000000000000000000000000000000000000000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d00000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000'),\ 'to': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d',\ 'type': 'CALL',\ 'value': 0}),\ AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'gas': 20382,\ 'gasUsed': 534,\ 'input': HexBytes('0x70a082310000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d'),\ 'output': HexBytes('0x00000000000000000000000000000000000000000000000053f53dfc545d56a6'),\ 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\ 'type': 'STATICCALL'}),\ AttributeDict({'calls': \[AttributeDict({'from': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\ 'gas': 2300,\ 'gasUsed': 83,\ 'input': HexBytes('0x'),\ 'to': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'type': 'CALL',\ 'value': 6049809828398585510})\],\ 'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'gas': 19432,\ 'gasUsed': 9223,\ 'input': HexBytes('0x2e1a7d4d00000000000000000000000000000000000000000000000053f53dfc545d56a6'),\ 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\ 'type': 'CALL',\ 'value': 0}),\ AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'gas': 3353,\ 'gasUsed': 0,\ 'input': HexBytes('0x'),\ 'to': '0xE11418f9961248da36b1008b1090235f680AE8f5',\ 'type': 'CALL',\ 'value': 6049809828398585510})\],\ 'from': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11',\ 'gas': 125270,\ 'gasUsed': 122013,\ 'input': HexBytes('0x791ac947000000000000000000000000000000000000007e37be2022c0914b2680000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000e11418f9961248da36b1008b1090235f680ae8f5000000000000000000000000000000000000000000000000000000006641fe7f0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000ec4cf8dcb526080792bc98e1ef41fb4775777b6b000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'),\ 'to': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',\ 'type': 'CALL',\ 'value': 0})\], 'from': '0xE11418f9961248da36b1008b1090235f680AE8f5', 'gas': 185574, 'gasUsed': 144300, 'input': HexBytes('0x56feb11b000000000000000000000000ec4cf8dcb526080792bc98e1ef41fb4775777b6b000000000000000000000000000000000000007e37be2022c0914b2680000000'), 'to': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11', 'type': 'CALL', 'value': 0}) >>> w3.geth.debug.trace\_transaction(tx\_hash, {'tracer': '4byteTracer'}) --- # Unknown .. \_eth-account: Accounts ======== .. \_local\_vs\_hosted: Local vs Hosted Nodes --------------------- Hosted Node A \*\*hosted\*\* node is controlled by someone else. You may also see these referred to as \*\*remote\*\* nodes. View a list of commercial \`node providers \`\_. Local Node A \*\*local\*\* node is started and controlled by you on your computer. For several reasons (e.g., privacy, security), this is the recommended path, but it requires more resources and work to set up and maintain. See \`ethereum.org \`\_ for a guided tour. Local vs Hosted Keys -------------------- An Ethereum private key is a 256-bit (32 bytes) random integer. For each private key, you get one Ethereum address, also known as an Externally Owned Account (EOA). In Python, the private key is expressed as a 32-byte long Python \`\`bytes\`\` object. When a private key is presented to users in a hexadecimal format, it may or may not contain a starting \`\`0x\`\` hexadecimal prefix. Local Private Key A local private key is a locally stored secret you import to your Python application. Please read below how you can create and import a local private key and use it to sign transactions. Hosted Private Key This is a legacy way to use accounts when working with unit test backends like \`\`EthereumTesterProvider\`\` or \`Anvil \`\_. Calling \`\`web3.eth.accounts\`\` gives you a predefined list of accounts that have been funded with test ETH. You can use :meth:\`~web3.eth.Eth.send\_transaction\` on any of these accounts without further configuration. In the past, around 2015, this was also a way to use private keys in a locally hosted node, but this practice is now discouraged. .. warning:: \`\`web3.eth.send\_transaction\`\` does not work with modern node providers, because they relied on a node state and all modern nodes are stateless. You must always use local private keys when working with nodes hosted by someone else. Some Common Uses for Local Private Keys --------------------------------------- A very common reason to work with local private keys is to interact with a hosted node. Some common things you might want to do with a \`Local Private Key\` are: - \`Sign a Transaction\`\_ - \`Sign a Contract Transaction\`\_ - \`Sign a Message\`\_ - \`Verify a Message\`\_ Using private keys usually involves \`\`w3.eth.account\`\` in one way or another. Read on for more, or see a full list of things you can do in the docs for :class:\`eth\_account.Account \`. Creating a Private Key ---------------------- Each Ethereum address has a matching private key. To create a new Ethereum account you can just generate a random number that acts as a private key. - A private key is just a random unguessable, or cryptographically safe, 256-bit integer number - A valid private key is > 0 and < max private key value (a number above the elliptic curve order FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141) - Private keys do not have checksums. To create a private key using web3.py and command line you can do: .. code-block:: shell python -c "from web3 import Web3; w3 = Web3(); acc = w3.eth.account.create(); print(f'private key={w3.to\_hex(acc.key)}, account={acc.address}')" Which outputs a new private key and an account pair:: private key=0x480c4aec9fa..., account=0x9202a9d5D2d129CB400a40e00aC822a53ED81167 - \*Never store private key with your source\*. Use environment variables to store the key. Read more below. - You can also import the raw hex private key to MetaMask and any other wallet - the private key can be shared between your Python code and any number of wallets. Funding a New Account --------------------- If you create a private key, it comes with its own Ethereum address. By default, the balance of this address is zero. Before you can send any transactions with your account, you need to top up. - For a local test environment (e.g., \`\`EthereumTesterProvider\`\`), any environment is bootstrapped with accounts that have test ETH in them. Move ETH from default accounts to your newly created account. - For public mainnet, you need to buy ETH in a cryptocurrency exchange and send it to your privately controlled account. - For a testnet, find a relevant testnet :ref:\`faucet \`. Reading a Private Key from an Environment Variable -------------------------------------------------- In this example we pass the private key to our Python application in an \`environment variable \`\_. This private key is then added to the transaction signing keychain with \`\`Signing\`\` middleware. If unfamiliar, note that you can \`export your private keys from Metamask and other wallets \`\_. .. warning :: - \*\*Never\*\* share your private keys. - \*\*Never\*\* put your private keys in source code. - \*\*Never\*\* commit private keys to a Git repository. Example \`\`account\_test\_script.py\`\` .. code-block:: 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 Example how to run this in UNIX shell: .. code-block:: shell # Generate a new 256-bit random integer using openssl UNIX command that acts as a private key. # You can also do: # python -c "from web3 import Web3; w3 = Web3(); acc = w3.eth.account.create(); print(f'private key={w3.to\_hex(acc.key)}, account={acc.address}')" # Store this in a safe place, like in your password manager. export PRIVATE\_KEY=0x\`openssl rand -hex 32\` # Run our script python account\_test\_script.py This will print:: Your hot wallet address is 0x27C8F899bb69E1501BBB96d09d7477a2a7518918 .. \_extract\_geth\_pk: Extract private key from geth keyfile ------------------------------------- .. NOTE:: The amount of available ram should be greater than 1GB. .. code-block:: python with open('~/.ethereum/keystore/UTC--...--5ce9454909639D2D17A3F753ce7d93fa0b9aB12E') as keyfile: encrypted\_key = keyfile.read() private\_key = w3.eth.account.decrypt(encrypted\_key, 'correcthorsebatterystaple') # tip: do not save the key or password anywhere, especially into a shared source file Sign a Message -------------- .. WARNING:: There is no single message format that is broadly adopted with community consensus. Keep an eye on several options, like \`EIP-683 \`\_, \`EIP-712 \`\_, and \`EIP-719 \`\_. Consider the :meth:\`w3.eth.sign() \` approach be deprecated. For this example, we will use the same message hashing mechanism that is provided by :meth:\`w3.eth.sign() \`. .. doctest:: >>> from web3 import Web3, EthereumTesterProvider >>> from eth\_account.messages import encode\_defunct >>> w3 = Web3(EthereumTesterProvider()) >>> msg = "I♥SF" >>> private\_key = b"\\xb2\\\\}\\xb3\\x1f\\xee\\xd9\\x12''\\xbf\\t9\\xdcv\\x9a\\x96VK-\\xe4\\xc4rm\\x03\[6\\xec\\xf1\\xe5\\xb3d" >>> message = encode\_defunct(text=msg) >>> signed\_message = w3.eth.account.sign\_message(message, private\_key=private\_key) >>> signed\_message SignedMessage(message\_hash=HexBytes('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750'), r=104389933075820307925104709181714897380569894203213074526835978196648170704563, s=28205917190874851400050446352651915501321657673772411533993420917949420456142, v=28, signature=HexBytes('0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c')) Verify a Message ---------------- With the original message text and a signature: .. doctest:: >>> message = encode\_defunct(text="I♥SF") >>> w3.eth.account.recover\_message(message, signature=signed\_message.signature) '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E' Prepare message for ecrecover in Solidity ----------------------------------------- Let's say you want a contract to validate a signed message, like if you're making payment channels, and you want to validate the value in Remix or web3.js. You might have produced the signed\_message locally, as in \`Sign a Message\`\_. If so, this will prepare it for Solidity: .. doctest:: >>> 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')) >>> ec\_recover\_args = (msghash, v, r, s) = ( ... Web3.to\_hex(signed\_message.message\_hash), ... signed\_message.v, ... to\_32byte\_hex(signed\_message.r), ... to\_32byte\_hex(signed\_message.s), ... ) >>> ec\_recover\_args ('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750', 28, '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') Instead, you might have received a message and a signature encoded to hex. Then this will prepare it for Solidity: .. doctest:: >>> from web3 import Web3 >>> from eth\_account.messages import encode\_defunct, \_hash\_eip191\_message >>> hex\_message = '0x49e299a55346' >>> hex\_signature = '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb33e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce1c' # ecrecover in Solidity expects an encoded version of the message # - encode the message >>> message = encode\_defunct(hexstr=hex\_message) # - hash the message explicitly >>> message\_hash = \_hash\_eip191\_message(message) # Remix / web3.js expect the message hash to be encoded to a hex string >>> hex\_message\_hash = Web3.to\_hex(message\_hash) # ecrecover in Solidity expects the signature to be split into v as a uint8, # and r, s as a bytes32 # Remix / web3.js expect r and s to be encoded to hex >>> sig = Web3.to\_bytes(hexstr=hex\_signature) >>> v, hex\_r, hex\_s = Web3.to\_int(sig\[-1\]), Web3.to\_hex(sig\[:32\]), Web3.to\_hex(sig\[32:64\]) # ecrecover in Solidity takes the arguments in order = (msghash, v, r, s) >>> ec\_recover\_args = (hex\_message\_hash, v, hex\_r, hex\_s) >>> ec\_recover\_args ('0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750', 28, '0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3', '0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce') Verify a message with ecrecover in Solidity ------------------------------------------- Create a simple ecrecover contract in \`Remix \`\_: .. code-block:: none pragma solidity ^0.4.19; contract Recover { function ecr (bytes32 msgh, uint8 v, bytes32 r, bytes32 s) public pure returns (address sender) { return ecrecover(msgh, v, r, s); } } Then call ecr with these arguments from \`Prepare message for ecrecover in Solidity\`\_ in Remix, \`\`"0x1476abb745d423bf09273f1afd887d951181d25adc66c4834a70491911b7f750", 28, "0xe6ca9bba58c88611fad66a6ce8f996908195593807c4b38bd528d2cff09d4eb3", "0x3e5bfbbf4d3e39b1a2fd816a7680c19ebebaf3a141b239934ad43cb33fcec8ce"\`\` The message is verified, because we get the correct sender of the message back in response: \`\`0x5ce9454909639d2d17a3f753ce7d93fa0b9ab12e\`\`. .. \_local-sign-transaction: Sign a Transaction ------------------ Create a transaction, sign it locally, and then send it to your node for broadcasting, with :meth:\`~web3.eth.Eth.send\_raw\_transaction\`. .. doctest:: >>> transaction = { ... 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', ... 'value': 1000000000, ... 'gas': 2000000, ... 'maxFeePerGas': 2000000000, ... 'maxPriorityFeePerGas': 1000000000, ... 'nonce': 0, ... 'chainId': 1, ... 'type': '0x2', # the type is optional and, if omitted, will be interpreted based on the provided transaction parameters ... 'accessList': ( # accessList is optional for dynamic fee transactions ... { ... 'address': '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae', ... 'storageKeys': ( ... '0x0000000000000000000000000000000000000000000000000000000000000003', ... '0x0000000000000000000000000000000000000000000000000000000000000007', ... ) ... }, ... { ... 'address': '0xbb9bc244d798123fde783fcc1c72d3bb8c189413', ... 'storageKeys': () ... }, ... ) ... } >>> key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' >>> signed = w3.eth.account.sign\_transaction(transaction, key) >>> signed.raw\_transaction HexBytes('0x02f8e20180843b9aca008477359400831e848094f0109fc8df283027b6285cc889f5aa624eac1f55843b9aca0080f872f85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000007d694bb9bc244d798123fde783fcc1c72d3bb8c189413c001a0b9ec671ccee417ff79e06e9e52bfa82b37cf1145affde486006072ca7a11cf8da0484a9beea46ff6a90ac76e7bbf3718db16a8b4b09cef477fb86cf4e123d98fde') >>> signed.hash HexBytes('0xe85ce7efa52c16cb5c469c7bde54fbd4911639fdfde08003f65525a85076d915') >>> signed.r 84095564551732371065849105252408326384410939276686534847013731510862163857293 >>> signed.s 32698347985257114675470251181312399332782188326270244072370350491677872459742 >>> signed.v 1 # When you run send\_raw\_transaction, you get back the hash of the transaction: >>> w3.eth.send\_raw\_transaction(signed.raw\_transaction) # doctest: +SKIP '0xe85ce7efa52c16cb5c469c7bde54fbd4911639fdfde08003f65525a85076d915' Sign a Contract Transaction --------------------------- To sign a transaction locally that will invoke a smart contract: #. Initialize your :meth:\`Contract \` object #. Build the transaction #. Sign the transaction, with :meth:\`w3.eth.account.sign\_transaction() \` #. Broadcast the transaction with :meth:\`~web3.eth.Eth.send\_raw\_transaction\` .. testsetup:: import json nonce = 0 EIP20\_ABI = json.loads('\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"\_spender","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"\_from","type":"address"},{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"},{"name":"\_spender","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"\_from","type":"address"},{"indexed":true,"name":"\_to","type":"address"},{"indexed":false,"name":"\_value","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"\_owner","type":"address"},{"indexed":true,"name":"\_spender","type":"address"},{"indexed":false,"name":"\_value","type":"uint256"}\],"name":"Approval","type":"event"}\]') # noqa: 501 .. doctest:: # When running locally, execute the statements found in the file linked below to load the EIP20\_ABI variable. # See: https://github.com/carver/ethtoken.py/blob/v0.0.1-alpha.4/ethtoken/abi.py >>> from web3 import Web3, EthereumTesterProvider >>> w3 = Web3(EthereumTesterProvider()) >>> unicorns = w3.eth.contract(address="0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359", abi=EIP20\_ABI) >>> nonce = w3.eth.get\_transaction\_count('0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E') # doctest: +SKIP # Build a transaction that invokes this contract's function, called transfer >>> unicorn\_txn = unicorns.functions.transfer( ... '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359', ... 1, ... ).build\_transaction({ ... 'chainId': 1, ... 'gas': 70000, ... 'maxFeePerGas': w3.to\_wei('2', 'gwei'), ... 'maxPriorityFeePerGas': w3.to\_wei('1', 'gwei'), ... 'nonce': nonce, ... }) >>> unicorn\_txn {'value': 0, 'chainId': 1, 'gas': 70000, 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'nonce': 0, 'to': '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359', 'data': '0xa9059cbb000000000000000000000000fb6916095ca1df60bb79ce92ce3ea74c37c5d3590000000000000000000000000000000000000000000000000000000000000001'} >>> private\_key = b"\\xb2\\\\}\\xb3\\x1f\\xee\\xd9\\x12''\\xbf\\t9\\xdcv\\x9a\\x96VK-\\xe4\\xc4rm\\x03\[6\\xec\\xf1\\xe5\\xb3d" >>> signed\_txn = w3.eth.account.sign\_transaction(unicorn\_txn, private\_key=private\_key) >>> signed\_txn.hash HexBytes('0x748db062639a45e519dba934fce09c367c92043867409160c9989673439dc817') >>> signed\_txn.raw\_transaction HexBytes('0x02f8b00180843b9aca0084773594008301117094fb6916095ca1df60bb79ce92ce3ea74c37c5d35980b844a9059cbb000000000000000000000000fb6916095ca1df60bb79ce92ce3ea74c37c5d3590000000000000000000000000000000000000000000000000000000000000001c001a0cec4150e52898cf1295cc4020ac0316cbf186071e7cdc5ec44eeb7cdda05afa2a06b0b3a09c7fb0112123c0bef1fd6334853a9dcf3cb5bab3ccd1f5baae926d449') >>> signed\_txn.r 93522894155654168208483453926995743737629589441154283159505514235904280342434 >>> signed\_txn.s 48417310681110102814014302147799665717176259465062324746227758019974374282313 >>> signed\_txn.v 1 >>> w3.eth.send\_raw\_transaction(signed\_txn.raw\_transaction) # doctest: +SKIP # When you run send\_raw\_transaction, you get the same result as the hash of the transaction: >>> w3.to\_hex(w3.keccak(signed\_txn.raw\_transaction)) '0x748db062639a45e519dba934fce09c367c92043867409160c9989673439dc817' --- # Resources and Learning Material — web3.py 7.6.1 documentation * [](index.html) * Resources and Learning Material * [View page source](_sources/resources.rst.txt) * * * Resources and Learning Material[](#resources-and-learning-material "Link to this heading") ============================================================================================ web3.py and the Ethereum Python ecosystem have an active community of developers and educators. Here you’ll find libraries, tutorials, examples, courses and other learning material. Warning Links on this page are community submissions and are not vetted by the team that maintains web3.py. As always, DYOR (Do Your Own Research). First Steps[](#first-steps "Link to this heading") ---------------------------------------------------- Resources for those brand new to Ethereum: * [A Developer’s Guide to Ethereum, Pt. 1](https://snakecharmers.ethereum.org/a-developers-guide-to-ethereum-pt-1/) * [Ethereum Python Ecosystem Tour](https://snakecharmers.ethereum.org/python-ecosystem/) Courses[](#courses "Link to this heading") -------------------------------------------- * [freeCodeCamp Solidity and Python Course (2022)](https://www.youtube.com/watch?v=umg2fWQX6jM) * [Blockchain Python Programming Tutorial (2019)](https://www.youtube.com/watch?v=pZSegEXtgAE) Tutorials[](#tutorials "Link to this heading") ------------------------------------------------ * Intro to [Ape development framework](https://snakecharmers.ethereum.org/intro-to-ape/) * Intro to [websockets](https://snakecharmers.ethereum.org/websocketprovider/) and web3.py * Intro to [asynchronous web3.py](https://snakecharmers.ethereum.org/web3-py-patterns-intro-async/) * Intro to [threaded web3.py](https://snakecharmers.ethereum.org/web3-py-patterns-multithreading/) * Sign [typed data messages](https://snakecharmers.ethereum.org/typed-data-message-signing/) (EIP 712) * Look up offchain data via [CCIP Read](https://snakecharmers.ethereum.org/web3-py-patterns-off-chain-lookups/) * Configure and [customize web3.py](https://snakecharmers.ethereum.org/web3-py-patterns-customizations/) * [Decode a signed transaction](https://snakecharmers.ethereum.org/web3-py-patterns-decoding-signed-transactions/) * Find a historical contract [revert reason](https://snakecharmers.ethereum.org/web3py-revert-reason-parsing/) * Generate a [vanity address](https://snakecharmers.ethereum.org/web3-py-patterns-mining-addresses/) * Similate transactions with [call state overrides](https://snakecharmers.ethereum.org/web3-py-patterns-eth_call-overrides/) * Configure web3 for [JSON-RPC fallback and MEV blocker providers](https://web3-ethereum-defi.readthedocs.io/tutorials/multi-rpc-configuration.html) Conference Presentations and Videos[](#conference-presentations-and-videos "Link to this heading") ---------------------------------------------------------------------------------------------------- * [Web3.Py - Now And Near Future by Marc Garreau (2022, 15 mins)](https://www.youtube.com/watch?v=hj6ubyyE_TY) * [Python and DeFi by Curve Finance (2022, 15 mins)](https://www.youtube.com/watch?v=4HOU3z0LoDg) * [Working with MetaMask in Python by Rishab Kattimani (2022, 15 mins)](https://www.youtube.com/watch?v=cFB1BGeCpn0) Smart Contract Programming Languages[](#smart-contract-programming-languages "Link to this heading") ------------------------------------------------------------------------------------------------------ * [Vyper](https://docs.vyperlang.org/en/stable/) - Contract-oriented, pythonic programming language that targets EVM Frameworks and Tooling[](#frameworks-and-tooling "Link to this heading") -------------------------------------------------------------------------- * [Ape](https://www.apeworx.io/) - The Ethereum development framework for Python Developers, Data Scientists, and Security Professionals * [Titanoboa](https://github.com/vyperlang/titanoboa) - A Vyper interpreter and testing framework * [Wake](https://github.com/Ackee-Blockchain/wake) - A Python-based development and testing framework for Solidity * [Brownie](https://github.com/eth-brownie/brownie) - \[No longer actively maintained\] A Python-based development and testing framework for smart contracts targeting EVM Libraries[](#libraries "Link to this heading") ------------------------------------------------ * [Web3 Ethereum DeFi](https://github.com/tradingstrategy-ai/web3-ethereum-defi) - Library for DeFi trading and protocols (Uniswap, PancakeSwap, Sushi, Aave, Chainlink) * [lighter-v1-python](https://github.com/elliottech/lighter-v1-python) - Lighter.xyz DEX client for Python * [uniswap-python](https://uniswap-python.com/) - Library lets you easily retrieve prices and make trades on all Uniswap versions. * [pyWalletConnect](https://github.com/bitlogik/pyWalletConnect) - WalletConnect implementation for wallets in Python * [dydx-v3-python](https://github.com/dydxprotocol/dydx-v3-python) - Python client for dYdX v3 * [Lido Python SDK](https://github.com/lidofinance/lido-python-sdk) - Library with which you can get all Lido validator’s signatures and check their validity Applications[](#applications "Link to this heading") ------------------------------------------------------ * [Curve Finance](https://github.com/curvefi?q=&type=all&language=python&sort=) * [Yearn Finance](https://github.com/yearn?q=&type=all&language=python&sort=) * [StakeWise Oracle](https://github.com/stakewise/oracle/) Hackathon Helpers[](#hackathon-helpers "Link to this heading") ---------------------------------------------------------------- * [ape-hackathon-kit](https://github.com/wolovim/ape-hackathon-kit) - Ape project template with a web front-end (Next.js, Tailwind, RainbowKit, wagmi) * [eth-flogger](https://github.com/wolovim/eth-flogger) - Sample web app utilizing async web3.py, Flask, SQLite, Sourcify * [Temo](https://github.com/wolovim/temo) - Sample terminal app utilizing async web3py, Textual, Anvil * [web3py-discord-bot](https://github.com/wolovim/web3py-discord-bot) - Sample Discord bot utilizing websockets, `eth_subscribe`, and discord.py * [py-signer](https://github.com/wolovim/py-signer) - Demo of typed data message signing (EIP-712) with eth-account and Ape --- # Unknown .. \_ens\_overview: Ethereum Name Service (ENS) =========================== The Ethereum Name Service (ENS) is analogous to the Domain Name Service. It enables users and developers to use human-friendly names in place of error-prone hexadecimal addresses, content hashes, and more. The :mod:\`ens\` module is included with web3.py. It provides an interface to look up domains and addresses, add resolver records, or get and set metadata. .. note:: web3.py \`\`v6.6.0\`\` introduced ENS name normalization standard \`ENSIP-15 \`\_. This update to ENS name validation and normalization won't affect ~99% of names but may prevent invalid names from being created and from interacting with the ENS contracts via web3.py. We feel strongly that this change, though breaking, is in the best interest of our users as it ensures compatibility with the latest ENS standards. Setup ----- Create an :class:\`~ens.ENS\` object (named \`\`ns\`\` below) in one of three ways: 1. Automatic detection 2. Specify an instance of a :ref:\`provider \` 3. From an existing :class:\`web3.Web3\` object .. code-block:: 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: .. code-block:: 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. .. code-block:: python # instantiate w3 instance from web3 import Web3, IPCProvider w3 = Web3(IPCProvider(...)) # use the module w3.ens.address('ethereum.eth') .. py:attribute:: 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 :ref:\`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. .. doctest:: >>> from web3 import Web3, EthereumTesterProvider >>> from ens import ENS >>> w3 = Web3(EthereumTesterProvider()) >>> assert w3.strict\_bytes\_type\_checking # assert strict by default >>> w3.is\_encodable('bytes2', b'1') False >>> w3.strict\_bytes\_type\_checking = False >>> w3.is\_encodable('bytes2', b'1') # zero-padded, so encoded to: b'1\\x00' True >>> ns = ENS.from\_web3(w3) >>> # assert inherited from w3 at time of instantiation via ENS.from\_web3() >>> assert ns.strict\_bytes\_type\_checking is False >>> ns.w3.is\_encodable('bytes2', b'1') True >>> # assert these are now separate instances >>> ns.strict\_bytes\_type\_checking = True >>> ns.w3.is\_encodable('bytes2', b'1') False >>> # assert w3 flag value remains >>> assert w3.strict\_bytes\_type\_checking is False >>> w3.is\_encodable('bytes2', b'1') True 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. .. doctest:: >>> from web3 import Web3, EthereumTesterProvider >>> w3 = Web3(EthereumTesterProvider()) >>> assert w3.strict\_bytes\_type\_checking # assert strict by default >>> w3.is\_encodable('bytes2', b'1') False >>> w3.strict\_bytes\_type\_checking = False >>> w3.is\_encodable('bytes2', b'1') # zero-padded, so encoded to: b'1\\x00' True >>> assert w3 == w3.ens.w3 # assert same object >>> assert not w3.ens.w3.strict\_bytes\_type\_checking >>> w3.ens.w3.is\_encodable('bytes2', b'1') True >>> # sanity check on eth module as well >>> assert not w3.eth.w3.strict\_bytes\_type\_checking >>> w3.eth.w3.is\_encodable('bytes2', b'1') True Usage ----- Name Info ~~~~~~~~~ .. \_ens\_get\_address: Get the Address for an ENS Name ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: python from ens.auto import ns eth\_address = ns.address('ens.eth') assert eth\_address == '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' The \`\`ENS\`\` module has no opinion as to which \*\*TLD (Top Level Domain)\*\* you can use, but will not infer a TLD if it is not provided with the name. Multichain Address Resolution +++++++++++++++++++++++++++++ \`ENSIP-9 \`\_ introduced multichain address resolution, allowing users to resolve addresses from different chains, specified by the coin type index from \`SLIP44 \`\_. The \`\`address()\`\` method on the \`\`ENS\`\` class supports multichain address resolution via the \`\`coin\_type\`\` keyword argument. .. code-block:: python from ens.auto import ns eth\_address = ns.address('ens.eth', coin\_type=60) # ETH is coin\_type 60 assert eth\_address == '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' Get the ENS Name for an Address ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: python domain = ns.name('0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') # name() also accepts the bytes version of the address assert ns.name(b'\\xfe\\x89\\xccz\\xbb,A\\x83h:\\xb7\\x16S\\xc4\\xcd\\xc9\\xb0-D\\xb7') == domain # confirm that the name resolves back to the address that you looked up: assert ns.address(domain) == '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' .. note:: For accuracy, and as a recommendation from the ENS documentation on \`reverse resolution \`\_, the \`\`ENS\`\` module now verifies that the forward resolution matches the address with every call to get the \`\`name()\`\` for an address. This is the only sure way to know whether the reverse resolution is correct. Anyone can claim any name, only forward resolution implies that the owner of the name gave their stamp of approval. Get the Owner of a Name ^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: python eth\_address = ns.owner('exchange.eth') .... Set Up Your Name and Address ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Link a Name to an Address ^^^^^^^^^^^^^^^^^^^^^^^^^ You can set up your name so that :meth:\`~ens.ENS.address\` will show the address it points to. In order to do so, you must already be the owner of the domain (or its parent). .. code-block:: python ns.setup\_address('ens.eth', '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') In the common case where you want to point the name to the owning address, you can skip the address. .. code-block:: python ns.setup\_address('ens.eth') You can claim arbitrarily deep subdomains. .. code-block:: python ns.setup\_address('supreme.executive.power.derives.from.a.mandate.from.the.masses.ens.eth') # wait for the transaction to be mined, then: assert ( ns.address('supreme.executive.power.derives.from.a.mandate.from.the.masses.ens.eth') == '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' ) .. warning:: Gas costs scale up with the number of subdomains! Multichain Address Support ++++++++++++++++++++++++++ \`ENSIP-9 \`\_ introduced multichain address resolution, allowing users to resolve addresses from different chains, specified by the coin type index from \`SLIP44 \`\_. The \`\`setup\_address()\`\` method on the \`\`ENS\`\` class supports multichain address setup via the \`\`coin\_type\`\` keyword argument. .. code-block:: python from ens.auto import ns ns.setup\_address('ens.eth', coin\_type=60) # ETH is coin\_type 60 assert ns.address('ens.eth', coin\_type=60) == '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7' Link an Address to a Name ^^^^^^^^^^^^^^^^^^^^^^^^^ You can set up your address so that :meth:\`~ens.ENS.name\` will show the name that points to it. This is like Caller ID. It enables you and others to take an account and determine what name points to it. Sometimes this is referred to as "reverse" resolution. The ENS Reverse Resolver is used for this functionality. .. code-block:: python ns.setup\_name('ens.eth', '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') If you don't supply the address, :meth:\`~ens.ENS.setup\_name\` will assume you want the address returned by :meth:\`~ens.ENS.address\`. .. code-block:: python ns.setup\_name('ens.eth') If the name doesn't already point to an address, :meth:\`~ens.ENS.setup\_name\` will call :meth:\`~ens.ENS.setup\_address\` for you. Wait for the transaction to be mined, then: .. code-block:: python assert ns.name('0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') == 'ens.eth' .... Text Records ~~~~~~~~~~~~ Set Text Metadata for an ENS Record ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As the owner of an ENS record, you can add text metadata. A list of supported fields can be found in the \`ENS documentation \`\_. You'll need to setup the address first, and then the text can be set: .. code-block:: python ns.setup\_address('ens.eth', '0xFe89cc7aBB2C4183683ab71653C4cdc9B02D44b7') ns.set\_text('ens.eth', 'url', 'https://example.com') A transaction dictionary can be passed as the last argument if desired: .. code-block:: python transaction\_dict = {'from': '0x123...'} ns.set\_text('ens.eth', 'url', 'https://example.com', transaction\_dict) If the transaction dictionary is not passed, sensible defaults will be used, and if a transaction dictionary is passed but does not have a \`\`from\`\` value, the default will be the \`\`owner\`\`. Read Text Metadata for an ENS Record ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Anyone can read the data from an ENS Record: .. code-block:: python url = ns.get\_text('ens.eth', 'url') assert url == 'https://example.com' .... Working With Resolvers ~~~~~~~~~~~~~~~~~~~~~~ Get the Resolver for an ENS Record ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You can get the resolver for an ENS name via the :meth:\`~ens.ENS.resolver\` method. .. code-block:: python >>> resolver = ns.resolver('ens.eth') >>> resolver.address '0x5B2063246F2191f18F2675ceDB8b28102e957458' .... Wildcard Resolution Support --------------------------- The \`\`ENS\`\` module supports Wildcard Resolution for resolvers that implement the \`\`ExtendedResolver\`\` interface as described in \`ENSIP-10 \`\_. Resolvers that implement the extended resolver interface should return \`\`True\`\` when calling the \`\`supportsInterface()\`\` function with the extended resolver interface id \`\`"0x9061b923"\`\` and should resolve subdomains to a unique address. --- # Unknown .. \_contracts: Contracts ========= .. py:module:: web3.contract Smart contracts are programs deployed to the Ethereum network. See the \`ethereum.org docs \`\_ for a proper introduction. Interacting with deployed contracts ----------------------------------- In order to use an existing contract, you'll need its deployed address and its ABI. Both can be found using block explorers, like Etherscan. Once you instantiate a contract instance, you can read data and execute transactions. .. code-block:: python # Configure w3, e.g., w3 = Web3(...) address = '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F988' abi = '\[{"inputs":\[{"internalType":"address","name":"account","type":"address"},{"internalType":"address","name":"minter\_","type":"address"},...' contract\_instance = w3.eth.contract(address=address, abi=abi) # read state: contract\_instance.functions.storedValue().call() # 42 # update state: tx\_hash = contract\_instance.functions.updateValue(43).transact() .. \_contract\_example: Contract Deployment Example --------------------------- To run this example, you will need to install a few extra features: - The sandbox node provided by eth-tester. You can install it with: .. code-block:: bash $ pip install -U "web3\[tester\]" - \`\`py-solc-x\`\`. This is the supported route to installing the solidity compiler \`\`solc\`\`. You can install it with: .. code-block:: bash $ pip install py-solc-x After \`\`py-solc-x\`\` is installed, you will need to install a version of \`\`solc\`\`. You can install the latest version via a new REPL with: .. code-block:: python >>> from solcx import install\_solc >>> install\_solc(version='latest') You should now be set up to compile and deploy a contract. The following example runs through these steps: #. Compile Solidity contract into bytecode and an ABI #. Initialize a Contract instance #. Deploy the contract using the Contract instance to initiate a transaction #. Interact with the contract functions using the Contract instance .. code-block:: 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' Contract Factories ------------------ These factories are not intended to be initialized directly. Instead, create contract objects using the :meth:\`w3.eth.contract() \` method. By default, the contract factory is :class:\`Contract\`. .. py:class:: Contract(address) Contract provides a default interface for deploying and interacting with Ethereum smart contracts. The address parameter can be a hex address or an ENS name, like \`\`mycontract.eth\`\`. Properties ---------- Each Contract Factory exposes the following properties. .. py:attribute:: Contract.address The hexadecimal encoded 20-byte address of the contract, or an ENS name. May be \`\`None\`\` if not provided during factory creation. .. py:attribute:: Contract.abi The contract \`\`abi\`\`, or Application Binary Interface, specifies how a contract can be interacted with. Without an \`\`abi\`\`, the contract cannot be decoded. The \`\`abi\`\` enables the Contract instance to expose functions and events as object properties. For further details, see the \`Solidity ABI specification \`\_. .. py:attribute:: Contract.bytecode The contract bytecode string. May be \`\`None\`\` if not provided during factory creation. .. py:attribute:: Contract.bytecode\_runtime The runtime part of the contract bytecode string. May be \`\`None\`\` if not provided during factory creation. .. py:attribute:: Contract.decode\_tuples If a Tuple/Struct is returned by a contract function, this flag defines whether to apply the field names from the ABI to the returned data. If False, the returned value will be a normal Python \`\`Tuple\`\`. If True, the returned value will be a Python \`\`NamedTuple\`\` of the class \`\`ABIDecodedNamedTuple\`\`. NamedTuples have some restrictions regarding field names. web3.py sets \`\`NamedTuple\`\`'s \`\`rename=True\`\`, so disallowed field names may be different than expected. See the \`Python docs \`\_ for more information. Defaults to \`\`False\`\` if not provided during factory creation. .. py:attribute:: Contract.functions This provides access to contract functions as attributes. For example: \`\`myContract.functions.MyMethod()\`\`. The exposed contract functions are classes of the type :py:class:\`ContractFunction\`. .. py:attribute:: Contract.events This provides access to contract events as attributes. For example: \`\`myContract.events.MyEvent()\`\`. The exposed contract events are classes of the type :py:class:\`ContractEvent\`. Methods ------- Method doctests use the following ABI and bytecode. .. code-block:: python >>> bytecode = '6060604052341561000c57fe5b604051602080610acb833981016040528080519060200190919050505b620f42408114151561003b5760006000fd5b670de0b6b3a76400008102600281905550600254600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b505b610a27806100a46000396000f30060606040523615610097576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde0314610099578063095ea7b31461013257806318160ddd1461018957806323b872dd146101af578063313ce5671461022557806370a082311461025157806395d89b411461029b578063a9059cbb14610334578063dd62ed3e1461038b575bfe5b34156100a157fe5b6100a96103f4565b60405180806020018281038252838181518152602001915080519060200190808383600083146100f8575b8051825260208311156100f8576020820191506020810190506020830392506100d4565b505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013a57fe5b61016f600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061042e565b604051808215151515815260200191505060405180910390f35b341561019157fe5b610199610521565b6040518082815260200191505060405180910390f35b34156101b757fe5b61020b600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610527565b604051808215151515815260200191505060405180910390f35b341561022d57fe5b610235610791565b604051808260ff1660ff16815260200191505060405180910390f35b341561025957fe5b610285600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610796565b6040518082815260200191505060405180910390f35b34156102a357fe5b6102ab6107e0565b60405180806020018281038252838181518152602001915080519060200190808383600083146102fa575b8051825260208311156102fa576020820191506020810190506020830392506102d6565b505050905090810190601f1680156103265780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561033c57fe5b610371600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061081a565b604051808215151515815260200191505060405180910390f35b341561039357fe5b6103de600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610973565b6040518082815260200191505060405180910390f35b604060405190810160405280600981526020017f54657374546f6b656e000000000000000000000000000000000000000000000081525081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60025481565b600081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410806105f1575081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054105b156105fc5760006000fd5b81600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b9392505050565b601281565b6000600060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b604060405190810160405280600481526020017f544553540000000000000000000000000000000000000000000000000000000081525081565b600081600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156108695760006000fd5b81600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b929150505600a165627a7a723058205071371ee2a4a1be3c96e77d939cdc26161a256fdd638efc08bd33dfc65d3b850029' >>> abi = '\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_spender","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_from","type":"address"},{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"},{"name":"\_spender","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"inputs":\[{"name":"\_totalSupply","type":"uint256"}\],"payable":false,"type":"constructor","stateMutability":"nonpayable"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Approval","type":"event"}\]' >>> contract = w3.eth.contract(abi=abi, bytecode=bytecode) Each Contract Factory exposes the following methods. .. testsetup:: contractmethods from web3 import Web3 w3 = Web3(Web3.EthereumTesterProvider()) bytecode = '6060604052341561000c57fe5b604051602080610acb833981016040528080519060200190919050505b620f42408114151561003b5760006000fd5b670de0b6b3a76400008102600281905550600254600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b505b610a27806100a46000396000f30060606040523615610097576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde0314610099578063095ea7b31461013257806318160ddd1461018957806323b872dd146101af578063313ce5671461022557806370a082311461025157806395d89b411461029b578063a9059cbb14610334578063dd62ed3e1461038b575bfe5b34156100a157fe5b6100a96103f4565b60405180806020018281038252838181518152602001915080519060200190808383600083146100f8575b8051825260208311156100f8576020820191506020810190506020830392506100d4565b505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013a57fe5b61016f600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061042e565b604051808215151515815260200191505060405180910390f35b341561019157fe5b610199610521565b6040518082815260200191505060405180910390f35b34156101b757fe5b61020b600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610527565b604051808215151515815260200191505060405180910390f35b341561022d57fe5b610235610791565b604051808260ff1660ff16815260200191505060405180910390f35b341561025957fe5b610285600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610796565b6040518082815260200191505060405180910390f35b34156102a357fe5b6102ab6107e0565b60405180806020018281038252838181518152602001915080519060200190808383600083146102fa575b8051825260208311156102fa576020820191506020810190506020830392506102d6565b505050905090810190601f1680156103265780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561033c57fe5b610371600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061081a565b604051808215151515815260200191505060405180910390f35b341561039357fe5b6103de600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610973565b6040518082815260200191505060405180910390f35b604060405190810160405280600981526020017f54657374546f6b656e000000000000000000000000000000000000000000000081525081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60025481565b600081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410806105f1575081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054105b156105fc5760006000fd5b81600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b9392505050565b601281565b6000600060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b604060405190810160405280600481526020017f544553540000000000000000000000000000000000000000000000000000000081525081565b600081600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156108695760006000fd5b81600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b929150505600a165627a7a723058205071371ee2a4a1be3c96e77d939cdc26161a256fdd638efc08bd33dfc65d3b850029' abi = '\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_spender","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_from","type":"address"},{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"},{"name":"\_spender","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"inputs":\[{"name":"\_totalSupply","type":"uint256"}\],"payable":false,"type":"constructor","stateMutability":"nonpayable"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Approval","type":"event"}\]' contract = w3.eth.contract(abi=abi, bytecode=bytecode) .. py:classmethod:: Contract.constructor(\*args, \*\*kwargs).transact(transaction=None) Construct and deploy a contract by sending a new public transaction. If provided \`\`transaction\`\` should be a dictionary conforming to the \`\`web3.eth.send\_transaction(transaction)\`\` method. This value may not contain the keys \`\`data\`\` or \`\`to\`\`. If the contract takes constructor parameters they should be provided as positional arguments or keyword arguments. If any of the arguments specified in the ABI are an \`\`address\`\` type, they will accept ENS names. If a \`\`gas\`\` value is not provided, then the \`\`gas\`\` value for the deployment transaction will be created using the \`\`web3.eth.estimate\_gas()\`\` method. Returns the transaction hash for the deploy transaction. .. doctest:: contractmethods >>> deploy\_txn = contract.constructor(1000000).transact({'from': w3.eth.accounts\[0\], 'gas': 899000, 'gasPrice': Web3.to\_wei(1, 'gwei')}) >>> txn\_receipt = w3.eth.get\_transaction\_receipt(deploy\_txn) >>> txn\_receipt\['contractAddress'\] '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b' .. py:classmethod:: Contract.constructor(\*args, \*\*kwargs).estimate\_gas(transaction=None, block\_identifier=None) :noindex: Estimate gas for constructing and deploying the contract. This method behaves the same as the :py:meth:\`Contract.constructor(\*args, \*\*kwargs).transact\` method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion. The \`\`block\_identifier\`\` parameter is passed directly to the call at the end portion of the function call. Returns the amount of gas consumed which can be used as a gas estimate for executing this transaction publicly. Returns the gas needed to deploy the contract. .. doctest:: contractmethods >>> contract.constructor(1000000).estimate\_gas() 664971 .. py:classmethod:: Contract.constructor(\*args, \*\*kwargs).build\_transaction(transaction=None) :noindex: Construct the contract deploy transaction bytecode data. If the contract takes constructor parameters they should be provided as positional arguments or keyword arguments. If any of the \`\`args\`\` specified in the ABI are an \`\`address\`\` type, they will accept ENS names. Returns the transaction dictionary that you can pass to send\_transaction method. .. doctest:: contractmethods >>> transaction = { ... 'gas': 664971, ... 'chainId': 131277322940537 ... } >>> contract\_data = contract.constructor(1000000).build\_transaction(transaction) >>> w3.eth.send\_transaction(contract\_data) HexBytes('0x40c51804800dee88e14e69826cfe51bc5f25f61935331e8aa6d8d7771fb36350') .. \_contract\_create\_filter: .. py:classmethod:: Contract.events.your\_event\_name.create\_filter(from\_block=None, to\_block="latest", argument\_filters={}, topics=\[\]) Creates a new event filter, an instance of :py:class:\`web3.utils.filters.LogFilter\`. - \`\`from\_block\`\` is a mandatory field. Defines the starting block (exclusive) filter block range. It can be either the starting block number, or 'latest' for the last mined block, or 'pending' for unmined transactions. In the case of \`\`from\_block\`\`, 'latest' and 'pending' set the 'latest' or 'pending' block as a static value for the starting filter block. - \`\`to\_block\`\` optional. Defaults to 'latest'. Defines the ending block (inclusive) in the filter block range. Special values 'latest' and 'pending' set a dynamic range that always includes the 'latest' or 'pending' blocks for the filter's upper block range. - \`\`address\`\` optional. Defaults to the contract address. The filter matches the event logs emanating from \`\`address\`\`. - \`\`argument\_filters\`\`, optional. Expects a dictionary of argument names and values. When provided event logs are filtered for the event argument values. Event arguments can be both indexed or unindexed. Indexed values will be translated to their corresponding topic arguments. Unindexed arguments will be filtered using a regular expression. - \`\`topics\`\` optional, accepts the standard JSON-RPC topics argument. See the JSON-RPC documentation for \`eth\_newFilter \`\_ more information on the \`\`topics\`\` parameters. .. doctest:: contractmethods >>> filter = contract.events.Transfer.create\_filter(from\_block='latest') .. py:classmethod:: Contract.events.your\_event\_name.build\_filter() Creates a EventFilterBuilder instance with the event abi, and the contract address if called from a deployed contract instance. The EventFilterBuilder provides a convenient way to construct the filter parameters with value checking against the event abi. It allows for defining multiple match values or of single values through the match\_any and match\_single methods. .. doctest:: contractmethods >>> filter\_builder = contract.events.Transfer.build\_filter() >>> filter\_builder.from\_block = "latest" >>> filter\_builder.args\['from'\].match\_any(w3.eth.accounts\[0\]) >>> filter\_builder.args\['to'\].match\_single(w3.eth.accounts\[1\]) >>> filter\_builder.args\['value'\].match\_single(10000) >>> filter\_instance = filter\_builder.deploy(w3) The \`\`deploy\`\` method returns a :py:class:\`web3.utils.filters.LogFilter\` instance from the filter parameters generated by the filter builder. Defining multiple match values for array arguments can be accomplished easily with the filter builder: .. doctest:: contractmethods >>> filter\_builder = contract.events.Transfer.build\_filter() >>> filter\_builder.args\['to'\].match\_any(w3.eth.accounts\[0\], w3.eth.accounts\[1\]) The filter builder blocks already defined filter parameters from being changed. .. doctest:: contractmethods >>> filter\_builder = contract.events.Transfer.build\_filter() >>> filter\_builder.from\_block = "latest" >>> filter\_builder.from\_block = 0 Traceback (most recent call last): web3.exceptions.Web3ValueError: from\_block is already set to 'latest'. Resetting filter parameters is not permitted .. py:classmethod:: Contract.encode\_abi(abi\_element\_identifier, args=None, kwargs=None, data=None) Encodes the arguments using the Ethereum ABI for the contract function that matches the given \`\`abi\_element\_identifier\`\` and arguments \`\`args\`\`. The \`\`data\`\` parameter defaults to the function selector. .. doctest:: contractmethods >>> contract.encode\_abi("approve", args=\[w3.eth.accounts\[0\], 10\]) '0x095ea7b30000000000000000000000007e5f4552091a69125d5dfcb7b8c2659029395bdf000000000000000000000000000000000000000000000000000000000000000a' .. py:classmethod:: Contract.all\_events() Returns a list of all the events present in a Contract where every event is an instance of :py:class:\`ContractEvent\`. .. doctest:: contractmethods >>> contract.all\_events() \[, \] .. py:classmethod:: Contract.get\_event\_by\_signature(signature) Searches for a distinct event with matching signature. Returns an instance of :py:class:\`ContractEvent\` upon finding a match. Raises \`\`Web3ValueError\`\` if no match is found. .. doctest:: contractmethods >>> contract.get\_event\_by\_signature('Transfer(address,address,uint256)') .. py:classmethod:: Contract.find\_events\_by\_name(name) Searches for all events matching the provided name. Returns a list of matching events where every event is an instance of :py:class:\`ContractEvent\`. Returns an empty list when no match is found. .. doctest:: contractmethods >>> contract.find\_events\_by\_name('Transfer') \[\] .. py:classmethod:: Contract.get\_event\_by\_name(name) Searches for a distinct event matching the name. Returns an instance of :py:class:\`ContractEvent\` upon finding a match. Raises \`\`Web3ValueError\`\` if no match is found or if multiple matches are found. .. doctest:: contractmethods >>> contract.get\_event\_by\_name('Approval') .. py:classmethod:: Contract.find\_events\_by\_selector(selector) Searches for all events matching the provided selector. Returns a list of matching events where every event is an instance of :py:class:\`ContractEvent\`. Returns an empty list when no match is found. .. doctest:: contractmethods >>> contract.find\_events\_by\_selector('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925') \[\] .. py:classmethod:: Contract.get\_event\_by\_selector(selector) Searches for a distinct event with matching selector. The selector can be a hexadecimal string, bytes or int. Returns an instance of :py:class:\`ContractEvent\` upon finding a match. Raises \`\`Web3ValueError\`\` if no match is found. .. doctest:: contractmethods >>> contract.get\_event\_by\_selector('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925') \>>> contract.get\_event\_by\_selector(b'\\x8c\[\\xe1\\xe5\\xeb\\xec}\[\\xd1OqB}\\x1e\\x84\\xf3\\xdd\\x03\\x14\\xc0\\xf7\\xb2)\\x1e\[ \\n\\xc8\\xc7\\xc3\\xb9%') \>>> contract.get\_event\_by\_selector(0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925) .. py:classmethod:: Contract.find\_events\_by\_topic(topic) Searches for all events matching the provided topic. Returns a list of matching events where every event is an instance of :py:class:\`ContractEvent\`. Returns an empty list when no match is found. .. doctest:: contractmethods >>> contract.find\_events\_by\_topic('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925') \[\] .. py:classmethod:: Contract.get\_event\_by\_topic(topic) Searches for a distinct event with matching topic. The topic is a hexadecimal string. Returns an instance of :py:class:\`ContractEvent\` upon finding a match. Raises \`\`Web3ValueError\`\` if no match is found. .. doctest:: contractmethods >>> contract.get\_event\_by\_topic('0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925') .. py:classmethod:: Contract.all\_functions() Returns a list of all the functions present in a Contract where every function is an instance of :py:class:\`ContractFunction\`. .. doctest:: contractmethods >>> contract.all\_functions() \[, , , , , , , , \] .. py:classmethod:: Contract.get\_function\_by\_signature(signature) Searches for a distinct function with matching signature. Returns an instance of :py:class:\`ContractFunction\` upon finding a match. Raises \`\`Web3ValueError\`\` if no match is found. .. doctest:: contractmethods >>> contract.get\_function\_by\_signature('approve(address,uint256)') .. py:classmethod:: Contract.find\_functions\_by\_name(name) Searches for all functions matching the name. Returns a list of matching functions where every function is an instance of :py:class:\`ContractFunction\`. Returns an empty list when no match is found. .. doctest:: contractmethods >>> contract.find\_functions\_by\_name('transferFrom') \[\] .. py:classmethod:: Contract.get\_function\_by\_name(name) Searches for a distinct function with matching name. Returns an instance of :py:class:\`ContractFunction\` upon finding a match. Raises \`\`Web3ValueError\`\` if no match is found or if multiple matches are found. .. doctest:: contractmethods >>> contract.get\_function\_by\_name('decimals') .. py:classmethod:: Contract.get\_function\_by\_selector(selector) Searches for a distinct function with matching selector. The selector can be a hexadecimal string, bytes or int. Returns an instance of :py:class:\`ContractFunction\` upon finding a match. Raises \`\`Web3ValueError\`\` if no match is found. .. doctest:: contractmethods >>> contract.get\_function\_by\_selector('0xdd62ed3e') \>>> contract.get\_function\_by\_selector(b'\\xddb\\xed>') \>>> contract.get\_function\_by\_selector(0xdd62ed3e) .. py:classmethod:: Contract.find\_functions\_by\_args(\*args) Searches for all function with matching args. Returns a list of matching functions where every function is an instance of :py:class:\`ContractFunction\`. Returns an empty list when no match is found. .. doctest:: contractmethods >>> contract.find\_functions\_by\_args(w3.eth.accounts\[0\], 10000) \[, \] .. py:classmethod:: Contract.get\_function\_by\_args(\*args) Searches for a distinct function with matching args. Returns an instance of :py:class:\`ContractFunction\` upon finding a match. Raises \`\`ValueError\`\` if no match is found or if multiple matches are found. .. doctest:: contractmethods >>> contract.get\_function\_by\_args(w3.eth.accounts\[0\], w3.eth.accounts\[1\], 10000) .. note:: \`\`Contract\`\` methods \`\`all\_functions\`\`, \`\`get\_function\_by\_signature\`\`, \`\`find\_functions\_by\_name\`\`, \`\`get\_function\_by\_name\`\`, \`\`get\_function\_by\_selector\`\`, \`\`find\_functions\_by\_args\`\` and \`\`get\_function\_by\_args\`\` can only be used when abi is provided to the contract. .. note:: web3.py rejects the initialization of contracts that have more than one function with the same selector or signature. eg. \`\`blockHashAddendsInexpansible(uint256)\`\` and \`\`blockHashAskewLimitary(uint256)\`\` have the same selector value equal to \`\`0x00000000\`\`. A contract containing both of these functions will be rejected. .. \_disable-strict-byte-check: Disabling Strict Checks for Bytes Types --------------------------------------- By default, web3 is strict when it comes to hex and bytes values, as of \`\`v6\`\`. If an abi specifies a byte size, but the value that gets passed in is not the specified size, web3 will invalidate the value. For example, if an abi specifies a type of \`\`bytes4\`\`, web3 will invalidate the following values: .. list-table:: Invalid byte and hex strings with strict (default) bytes4 type checking :widths: 25 75 :header-rows: 1 \* - Input - Reason \* - \`\`''\`\` - Needs to be prefixed with a "0x" to be interpreted as an empty hex string \* - \`\`2\`\` - Wrong type \* - \`\`'ah'\`\` - String is not valid hex \* - \`\`'1234'\`\` - Needs to either be a bytestring (b'1234') or be a hex value of the right size, prefixed with 0x (in this case: '0x31323334') \* - \`\`b''\`\` - Needs to have exactly 4 bytes \* - \`\`b'ab'\`\` - Needs to have exactly 4 bytes \* - \`\`'0xab'\`\` - Needs to have exactly 4 bytes \* - \`\`'0x6162636464'\`\` - Needs to have exactly 4 bytes However, you may want to be less strict with acceptable values for bytes types. This may prove useful if you trust that values coming through are what they are meant to be with respect to the ABI. In this case, the automatic padding might be convenient for inferred types. For this, you can set the :meth:\`w3.strict\_bytes\_type\_checking\` flag to \`\`False\`\`, which is available on the Web3 instance. A Web3 instance which has this flag set to \`\`False\`\` will have a less strict set of rules on which values are accepted. A \`\`bytes\`\` type will allow values as a hex string, a bytestring, or a regular Python string that can be decoded as a hex. 0x-prefixed hex strings are also not required. - A Python string that is not prefixed with \`\`0x\`\` is valid. - A bytestring whose length is less than the specified byte size is valid. .. list-table:: Valid byte and hex strings for a non-strict bytes4 type :widths: 25 75 :header-rows: 1 \* - Input - Normalizes to \* - \`\`''\`\` - \`\`b'\\x00\\x00\\x00\\x00'\`\` \* - \`\`'0x'\`\` - \`\`b'\\x00\\x00\\x00\\x00'\`\` \* - \`\`b''\`\` - \`\`b'\\x00\\x00\\x00\\x00'\`\` \* - \`\`b'ab'\`\` - \`\`b'ab\\x00\\x00'\`\` \* - \`\`'0xab'\`\` - \`\`b'\\xab\\x00\\x00\\x00'\`\` \* - \`\`'1234'\`\` - \`\`b'\\x124\\x00\\x00'\`\` \* - \`\`'0x61626364'\`\` - \`\`b'abcd'\`\` \* - \`\`'1234'\`\` - \`\`b'1234'\`\` Taking the following contract code as an example: .. testsetup:: arrayscontract from web3 import Web3 w3 = Web3(Web3.EthereumTesterProvider()) bytecode = "608060405234801561001057600080fd5b506040516106103803806106108339810180604052602081101561003357600080fd5b81019080805164010000000081111561004b57600080fd5b8281019050602081018481111561006157600080fd5b815185602082028301116401000000008211171561007e57600080fd5b5050929190505050806000908051906020019061009c9291906100a3565b505061019c565b82805482825590600052602060002090600f0160109004810192821561015a5791602002820160005b8382111561012a57835183826101000a81548161ffff02191690837e010000000000000000000000000000000000000000000000000000000000009004021790555092602001926002016020816001010492830192600103026100cc565b80156101585782816101000a81549061ffff021916905560020160208160010104928301926001030261012a565b505b509050610167919061016b565b5090565b61019991905b8082111561019557600081816101000a81549061ffff021916905550600101610171565b5090565b90565b610465806101ab6000396000f3fe608060405260043610610051576000357c0100000000000000000000000000000000000000000000000000000000900480633b3230ee14610056578063d7c8a410146100e7578063dfe3136814610153575b600080fd5b34801561006257600080fd5b5061008f6004803603602081101561007957600080fd5b8101908080359060200190929190505050610218565b60405180827dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200191505060405180910390f35b3480156100f357600080fd5b506100fc61026c565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561013f578082015181840152602081019050610124565b505050509050019250505060405180910390f35b34801561015f57600080fd5b506102166004803603602081101561017657600080fd5b810190808035906020019064010000000081111561019357600080fd5b8201836020820111156101a557600080fd5b803590602001918460208302840111640100000000831117156101c757600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050509192919290505050610326565b005b60008181548110151561022757fe5b9060005260206000209060109182820401919006600202915054906101000a90047e010000000000000000000000000000000000000000000000000000000000000281565b6060600080548060200260200160405190810160405280929190818152602001828054801561031c57602002820191906000526020600020906000905b82829054906101000a90047e01000000000000000000000000000000000000000000000000000000000000027dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200190600201906020826001010492830192600103820291508084116102a95790505b5050505050905090565b806000908051906020019061033c929190610340565b5050565b82805482825590600052602060002090600f016010900481019282156103f75791602002820160005b838211156103c757835183826101000a81548161ffff02191690837e01000000000000000000000000000000000000000000000000000000000000900402179055509260200192600201602081600101049283019260010302610369565b80156103f55782816101000a81549061ffff02191690556002016020816001010492830192600103026103c7565b505b5090506104049190610408565b5090565b61043691905b8082111561043257600081816101000a81549061ffff02191690555060010161040e565b5090565b9056fea165627a7a72305820a8f9f1f4815c1eedfb8df31298a5cd13b198895de878871328b5d96296b69b4e0029" abi = ''' \[ { "constant": true, "inputs": \[ { "name": "", "type": "uint256" } \], "name": "bytes2Value", "outputs": \[ { "name": "", "type": "bytes2" } \], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": \[\], "name": "getBytes2Value", "outputs": \[ { "name": "", "type": "bytes2\[\]" } \], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": \[ { "name": "\_bytes2Value", "type": "bytes2\[\]" } \], "name": "setBytes2Value", "outputs": \[\], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": \[ { "name": "\_bytes2Value", "type": "bytes2\[\]" } \], "payable": false, "stateMutability": "nonpayable", "type": "constructor" } \] '''.strip() .. code-block:: 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..." .. doctest:: arrayscontract >>> arrays\_contract\_instance = w3.eth.contract(abi=abi, bytecode=bytecode) >>> tx\_hash = arrays\_contract\_instance.constructor(\[b'bb'\]).transact() >>> tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) >>> arrays\_contract = w3.eth.contract( ... address=tx\_receipt.contractAddress, ... abi=abi ... ) >>> arrays\_contract.functions.getBytes2Value().call() \[b'bb'\] >>> # set value with appropriate byte size >>> arrays\_contract.functions.setBytes2Value(\[b'aa'\]).transact({'gas': 420000, "maxPriorityFeePerGas": 10 \*\* 9, "maxFeePerGas": 10 \*\* 9}) HexBytes('0xcb95151142ea56dbf2753d70388aef202a7bb5a1e323d448bc19f1d2e1fe3dc9') >>> # check value >>> arrays\_contract.functions.getBytes2Value().call() \[b'aa'\] >>> # trying to set value without appropriate size (bytes2) is not valid >>> arrays\_contract.functions.setBytes2Value(\[b'b'\]).transact() Traceback (most recent call last): ... web3.exceptions.MismatchedABI: Could not identify the intended function with name >>> # check value is still b'aa' >>> arrays\_contract.functions.getBytes2Value().call() \[b'aa'\] >>> # disabling strict byte checking... >>> w3.strict\_bytes\_type\_checking = False >>> tx\_hash = arrays\_contract\_instance.constructor(\[b'b'\]).transact() >>> tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) >>> arrays\_contract = w3.eth.contract( ... address=tx\_receipt.contractAddress, ... abi=abi ... ) >>> # check value is zero-padded... i.e. b'b\\x00' >>> arrays\_contract.functions.getBytes2Value().call() \[b'b\\x00'\] >>> # set the flag back to True >>> w3.strict\_bytes\_type\_checking = True >>> arrays\_contract.functions.setBytes2Value(\[b'a'\]).transact() Traceback (most recent call last): ... web3.exceptions.MismatchedABI: Could not identify the intended function with name .. \_contract-functions: Contract Functions ------------------ The named functions exposed through the :py:attr:\`Contract.functions\` property are of the ContractFunction type. This class is not to be used directly, but instead through :py:attr:\`Contract.functions\`. For example: .. code-block:: python myContract = web3.eth.contract(address=contract\_address, abi=contract\_abi) twentyone = myContract.functions.multiply7(3).call() If you have the function name in a variable, you might prefer this alternative: .. code-block:: python func\_to\_call = 'multiply7' contract\_func = myContract.functions\[func\_to\_call\] twentyone = contract\_func(3).call() You can also interact with contract functions without parentheses if the function doesn't take any arguments. For example: .. code-block:: python >>> myContract.functions.return13.call() 13 >>> myContract.functions.return13().call() 13 In cases where functions are overloaded and use arguments of similar types, a function may resolve to an undesired function when using the method syntax. For example, given two functions with the same name that take a single argument of differing types of \`\`bytes\`\` and \`\`bytes32\`\`. When a reference to :meth:\`contract.functions.setBytes(b'1')\` is used, the function will resolve as the one that takes \`\`bytes\`\`. If a value is passed that was meant to be 32 bytes but the given argument was off by one, the function reference will still use the one that takes \`\`bytes\`\`. When in doubt, use explicit function references to the signature. Use bracket notation (:meth:\`contract.functions\["setBytes(bytes32)"\](b'')\`) or the contract API \`contract.get\_function\_by\_signature("setBytes(bytes32)")\` to retrieve the desired function. This will ensure an exception is raised if the argument is not strictly 32 bytes in length. .. py:class:: ContractFunction Attributes ~~~~~~~~~~ The :py:class:\`ContractFunction\` class provides attributes for each function. Access the function attributes through \`Contract.functions.myMethod\`. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).abi\_element\_identifier The signature of the function assigned to the class \`\`\_\_name\_\_\`\` during initialization. Fallback and Receive functions will be assigned as classes :py:class:\`FallbackFn\` or :py:class:\`RecieveFn\` respectively. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).name A string representing the function, receive or fallback name. Use :py:attr:\`ContractFunction.signature\` when the function arguments are needed. This is an alias of :py:attr:\`ContractFunction.fn\_name\`. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).signature A string representing the function, receive or fallback signature. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).selector A HexStr encoded from the first four bytes of the function signature. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).abi The function ABI with the type, name, inputs and outputs. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).arguments A tuple of all function inputs, normalized so that \`kwargs\` themselves are flattened into a tuple as returned by :py:meth:\`eth\_utils.abi.get\_normalized\_abi\_inputs\`. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).argument\_names The function input names. .. py:attribute:: ContractFunction.myMethod(\*args, \*\*kwargs).argument\_types The function input types. Methods ~~~~~~~ :py:class:\`ContractFunction\` provides methods to interact with contract functions. Positional and keyword arguments supplied to the contract function subclass will be used to find the contract function by signature, and forwarded to the contract function when applicable. \`EIP-3668 \`\_ introduced support for the \`\`OffchainLookup\`\` revert / CCIP Read support. CCIP Read is set to \`\`True\`\` for calls by default, as recommended in EIP-3668. This is done via a global \`\`global\_ccip\_read\_enabled\`\` flag on the provider. If raising the \`\`OffchainLookup\`\` revert is preferred for a specific call, the \`\`ccip\_read\_enabled\`\` flag on the call may be set to \`\`False\`\`. .. code-block:: python >>> # raises the revert instead of handling the offchain lookup >>> myContract.functions.revertsWithOffchainLookup(myData).call(ccip\_read\_enabled=False) \*\*\* web3.exceptions.OffchainLookup Disabling CCIP Read support can be useful if a transaction needs to be sent to the callback function. In such cases, "preflighting" with an \`\`eth\_call\`\`, handling the \`\`OffchainLookup\`\`, and sending the data via a transaction may be necessary. See :ref:\`ccip-read-example\` in the examples section for how to preflight a transaction with a contract call. Similarly, if CCIP Read is globally set to \`\`False\`\` via the \`\`global\_ccip\_read\_enabled\`\` flag on the provider, it may be enabled on a per-call basis - overriding the global flag. This ensures only explicitly enabled calls will handle the \`\`OffchainLookup\`\` revert appropriately. .. code-block:: python >>> # global flag set to \`False\` >>> w3.provider.global\_ccip\_read\_enabled = False >>> # does not raise the revert since explicitly enabled on the call: >>> response = myContract.functions.revertsWithOffchainLookup(myData).call(ccip\_read\_enabled=True) If the function called results in a \`\`revert\`\` error, a \`\`ContractLogicError\`\` will be raised. If there is an error message with the error, web3.py attempts to parse the message that comes back and return it to the user as the error string. As of v6.3.0, the raw data is also returned and can be accessed via the \`\`data\`\` attribute on \`\`ContractLogicError\`\`. .. py:method:: ContractFunction.transact(transaction) Execute the specified function by sending a new public transaction. Refer to the following invocation: .. code-block:: python myContract.functions.myMethod(\*args, \*\*kwargs).transact(transaction) The first portion of the function call \`\`myMethod(\*args, \*\*kwargs)\`\` selects the appropriate contract function based on the name and provided argument. Arguments can be provided as positional arguments, keyword arguments, or a mix of the two. The end portion of this function call \`\`transact(transaction)\`\` takes a single parameter which should be a python dictionary conforming to the same format as the \`\`web3.eth.send\_transaction(transaction)\`\` method. This dictionary may not contain the keys \`\`data\`\`. If any of the \`\`args\`\` or \`\`kwargs\`\` specified in the ABI are an \`\`address\`\` type, they will accept ENS names. If a \`\`gas\`\` value is not provided, then the \`\`gas\`\` value for the method transaction will be created using the \`\`web3.eth.estimate\_gas()\`\` method. Returns the transaction hash. .. code-block:: python >>> token\_contract.functions.transfer(web3.eth.accounts\[1\], 12345).transact() "0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd" .. py:method:: ContractFunction.call(transaction, block\_identifier='latest') Call a contract function, executing the transaction locally using the \`\`eth\_call\`\` API. This will not create a new public transaction. Refer to the following invocation: .. code-block:: python myContract.functions.myMethod(\*args, \*\*kwargs).call(transaction) This method behaves the same as the :py:meth:\`ContractFunction.transact\` method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion. Returns the return value of the executed function. .. code-block:: python >>> my\_contract.functions.multiply7(3).call() 21 >>> token\_contract.functions.myBalance().call({'from': web3.eth.accounts\[0\]}) 12345 # the token balance for \`web3.eth.accounts\[0\]\` >>> token\_contract.functions.myBalance().call({'from': web3.eth.accounts\[1\]}) 54321 # the token balance for the account \`web3.eth.accounts\[1\]\` You can call the method at a historical block using \`\`block\_identifier\`\`. Some examples: .. code-block:: python # You can call your contract method at a block number: >>> token\_contract.functions.myBalance().call(block\_identifier=10) # or a number of blocks back from pending, # in this case, the block just before the latest block: >>> token\_contract.functions.myBalance().call(block\_identifier=-2) # or a block hash: >>> token\_contract.functions.myBalance().call(block\_identifier='0x4ff4a38b278ab49f7739d3a4ed4e12714386a9fdf72192f2e8f7da7822f10b4d') >>> token\_contract.functions.myBalance().call(block\_identifier=b'O\\xf4\\xa3\\x8b\\'\\x8a\\xb4\\x9fw9\\xd3\\xa4\\xedN\\x12qC\\x86\\xa9\\xfd\\xf7!\\x92\\xf2\\xe8\\xf7\\xdax"\\xf1\\x0bM') # Latest is the default, so this is redundant: >>> token\_contract.functions.myBalance().call(block\_identifier='latest') # You can check the state after your pending transactions (if supported by your node): >>> token\_contract.functions.myBalance().call(block\_identifier='pending') Passing the \`\`block\_identifier\`\` parameter for past block numbers requires that your Ethereum API node is running in the more expensive archive node mode. Normally synced Ethereum nodes will fail with a "missing trie node" error, because Ethereum node may have purged the past state from its database. \`More information about archival nodes here \`\_. .. py:method:: ContractFunction.estimate\_gas(transaction, block\_identifier=None) Call a contract function, executing the transaction locally using the \`\`eth\_call\`\` API. This will not create a new public transaction. Refer to the following invocation: .. code-block:: python myContract.functions.myMethod(\*args, \*\*kwargs).estimate\_gas(transaction) This method behaves the same as the :py:meth:\`ContractFunction.transact\` method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion. Returns the amount of gas consumed which can be used as a gas estimate for executing this transaction publicly. .. code-block:: python >>> my\_contract.functions.multiply7(3).estimate\_gas() 42650 .. note:: The parameter \`\`block\_identifier\`\` is not enabled in geth nodes, hence passing a value of \`\`block\_identifier\`\` when connected to a geth nodes would result in an error like: \`\`ValueError: {'code': -32602, 'message': 'too many arguments, want at most 1'}\`\` .. py:method:: ContractFunction.build\_transaction(transaction) Builds a transaction dictionary based on the contract function call specified. Refer to the following invocation: .. code-block:: python myContract.functions.myMethod(\*args, \*\*kwargs).build\_transaction(transaction) This method behaves the same as the :py:meth:\`Contract.transact\` method, with transaction details being passed into the end portion of the function call, and function arguments being passed into the first portion. .. note:: \`nonce\` is not returned as part of the transaction dictionary unless it is specified in the first portion of the function call: .. code-block:: python >>> math\_contract.functions.increment(5).build\_transaction({'nonce': 10}) You may use :meth:\`~web3.eth.Eth.getTransactionCount\` to get the current nonce for an account. Therefore a shortcut for producing a transaction dictionary with nonce included looks like: .. code-block:: python >>> math\_contract.functions.increment(5).build\_transaction({'nonce': web3.eth.get\_transaction\_count('0xF5...')}) Returns a transaction dictionary. This transaction dictionary can then be sent using :meth:\`~web3.eth.Eth.send\_transaction\`. Additionally, the dictionary may be used for offline transaction signing using :meth:\`~web3.eth.account.Account.sign\_transaction\`. .. code-block:: python >>> math\_contract.functions.increment(5).build\_transaction({'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000}) { 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'data': '0x7cf5dab00000000000000000000000000000000000000000000000000000000000000005', 'value': 0, 'gas': 43242, 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'chainId': 1 } .. \_fallback-function: Fallback Function ~~~~~~~~~~~~~~~~~ The Contract Factory also offers an API to interact with the fallback function, which supports four methods like normal functions: .. py:method:: Contract.fallback.call(transaction) Call fallback function, executing the transaction locally using the \`\`eth\_call\`\` API. This will not create a new public transaction. .. py:method:: Contract.fallback.estimate\_gas(transaction) Call fallback function and return the gas estimation. .. py:method:: Contract.fallback.transact(transaction) Execute fallback function by sending a new public transaction. .. py:method:: Contract.fallback.build\_transaction(transaction) Builds a transaction dictionary based on the contract fallback function call. Contract Events --------------- The named events exposed through the :py:attr:\`Contract.events\` property are of the ContractEvent type. This class is not to be used directly, but instead through :py:attr:\`Contract.events\`. For example: .. code-block:: python myContract = web3.eth.contract(address=contract\_address, abi=contract\_abi) tx\_hash = myContract.functions.myFunction().transact() receipt = web3.eth.get\_transaction\_receipt(tx\_hash) myContract.events.myEvent().process\_receipt(receipt) .. py:class:: ContractEvent Attributes ~~~~~~~~~~ The :py:class:\`ContractEvent\` class provides attributes for each event. Access the event attributes through \`Contract.events.myEvent\`. .. py:attribute:: ContractEvent.myEvent(\*args, \*\*kwargs).abi\_element\_identifier The signature of the event assigned to the class \`\`\_\_name\_\_\`\` during initialization. .. py:attribute:: ContractEvent.myEvent(\*args, \*\*kwargs).name A string representing the event, receive or fallback name. Use :py:attr:\`ContractEvent.myEvent(\*args, \*\*kwargs).signature\` when the event arguments are needed. This is an alias of :py:attr:\`ContractEvent.myEvent(\*args, \*\*kwargs).event\_name\`. .. py:attribute:: ContractEvent.myEvent(\*args, \*\*kwargs).signature A string representing the event signature. .. py:attribute:: ContractEvent.myEvent(\*args, \*\*kwargs).abi The event ABI with the type, name, inputs. .. py:attribute:: ContractEvent.myEvent(\*args, \*\*kwargs).argument\_names The event input names. .. py:attribute:: ContractEvent.myEvent(\*args, \*\*kwargs).argument\_types The event input types. Methods ~~~~~~~ :py:class:\`ContractEvent\` provides methods to interact with contract events. Positional and keyword arguments supplied to the contract event subclass will be used to find the contract event by signature. .. \_contract\_get\_logs: .. py:method:: ContractEvent.get\_logs(from\_block=None, to\_block="latest", block\_hash=None, argument\_filters={}) :noindex: Fetches all logs for a given event within the specified block range or block hash. Returns a list of decoded event logs sorted by \`\`logIndex\`\`. \`\`argument\_filters\`\` is an optional dictionary argument that can be used to filter for logs where the event's argument values match the values provided in the dictionary. The keys must match the event argument names as they exist in the ABI. The values can either be a single value or a list of values to match against. If a list is provided, the logs will be filtered for any logs that match any of the values in the list. Indexed arguments are filtered pre-call by building specific \`\`topics\`\` to filter for. Non-indexed arguments are filtered by the library after the logs are fetched from the node. .. code-block:: python my\_contract = web3.eth.contract(address=contract\_address, abi=contract\_abi) # get \`\`myEvent\`\` logs from block 1337 to block 2337 where the value for the # event argument "eventArg1" is either 1, 2, or 3 my\_contract.events.myEvent().get\_logs( argument\_filters={"eventArg1": \[1, 2, 3\]}, from\_block=1337, to\_block=2337, ) .. \_process\_receipt: .. py:method:: ContractEvent.process\_receipt(transaction\_receipt, errors=WARN) :noindex: Extracts the pertinent logs from a transaction receipt. If there are no errors, \`\`process\_receipt\`\` returns a tuple of :ref:\`Event Log Objects \`, emitted from the event (e.g. \`\`myEvent\`\`), with decoded output. .. code-block:: python >>> tx\_hash = contract.functions.myFunction(12345).transact({'to':contract\_address}) >>> tx\_receipt = w3.eth.get\_transaction\_receipt(tx\_hash) >>> rich\_logs = contract.events.myEvent().process\_receipt(tx\_receipt) >>> rich\_logs\[0\]\['args'\] {'myArg': 12345} If there are errors, the logs will be handled differently depending on the flag that is passed in: - \`\`WARN\`\` (default) - logs a warning to the console for the log that has an error, and discards the log. Returns any logs that are able to be processed. - \`\`STRICT\`\` - stops all processing and raises the error encountered. - \`\`IGNORE\`\` - returns any raw logs that raised an error with an added "errors" field, along with any other logs were able to be processed. - \`\`DISCARD\`\` - silently discards any logs that have errors, and returns processed logs that don't have errors. An event log error flag needs to be imported from \`\`web3/logs.py\`\`. .. code-block:: python >>> tx\_hash = contract.functions.myFunction(12345).transact({'to':contract\_address}) >>> tx\_receipt = w3.eth.get\_transaction\_receipt(tx\_hash) >>> processed\_logs = contract.events.myEvent().process\_receipt(tx\_receipt) >>> processed\_logs ( AttributeDict({ 'args': AttributeDict({}), 'event': 'myEvent', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('0xfb95ccb6ab39e19821fb339dee33e7afe2545527725b61c64490a5613f8d11fa'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('0xd74c3e8bdb19337987b987aee0fa48ed43f8f2318edfc84e3a8643e009592a68'), 'blockNumber': 3 }) ) # Or, if there were errors encountered during processing: >>> from web3.logs import STRICT, IGNORE, DISCARD, WARN >>> processed\_logs = contract.events.myEvent().process\_receipt(tx\_receipt, errors=IGNORE) >>> processed\_logs ( AttributeDict({ 'type': 'mined', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('0x01682095d5abb0270d11a31139b9a1f410b363c84add467004e728ec831bd529'), 'blockHash': HexBytes('0x92abf9325a3959a911a2581e9ea36cba3060d8b293b50e5738ff959feb95258a'), 'blockNumber': 5, 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'data': '0x0000000000000000000000000000000000000000000000000000000000003039', 'topics': \[ HexBytes('0xf70fe689e290d8ce2b2a388ac28db36fbb0e16a6d89c6804c461f65a1b40bb15') \], 'errors': LogTopicError('Expected 1 log topics. Got 0')}) }) ) >>> processed\_logs = contract.events.myEvent().process\_receipt(tx\_receipt, errors=DISCARD) >>> assert processed\_logs == () True .. py:method:: ContractEvent.process\_log(log) Similar to process\_receipt\_, but only processes one log at a time, instead of a whole transaction receipt. Will return a single :ref:\`Event Log Object \` if there are no errors encountered during processing. If an error is encountered during processing, it will be raised. .. code-block:: python >>> tx\_hash = contract.functions.myFunction(12345).transact({'to':contract\_address}) >>> tx\_receipt = w3.eth.get\_transaction\_receipt(tx\_hash) >>> log\_to\_process = tx\_receipt\['logs'\]\[0\] >>> processed\_log = contract.events.myEvent().process\_log(log\_to\_process) >>> processed\_log AttributeDict({ 'args': AttributeDict({}), 'event': 'myEvent', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('0xfb95ccb6ab39e19821fb339dee33e7afe2545527725b61c64490a5613f8d11fa'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('0xd74c3e8bdb19337987b987aee0fa48ed43f8f2318edfc84e3a8643e009592a68'), 'blockNumber': 3 }) .. \_event-log-object: Event Log Object ~~~~~~~~~~~~~~~~ The Event Log Object is a python dictionary with the following keys: \* \`\`args\`\`: Dictionary - The arguments coming from the event. \* \`\`event\`\`: String - The event name. \* \`\`logIndex\`\`: Number - integer of the log index position in the block. \* \`\`transactionIndex\`\`: Number - integer of the transactions index position log was created from. \* \`\`transactionHash\`\`: String, 32 Bytes - hash of the transactions this log was created from. \* \`\`address\`\`: String, 32 Bytes - address from which this log originated. \* \`\`blockHash\`\`: String, 32 Bytes - hash of the block where this log was in. null when it's pending. \* \`\`blockNumber\`\`: Number - the block number where this log was in. null when it's pending. .. testsetup:: create\_filter from web3 import Web3 from hexbytes import HexBytes w3 = Web3(Web3.EthereumTesterProvider()) bytecode = '6060604052341561000c57fe5b604051602080610acb833981016040528080519060200190919050505b620f42408114151561003b5760006000fd5b670de0b6b3a76400008102600281905550600254600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b505b610a27806100a46000396000f30060606040523615610097576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde0314610099578063095ea7b31461013257806318160ddd1461018957806323b872dd146101af578063313ce5671461022557806370a082311461025157806395d89b411461029b578063a9059cbb14610334578063dd62ed3e1461038b575bfe5b34156100a157fe5b6100a96103f4565b60405180806020018281038252838181518152602001915080519060200190808383600083146100f8575b8051825260208311156100f8576020820191506020810190506020830392506100d4565b505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013a57fe5b61016f600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061042e565b604051808215151515815260200191505060405180910390f35b341561019157fe5b610199610521565b6040518082815260200191505060405180910390f35b34156101b757fe5b61020b600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610527565b604051808215151515815260200191505060405180910390f35b341561022d57fe5b610235610791565b604051808260ff1660ff16815260200191505060405180910390f35b341561025957fe5b610285600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610796565b6040518082815260200191505060405180910390f35b34156102a357fe5b6102ab6107e0565b60405180806020018281038252838181518152602001915080519060200190808383600083146102fa575b8051825260208311156102fa576020820191506020810190506020830392506102d6565b505050905090810190601f1680156103265780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561033c57fe5b610371600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061081a565b604051808215151515815260200191505060405180910390f35b341561039357fe5b6103de600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610973565b6040518082815260200191505060405180910390f35b604060405190810160405280600981526020017f54657374546f6b656e000000000000000000000000000000000000000000000081525081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60025481565b600081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410806105f1575081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054105b156105fc5760006000fd5b81600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b9392505050565b601281565b6000600060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b604060405190810160405280600481526020017f544553540000000000000000000000000000000000000000000000000000000081525081565b600081600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156108695760006000fd5b81600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b929150505600a165627a7a723058205071371ee2a4a1be3c96e77d939cdc26161a256fdd638efc08bd33dfc65d3b850029' ABI = '\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_spender","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_from","type":"address"},{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"},{"name":"\_spender","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"inputs":\[{"name":"\_totalSupply","type":"uint256"}\],"payable":false,"type":"constructor","stateMutability":"nonpayable"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Approval","type":"event"}\]' my\_token\_contract = w3.eth.contract(abi=ABI, bytecode=bytecode) alice, bob = w3.eth.accounts\[0\], w3.eth.accounts\[1\] assert alice == '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', alice assert bob == '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF', bob tx\_hash = my\_token\_contract.constructor(1000000).transact({'from': alice, 'gas': 899000, 'gasPrice': Web3.to\_wei(1, 'gwei')}) assert tx\_hash == HexBytes('0x49e3da72a95e4074a9eaea7b438c73ca154627d317e58abeae914e3769a15044'), tx\_hash txn\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) assert txn\_receipt\['contractAddress'\] == '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', txn\_receipt\['contractAddress'\] contract\_address = txn\_receipt\['contractAddress'\] contract = w3.eth.contract(contract\_address, abi=ABI) total\_supply = contract.functions.totalSupply().call() decimals = 10 \*\* 18 assert total\_supply == 1000000 \* decimals, total\_supply tx\_hash = contract.functions.transfer(alice, 10).transact({'gas': 899000, 'gasPrice': Web3.to\_wei(1, 'gwei')}) tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) .. doctest:: create\_filter >>> transfer\_filter = my\_token\_contract.events.Transfer.create\_filter(from\_block="0x0", argument\_filters={'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf'}) >>> transfer\_filter.get\_new\_entries() \[AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'value': 10}), 'event': 'Transfer', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('0x9da859237e7259832b913d51cb128c8d73d1866056f7a41b52003c953e749678'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('...'), 'blockNumber': 2})\] >>> transfer\_filter.get\_new\_entries() \[\] >>> tx\_hash = contract.functions.transfer(alice, 10).transact({'gas': 899000, 'gasPrice': 1000000000}) >>> tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) >>> transfer\_filter.get\_new\_entries() \[AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'value': 10}), 'event': 'Transfer', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('...'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('...'), 'blockNumber': 3})\] >>> transfer\_filter.get\_all\_entries() \[AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'value': 10}), 'event': 'Transfer', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('...'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('...'), 'blockNumber': 2}), AttributeDict({'args': AttributeDict({'from': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'to': '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'value': 10}), 'event': 'Transfer', 'logIndex': 0, 'transactionIndex': 0, 'transactionHash': HexBytes('...'), 'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', 'blockHash': HexBytes('...'), 'blockNumber': 3})\] Utils ----- .. py:classmethod:: Contract.decode\_function\_input(data) Decodes the transaction data used to invoke a smart contract function, and returns :py:class:\`ContractFunction\` and decoded parameters as :py:class:\`dict\`. .. code-block:: python >>> transaction = w3.eth.get\_transaction('0x5798fbc45e3b63832abc4984b0f3574a13545f415dd672cd8540cd71f735db56') >>> transaction.input '0x612e45a3000000000000000000000000b656b2a9c3b2416437a811e07466ca712f5a5b5a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000093a80000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000116c6f6e656c792c20736f206c6f6e656c7900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' >>> contract.decode\_function\_input(transaction.input) (, {'\_recipient': '0xB656b2a9c3b2416437A811e07466cA712F5a5b5a', '\_amount': 0, '\_description': b'lonely, so lonely', '\_transactionData': b'', '\_debatingPeriod': 604800, '\_newCurator': True}) ContractCaller -------------- .. py:class:: ContractCaller The \`\`ContractCaller\`\` class provides an API to call functions in a contract. This class is not to be used directly, but instead through \`\`Contract.caller\`\`. There are a number of different ways to invoke the \`\`ContractCaller\`\`. For example: .. testsetup:: contractcaller import json from web3 import Web3 w3 = Web3(Web3.EthereumTesterProvider()) bytecode = "0x606060405261022e806100126000396000f360606040523615610074576000357c01000000000000000000000000000000000000000000000000000000009004806316216f391461007657806361bc221a146100995780637cf5dab0146100bc578063a5f3c23b146100e8578063d09de08a1461011d578063dcf537b11461014057610074565b005b610083600480505061016c565b6040518082815260200191505060405180910390f35b6100a6600480505061017f565b6040518082815260200191505060405180910390f35b6100d26004808035906020019091905050610188565b6040518082815260200191505060405180910390f35b61010760048080359060200190919080359060200190919050506101ea565b6040518082815260200191505060405180910390f35b61012a6004805050610201565b6040518082815260200191505060405180910390f35b6101566004808035906020019091905050610217565b6040518082815260200191505060405180910390f35b6000600d9050805080905061017c565b90565b60006000505481565b6000816000600082828250540192505081905550600060005054905080507f3496c3ede4ec3ab3686712aa1c238593ea6a42df83f98a5ec7df9834cfa577c5816040518082815260200191505060405180910390a18090506101e5565b919050565b6000818301905080508090506101fb565b92915050565b600061020d6001610188565b9050610214565b90565b60006007820290508050809050610229565b91905056" 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 .. doctest:: contractcaller >>> myContract = w3.eth.contract(address=address, abi=ABI) >>> twentyone = myContract.caller.multiply7(3) >>> twentyone 21 It can also be invoked using parentheses: .. doctest:: contractcaller >>> twentyone = myContract.caller().multiply7(3) >>> twentyone 21 And a transaction dictionary, with or without the \`\`transaction\`\` keyword. You can also optionally include a block identifier. For example: .. doctest:: contractcaller >>> from\_address = w3.eth.accounts\[1\] >>> twentyone = myContract.caller({'from': from\_address}).multiply7(3) >>> twentyone 21 >>> twentyone = myContract.caller(transaction={'from': from\_address}).multiply7(3) >>> twentyone 21 >>> twentyone = myContract.caller(block\_identifier='latest').multiply7(3) >>> twentyone 21 Like :py:class:\`ContractFunction\`, :py:class:\`ContractCaller\` provides methods to interact with contract functions. Positional and keyword arguments supplied to the contract caller subclass will be used to find the contract function by signature, and forwarded to the contract function when applicable. Examples -------- Working with an ERC-20 Token Contract ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Most fungible tokens on the Ethereum blockchain conform to the \`ERC-20\`\_ standard. This section of the guide covers interacting with an existing token contract which conforms to this standard. .. testsetup:: from web3 import Web3 from hexbytes import HexBytes w3 = Web3(Web3.EthereumTesterProvider()) bytecode = '6060604052341561000c57fe5b604051602080610acb833981016040528080519060200190919050505b620f42408114151561003b5760006000fd5b670de0b6b3a76400008102600281905550600254600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b505b610a27806100a46000396000f30060606040523615610097576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde0314610099578063095ea7b31461013257806318160ddd1461018957806323b872dd146101af578063313ce5671461022557806370a082311461025157806395d89b411461029b578063a9059cbb14610334578063dd62ed3e1461038b575bfe5b34156100a157fe5b6100a96103f4565b60405180806020018281038252838181518152602001915080519060200190808383600083146100f8575b8051825260208311156100f8576020820191506020810190506020830392506100d4565b505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013a57fe5b61016f600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061042e565b604051808215151515815260200191505060405180910390f35b341561019157fe5b610199610521565b6040518082815260200191505060405180910390f35b34156101b757fe5b61020b600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610527565b604051808215151515815260200191505060405180910390f35b341561022d57fe5b610235610791565b604051808260ff1660ff16815260200191505060405180910390f35b341561025957fe5b610285600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610796565b6040518082815260200191505060405180910390f35b34156102a357fe5b6102ab6107e0565b60405180806020018281038252838181518152602001915080519060200190808383600083146102fa575b8051825260208311156102fa576020820191506020810190506020830392506102d6565b505050905090810190601f1680156103265780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561033c57fe5b610371600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061081a565b604051808215151515815260200191505060405180910390f35b341561039357fe5b6103de600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610973565b6040518082815260200191505060405180910390f35b604060405190810160405280600981526020017f54657374546f6b656e000000000000000000000000000000000000000000000081525081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60025481565b600081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410806105f1575081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054105b156105fc5760006000fd5b81600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555081600060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b9392505050565b601281565b6000600060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b604060405190810160405280600481526020017f544553540000000000000000000000000000000000000000000000000000000081525081565b600081600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156108695760006000fd5b81600060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b929150505600a165627a7a723058205071371ee2a4a1be3c96e77d939cdc26161a256fdd638efc08bd33dfc65d3b850029' ABI = '\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_spender","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_from","type":"address"},{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"type":"function","stateMutability":"view"},{"constant":false,"inputs":\[{"name":"\_to","type":"address"},{"name":"\_value","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"type":"function","stateMutability":"nonpayable"},{"constant":true,"inputs":\[{"name":"\_owner","type":"address"},{"name":"\_spender","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"type":"function","stateMutability":"view"},{"inputs":\[{"name":"\_totalSupply","type":"uint256"}\],"payable":false,"type":"constructor","stateMutability":"nonpayable"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}\],"name":"Approval","type":"event"}\]' factory = w3.eth.contract(abi=ABI, bytecode=bytecode) alice, bob = w3.eth.accounts\[0\], w3.eth.accounts\[1\] assert alice == '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf', alice assert bob == '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF', bob tx\_hash = factory.constructor(1000000).transact({'from': alice, 'gas': 899000, 'gasPrice': Web3.to\_wei(1, 'gwei')}) assert tx\_hash == HexBytes('0x49e3da72a95e4074a9eaea7b438c73ca154627d317e58abeae914e3769a15044'), tx\_hash txn\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) assert txn\_receipt\['contractAddress'\] == '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b', txn\_receipt\['contractAddress'\] contract\_address = txn\_receipt\['contractAddress'\] contract = w3.eth.contract(contract\_address, abi=ABI) total\_supply = contract.functions.totalSupply().call() decimals = 10 \*\* 18 assert total\_supply == 1000000 \* decimals, total\_supply In this guide we will interact with an existing token contract that we have already deployed to a local testing chain. This guide assumes: 1. An existing token contract at a known address. 2. Access to the proper \`\`ABI\`\` for the given contract. 3. A \`\`web3.main.Web3\`\` instance connected to a provider with an unlocked account which can send transactions. Creating the contract factory \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` First we need to create a contract instance with the address of our token contract and the \`\`ERC-20\`\` ABI. .. doctest:: >>> contract = w3.eth.contract(contract\_address, abi=ABI) >>> contract.address '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b' Querying token metadata \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Each token will have a total supply which represents the total number of tokens in circulation. In this example we've initialized the token contract to have 1 million tokens. Since this token contract is setup to have 18 decimal places, the raw total supply returned by the contract is going to have 18 additional decimal places. .. doctest:: >>> contract.functions.name().call() 'TestToken' >>> contract.functions.symbol().call() 'TEST' >>> decimals = contract.functions.decimals().call() >>> decimals 18 >>> DECIMALS = 10 \*\* decimals >>> contract.functions.totalSupply().call() // DECIMALS 1000000 Query account balances \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Next we can query some account balances using the contract's \`\`balanceOf\`\` function. The token contract we are using starts with a single account which we'll refer to as \`\`alice\`\` holding all of the tokens. .. doctest:: >>> alice = '0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf' >>> bob = '0x2B5AD5c4795c026514f8317c7a215E218DcCD6cF' >>> raw\_balance = contract.functions.balanceOf(alice).call() >>> raw\_balance 1000000000000000000000000 >>> raw\_balance // DECIMALS 1000000 >>> contract.functions.balanceOf(bob).call() 0 Sending tokens \`\`\`\`\`\`\`\`\`\`\`\`\`\` Next we can transfer some tokens from \`\`alice\`\` to \`\`bob\`\` using the contract's \`\`transfer\`\` function. .. doctest:: >>> tx\_hash = contract.functions.transfer(bob, 100).transact({'from': alice}) >>> tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) >>> contract.functions.balanceOf(alice).call() 999999999999999999999900 >>> contract.functions.balanceOf(bob).call() 100 Creating an approval for external transfers \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Alice could also \*approve\* someone else to spend tokens from her account using the \`\`approve\`\` function. We can also query how many tokens we're approved to spend using the \`\`allowance\`\` function. .. doctest:: >>> contract.functions.allowance(alice, bob).call() 0 >>> tx\_hash = contract.functions.approve(bob, 200).transact({'from': alice}) >>> tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) >>> contract.functions.allowance(alice, bob).call() 200 Performing an external transfer \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` When someone has an allowance they can transfer those tokens using the \`\`transferFrom\`\` function. .. doctest:: >>> contract.functions.allowance(alice, bob).call() 200 >>> contract.functions.balanceOf(bob).call() 100 >>> tx\_hash = contract.functions.transferFrom(alice, bob, 75).transact({'from': bob}) >>> tx\_receipt = w3.eth.wait\_for\_transaction\_receipt(tx\_hash) >>> contract.functions.allowance(alice, bob).call() 125 >>> contract.functions.balanceOf(bob).call() 175 .. \_ERC-20: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-20.md Using a struct as a function argument ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ web3.py accepts struct arguments as dictionaries. This format also supports nested structs. Let's take a look at a quick example. Given the following Solidity contract: .. code-block:: none contract Example { address addr; struct S1 { address a1; address a2; } struct S2 { bytes32 b1; bytes32 b2; } struct X { S1 s1; S2 s2; address\[\] users; } function update(X memory x) public { addr = x.s1.a2; } function retrieve() public view returns (address) { return addr; } } You can interact with the web3.py contract API as follows: .. code-block:: python # deploy or lookup the deployed contract, then: >>> deployed\_contract.functions.retrieve().call() '0x0000000000000000000000000000000000000000' >>> deployed\_contract.functions.update({'s1': \['0x0000000000000000000000000000000000000001', '0x0000000000000000000000000000000000000002'\], 's2': \[b'0'\*32, b'1'\*32\], 'users': \[\]}).transact() >>> deployed\_contract.functions.retrieve().call() '0x0000000000000000000000000000000000000002' .. \_ambiguous-contract-functions: Invoke Ambiguous Contract Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Calling overloaded functions can be done as you would expect. Passing arguments will disambiguate which function you want to call. For example, if you have a contract with two functions with the name \`\`identity\`\` that accept different types of arguments, you can call them like this: .. code-block:: python >>> ambiguous\_contract = w3.eth.contract(address=..., abi=...) >>> ambiguous\_contract.functions.identity(1, True).call() 1 >>> ambiguous\_contract.functions.identity("one", 1, True).call() 1 If there is a need to first retrieve the function, you can use the contract instance's \`\`get\_function\_by\_signature\`\` method to get the function you want to call. Below is an example of a contract that has multiple functions of the same name, and the arguments are ambiguous. You can use the :meth:\`Contract.get\_function\_by\_signature\` method to reference the intended function and call it with the correct arguments. .. code-block:: python >>> contract\_source\_code = """ pragma solidity ^0.8.24; contract AmbiguousDuo { function identity(uint256 input, bool uselessFlag) public pure returns (uint256) { return input; } function identity(int256 input, bool uselessFlag) public pure returns (int256) { return input; } } """ # fast forward all the steps of compiling and deploying the contract. >>> identity\_func = ambiguous\_contract.get\_function\_by\_signature('identity(uint256,bool)') >>> identity\_func(1, True) \>>> identity\_func(1, True).call() 1 .. \_ccip-read-example: CCIP Read support for offchain lookup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Contract calls support CCIP Read by default, via a \`\`ccip\_read\_enabled\`\` flag on the call and, more globally, a \`\`global\_ccip\_read\_enabled\`\` flag on the provider. The following should work by default without raising an \`\`OffchainLookup\`\` and instead handling it appropriately as per the specification outlined in \`EIP-3668 \`\_. .. code-block:: python myContract.functions.revertsWithOffchainLookup(myData).call() If the offchain lookup requires the user to send a transaction rather than make a call, this may be handled appropriately in the following way: .. code-block:: python from web3 import Web3, WebSocketProvider from web3.utils import handle\_offchain\_lookup w3 = Web3(WebSocketProvider(...)) myContract = w3.eth.contract(address=...) myData = b'data for offchain lookup function call' # preflight with an \`eth\_call\` and handle the exception try: myContract.functions.revertsWithOffchainLookup(myData).call(ccip\_read\_enabled=False) except OffchainLookup as ocl: tx = {'to': myContract.address, 'from': my\_account} data\_for\_callback\_function = handle\_offchain\_lookup(ocl.payload) tx\['data'\] = data\_for\_callback\_function # send the built transaction with \`eth\_sendTransaction\` or sign and send with \`eth\_sendRawTransaction\` tx\_hash = w3.eth.send\_transaction(tx) Contract Unit Tests in Python ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is an example of how one can use the \`pytest\`\_ framework in python, web3.py, eth-tester, and PyEVM to perform unit tests entirely in python without any additional need for a full featured ethereum node/client. To install needed dependencies you can use the pinned extra for testing: .. \_pytest: https://docs.pytest.org/en/latest/ .. code-block:: bash $ pip install web3\[test\] pytest Once you have an environment set up for testing, you can then write your tests like so: .. include:: ../tests/core/contracts/test\_contract\_example.py :code: python :start-line: 1 --- # Index — web3.py 7.6.1 documentation * [](index.html) * Index * * * Index ===== [**A**](#A) | [**B**](#B) | [**C**](#C) | [**D**](#D) | [**E**](#E) | [**F**](#F) | [**G**](#G) | [**H**](#H) | [**I**](#I) | [**K**](#K) | [**L**](#L) | [**M**](#M) | [**N**](#N) | [**O**](#O) | [**P**](#P) | [**R**](#R) | [**S**](#S) | [**T**](#T) | [**U**](#U) | [**V**](#V) | [**W**](#W) A - | | | | --- | --- | | * [abi (web3.contract.Contract attribute)](web3.contract.html#web3.contract.Contract.abi)

* [accounts (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.accounts)

* [add() (Web3.middleware\_onion method)](middleware.html#Web3.middleware_onion.add)

* [add\_peer() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.add_peer)

* [address (web3.contract.Contract attribute)](web3.contract.html#web3.contract.Contract.address)

* [address() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.address)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.address) | * [AddressMismatch](ens.html#ens.exceptions.AddressMismatch)

* [all\_events() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.all_events)

* [all\_functions() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.all_functions)

* [api (web3.Web3 attribute)](web3.main.html#web3.Web3.api)

* [async\_handle\_offchain\_lookup() (web3.utils.abi.utils method)](web3.utils.html#web3.utils.abi.utils.async_handle_offchain_lookup)

* [AsyncENS (class in ens.async\_ens)](ens.html#ens.async_ens.AsyncENS)

* [AsyncEthereumTesterProvider (class in web3.providers.eth\_tester)](providers.html#web3.providers.eth_tester.AsyncEthereumTesterProvider)

* [attach\_modules() (web3.w3 method)](web3.main.html#web3.w3.attach_modules) | B - | | | | --- | --- | | * [backoff\_factor (web3.providers.rpc.utils.ExceptionRetryConfiguration attribute)](internals.html#web3.providers.rpc.utils.ExceptionRetryConfiguration.backoff_factor)

* [batch\_requests() (web3.Web3 method)](web3.main.html#web3.Web3.batch_requests)

* [BidTooLow](ens.html#ens.exceptions.BidTooLow)

* [blob\_base\_fee() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.blob_base_fee)

* [block\_number (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.block_number) | * [BlockFilter (class in web3.utils.filters)](filters.html#web3.utils.filters.BlockFilter)

* [build\_filter() (web3.contract.Contract.events.your\_event\_name class method)](web3.contract.html#web3.contract.Contract.events.your_event_name.build_filter)

* [build\_transaction() (web3.contract.Contract.fallback method)](web3.contract.html#web3.contract.Contract.fallback.build_transaction)
* [(web3.contract.ContractFunction method)](web3.contract.html#web3.contract.ContractFunction.build_transaction)

* [bytecode (web3.contract.Contract attribute)](web3.contract.html#web3.contract.Contract.bytecode)

* [bytecode\_runtime (web3.contract.Contract attribute)](web3.contract.html#web3.contract.Contract.bytecode_runtime) | C - | | | | --- | --- | | * [call() (web3.contract.Contract.fallback method)](web3.contract.html#web3.contract.Contract.fallback.call)
* [(web3.contract.ContractFunction method)](web3.contract.html#web3.contract.ContractFunction.call)

* [(web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.call)

* [chain\_id (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.chain_id)

* [check\_if\_arguments\_can\_be\_encoded() (in module web3.utils.abi)](web3.utils.html#web3.utils.abi.check_if_arguments_can_be_encoded)

* [clear() (Web3.middleware\_onion method)](middleware.html#Web3.middleware_onion.clear)

* [client\_version (web3.Web3 attribute)](web3.main.html#web3.Web3.client_version)

* [construct\_time\_based\_gas\_price\_strategy() (in module web3.gas\_strategies.time\_based)](gas_price.html#web3.gas_strategies.time_based.construct_time_based_gas_price_strategy) | * [constructor() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.constructor)

* [content() (web3.geth.txpool.TxPool method)](web3.geth.html#web3.geth.txpool.TxPool.content)

* [Contract (class in web3.contract)](web3.contract.html#web3.contract.Contract)

* [contract() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.contract)

* [ContractCaller (class in web3.contract)](web3.contract.html#web3.contract.ContractCaller)

* [ContractEvent (class in web3.contract)](web3.contract.html#web3.contract.ContractEvent)

* [ContractFunction (class in web3.contract)](web3.contract.html#web3.contract.ContractFunction)

* [create\_access\_list() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.create_access_list)

* [create\_filter() (web3.contract.Contract.events.your\_event\_name class method)](web3.contract.html#web3.contract.Contract.events.your_event_name.create_filter) | D - | | | | --- | --- | | * [datadir() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.datadir)

* [decode\_function\_input() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.decode_function_input) | * [decode\_tuples (web3.contract.Contract attribute)](web3.contract.html#web3.contract.Contract.decode_tuples)

* [default\_account (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.default_account)

* [default\_block (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.default_block) | E - | | | | --- | --- | | * [encode\_abi() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.encode_abi)

* ens
* [module](ens.html#module-ens)

* [ENS (class in ens.ens)](ens.html#ens.ens.ENS)

* ens.async\_ens
* [module](ens.html#module-ens.async_ens)

* ens.ens
* [module](ens.html#module-ens.ens)

* ens.exceptions
* [module](ens.html#module-ens.exceptions)

* [ENSException](ens.html#ens.exceptions.ENSException) | * [ENSTypeError](ens.html#ens.exceptions.ENSTypeError)

* [ENSValidationError](ens.html#ens.exceptions.ENSValidationError)

* [ENSValueError](ens.html#ens.exceptions.ENSValueError)

* [errors (web3.providers.rpc.utils.ExceptionRetryConfiguration attribute)](internals.html#web3.providers.rpc.utils.ExceptionRetryConfiguration.errors)

* [estimate\_gas() (web3.contract.Contract.fallback method)](web3.contract.html#web3.contract.Contract.fallback.estimate_gas)
* [(web3.contract.ContractFunction method)](web3.contract.html#web3.contract.ContractFunction.estimate_gas)

* [(web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.estimate_gas)

* [Eth (class in web3.eth)](web3.eth.html#web3.eth.Eth)

* [eth (web3.Web3 attribute)](web3.main.html#web3.Web3.eth)

* [EthereumTesterProvider (class in web3.providers.eth\_tester)](providers.html#web3.providers.eth_tester.EthereumTesterProvider)

* [events (web3.contract.Contract attribute)](web3.contract.html#web3.contract.Contract.events) | F - | | | | --- | --- | | * [fee\_history() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.fee_history)

* [Filter (class in web3.utils.filters)](filters.html#web3.utils.filters.Filter)

* [filter() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.filter)

* [filter\_id (web3.utils.filters.Filter attribute)](filters.html#web3.utils.filters.Filter.filter_id)

* [find\_events\_by\_name() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.find_events_by_name)

* [find\_events\_by\_selector() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.find_events_by_selector)

* [find\_events\_by\_topic() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.find_events_by_topic) | * [find\_functions\_by\_args() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.find_functions_by_args)

* [find\_functions\_by\_name() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.find_functions_by_name)

* [format\_entry() (web3.utils.filters.Filter method)](filters.html#web3.utils.filters.Filter.format_entry)

* [from\_web3() (ens.async\_ens.AsyncENS class method)](ens.html#ens.async_ens.AsyncENS.from_web3)
* [(ens.ens.ENS class method)](ens.html#ens.ens.ENS.from_web3)

* [from\_wei() (web3.Web3 method)](web3.main.html#web3.Web3.from_wei)

* [functions (web3.contract.Contract attribute)](web3.contract.html#web3.contract.Contract.functions) | G - | | | | --- | --- | | * [gas\_price (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.gas_price)

* [generate\_gas\_price() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.generate_gas_price)

* [get\_abi\_element() (in module web3.utils.abi)](web3.utils.html#web3.utils.abi.get_abi_element)

* [get\_abi\_element\_info() (in module web3.utils.abi)](web3.utils.html#web3.utils.abi.get_abi_element_info)

* [get\_all\_entries() (web3.utils.filters.Filter method)](filters.html#web3.utils.filters.Filter.get_all_entries)

* [get\_attestations() (Beacon method)](web3.beacon.html#Beacon.get_attestations)

* [get\_attester\_slashings() (Beacon method)](web3.beacon.html#Beacon.get_attester_slashings)

* [get\_balance() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_balance)

* [get\_beacon\_heads() (Beacon method)](web3.beacon.html#Beacon.get_beacon_heads)

* [get\_beacon\_state() (Beacon method)](web3.beacon.html#Beacon.get_beacon_state)

* [get\_blob\_sidecars() (Beacon method)](web3.beacon.html#Beacon.get_blob_sidecars)

* [get\_block() (Beacon method)](web3.beacon.html#Beacon.get_block)
* [(web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_block)

* [get\_block\_attestations() (Beacon method)](web3.beacon.html#Beacon.get_block_attestations)

* [get\_block\_header() (Beacon method)](web3.beacon.html#Beacon.get_block_header)

* [get\_block\_headers() (Beacon method)](web3.beacon.html#Beacon.get_block_headers)

* [get\_block\_number() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_block_number)

* [get\_block\_root() (Beacon method)](web3.beacon.html#Beacon.get_block_root)

* [get\_block\_transaction\_count() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_block_transaction_count)

* [get\_code() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_code)

* [get\_create2\_address() (web3.utils.abi.utils method)](web3.utils.html#web3.utils.abi.utils.get_create2_address)

* [get\_create\_address() (web3.utils.abi.utils method)](web3.utils.html#web3.utils.abi.utils.get_create_address)

* [get\_deposit\_contract() (Beacon method)](web3.beacon.html#Beacon.get_deposit_contract)

* [get\_epoch\_committees() (Beacon method)](web3.beacon.html#Beacon.get_epoch_committees)

* [get\_event\_abi() (in module web3.utils.abi)](web3.utils.html#web3.utils.abi.get_event_abi)

* [get\_event\_by\_name() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_event_by_name)

* [get\_event\_by\_selector() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_event_by_selector)

* [get\_event\_by\_signature() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_event_by_signature)

* [get\_event\_by\_topic() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_event_by_topic)

* [get\_event\_log\_topics() (in module web3.utils.abi)](web3.utils.html#web3.utils.abi.get_event_log_topics)

* [get\_filter\_changes() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_filter_changes)

* [get\_filter\_logs() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_filter_logs)

* [get\_finality\_checkpoint() (Beacon method)](web3.beacon.html#Beacon.get_finality_checkpoint)

* [get\_fork\_data() (Beacon method)](web3.beacon.html#Beacon.get_fork_data) | * [get\_fork\_schedule() (Beacon method)](web3.beacon.html#Beacon.get_fork_schedule)

* [get\_function\_by\_args() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_function_by_args)

* [get\_function\_by\_name() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_function_by_name)

* [get\_function\_by\_selector() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_function_by_selector)

* [get\_function\_by\_signature() (web3.contract.Contract class method)](web3.contract.html#web3.contract.Contract.get_function_by_signature)

* [get\_genesis() (Beacon method)](web3.beacon.html#Beacon.get_genesis)

* [get\_hash\_root() (Beacon method)](web3.beacon.html#Beacon.get_hash_root)

* [get\_health() (Beacon method)](web3.beacon.html#Beacon.get_health)

* [get\_logs() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_logs)

* [get\_new\_entries() (web3.utils.filters.Filter method)](filters.html#web3.utils.filters.Filter.get_new_entries)

* [get\_node\_identity() (Beacon method)](web3.beacon.html#Beacon.get_node_identity)

* [get\_peer() (Beacon method)](web3.beacon.html#Beacon.get_peer)

* [get\_peers() (Beacon method)](web3.beacon.html#Beacon.get_peers)

* [get\_proof() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_proof)

* [get\_proposer\_slashings() (Beacon method)](web3.beacon.html#Beacon.get_proposer_slashings)

* [get\_raw\_transaction() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_raw_transaction)

* [get\_raw\_transaction\_by\_block() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_raw_transaction_by_block)

* [get\_spec() (Beacon method)](web3.beacon.html#Beacon.get_spec)

* [get\_storage\_at() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_storage_at)

* [get\_syncing() (Beacon method)](web3.beacon.html#Beacon.get_syncing)

* [get\_text() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.get_text)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.get_text)

* [get\_transaction() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_transaction)

* [get\_transaction\_by\_block() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_transaction_by_block)

* [get\_transaction\_count() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_transaction_count)

* [get\_transaction\_receipt() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_transaction_receipt)

* [get\_uncle\_by\_block() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_uncle_by_block)

* [get\_uncle\_count() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.get_uncle_count)

* [get\_validator() (Beacon method)](web3.beacon.html#Beacon.get_validator)

* [get\_validator\_balances() (Beacon method)](web3.beacon.html#Beacon.get_validator_balances)

* [get\_validators() (Beacon method)](web3.beacon.html#Beacon.get_validators)

* [get\_version() (Beacon method)](web3.beacon.html#Beacon.get_version)

* [get\_voluntary\_exits() (Beacon method)](web3.beacon.html#Beacon.get_voluntary_exits)

* [geth (web3.Web3 attribute)](web3.main.html#web3.Web3.geth) | H - | | | | --- | --- | | * [handle\_offchain\_lookup() (web3.utils.abi.utils method)](web3.utils.html#web3.utils.abi.utils.handle_offchain_lookup) | * [HTTPProvider (web3.Web3 attribute)](web3.main.html#web3.Web3.HTTPProvider) | I - | | | | --- | --- | | * [inject() (Web3.middleware\_onion method)](middleware.html#Web3.middleware_onion.inject)

* [inspect() (web3.geth.txpool.TxPool method)](web3.geth.html#web3.geth.txpool.TxPool.inspect)

* [InvalidBidHash](ens.html#ens.exceptions.InvalidBidHash)

* [InvalidLabel](ens.html#ens.exceptions.InvalidLabel)

* [InvalidName](ens.html#ens.exceptions.InvalidName) | * [IPCProvider (web3.Web3 attribute)](web3.main.html#web3.Web3.IPCProvider)

* [is\_address() (web3.Web3 method)](web3.main.html#web3.Web3.is_address)

* [is\_checksum\_address() (web3.Web3 method)](web3.main.html#web3.Web3.is_checksum_address)

* [is\_connected() (BaseProvider method)](internals.html#BaseProvider.is_connected)

* [is\_encodable() (web3.w3 method)](web3.main.html#web3.w3.is_encodable)

* [is\_valid\_entry() (web3.utils.filters.Filter method)](filters.html#web3.utils.filters.Filter.is_valid_entry) | K - * [keccak() (web3.Web3 class method)](web3.main.html#web3.Web3.keccak) L - | | | | --- | --- | | * [listening() (in module web3.net)](web3.net.html#web3.net.listening)

* [LocalFilterMiddleware() (web3.middleware method)](middleware.html#web3.middleware.LocalFilterMiddleware) | * [log\_topic\_to\_bytes() (in module web3.utils.abi)](web3.utils.html#web3.utils.abi.log_topic_to_bytes)

* [LogFilter (class in web3.utils.filters)](filters.html#web3.utils.filters.LogFilter) | M - * [make\_request() (BaseProvider method)](internals.html#BaseProvider.make_request) * [(web3.providers.persistent.persistent\_connection.PersistentConnection method)](providers.html#web3.providers.persistent.persistent_connection.PersistentConnection.make_request) * [max\_priority\_fee (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.max_priority_fee) * [method (web3.\_utils.caching.RequestInformation attribute)](internals.html#web3._utils.caching.RequestInformation.method) * [method\_allowlist (web3.providers.rpc.utils.ExceptionRetryConfiguration attribute)](internals.html#web3.providers.rpc.utils.ExceptionRetryConfiguration.method_allowlist) * [middleware (BaseProvider attribute)](internals.html#BaseProvider.middleware) * [(Web3.middleware\_onion attribute)](middleware.html#Web3.middleware_onion.middleware) * [middleware\_response\_processors (web3.\_utils.caching.RequestInformation attribute)](internals.html#web3._utils.caching.RequestInformation.middleware_response_processors) * [modify\_transaction() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.modify_transaction) * module * [ens](ens.html#module-ens) * [ens.async\_ens](ens.html#module-ens.async_ens) * [ens.ens](ens.html#module-ens.ens) * [ens.exceptions](ens.html#module-ens.exceptions) * [web3](web3.main.html#module-web3) * [web3.contract](web3.contract.html#module-web3.contract) * [web3.eth](web3.eth.html#module-web3.eth) * [web3.gas\_strategies.rpc](gas_price.html#module-web3.gas_strategies.rpc) * [web3.gas\_strategies.time\_based](gas_price.html#module-web3.gas_strategies.time_based) * [web3.geth](web3.geth.html#module-web3.geth) * [web3.geth.admin](web3.geth.html#module-web3.geth.admin) * [web3.geth.debug](web3.geth.html#module-web3.geth.debug) * [web3.geth.txpool](web3.geth.html#module-web3.geth.txpool) * [web3.net](web3.net.html#module-web3.net) * [web3.tracing](web3.tracing.html#module-web3.tracing) * [web3.utils](web3.utils.html#module-web3.utils) * [web3.utils.abi](web3.utils.html#module-web3.utils.abi) * [web3.utils.filters](filters.html#module-web3.utils.filters) N - | | | | --- | --- | | * [name() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.name)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.name) | * [node\_info() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.node_info) | O - | | | | --- | --- | | * [OversizeTransaction](ens.html#ens.exceptions.OversizeTransaction) | * [owner() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.owner)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.owner) | P - | | | | --- | --- | | * [params (web3.\_utils.caching.RequestInformation attribute)](internals.html#web3._utils.caching.RequestInformation.params)

* [peer\_count() (in module web3.net)](web3.net.html#web3.net.peer_count) | * [peers() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.peers)

* [process\_log() (web3.contract.ContractEvent method)](web3.contract.html#web3.contract.ContractEvent.process_log)

* [process\_subscriptions() (web3.providers.persistent.persistent\_connection.PersistentConnection method)](providers.html#web3.providers.persistent.persistent_connection.PersistentConnection.process_subscriptions) | R - | | | | --- | --- | | * [recv() (web3.providers.persistent.persistent\_connection.PersistentConnection method)](providers.html#web3.providers.persistent.persistent_connection.PersistentConnection.recv)

* [remove() (Web3.middleware\_onion method)](middleware.html#Web3.middleware_onion.remove)

* [replace() (Web3.middleware\_onion method)](middleware.html#Web3.middleware_onion.replace)

* [replace\_transaction() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.replace_transaction)

* [resolver() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.resolver)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.resolver) | * [ResolverNotFound](ens.html#ens.exceptions.ResolverNotFound)

* [response\_formatters (web3.\_utils.caching.RequestInformation attribute)](internals.html#web3._utils.caching.RequestInformation.response_formatters)

* [retries (web3.providers.rpc.utils.ExceptionRetryConfiguration attribute)](internals.html#web3.providers.rpc.utils.ExceptionRetryConfiguration.retries)

* [rpc\_gas\_price\_strategy() (in module web3.gas\_strategies.rpc)](gas_price.html#web3.gas_strategies.rpc.rpc_gas_price_strategy) | S - | | | | --- | --- | | * [send() (web3.providers.persistent.persistent\_connection.PersistentConnection method)](providers.html#web3.providers.persistent.persistent_connection.PersistentConnection.send)

* [send\_raw\_transaction() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.send_raw_transaction)

* [send\_transaction() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.send_transaction)

* [set\_contract\_factory() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.set_contract_factory)

* [set\_data\_filters() (web3.utils.filters.LogFilter method)](filters.html#web3.utils.filters.LogFilter.set_data_filters)

* [set\_gas\_price\_strategy() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.set_gas_price_strategy)

* [set\_text() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.set_text)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.set_text)

* [setup\_address() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.setup_address)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.setup_address)

* [setup\_name() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.setup_name)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.setup_name)

* [setup\_owner() (ens.async\_ens.AsyncENS method)](ens.html#ens.async_ens.AsyncENS.setup_owner)
* [(ens.ens.ENS method)](ens.html#ens.ens.ENS.setup_owner)

* [sign() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.sign)

* [sign\_transaction() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.sign_transaction) | * [sign\_typed\_data() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.sign_typed_data)

* [SignAndSendRawMiddlewareBuilder() (web3.middleware method)](middleware.html#web3.middleware.SignAndSendRawMiddlewareBuilder)

* [socket](providers.html#socket)

* [solidity\_keccak() (web3.Web3 class method)](web3.main.html#web3.Web3.solidity_keccak)

* [StalecheckMiddlewareBuilder() (web3.middleware method)](middleware.html#web3.middleware.StalecheckMiddlewareBuilder)

* [start\_http() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.start_http)

* [start\_ws() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.start_ws)

* [status() (web3.geth.txpool.TxPool method)](web3.geth.html#web3.geth.txpool.TxPool.status)

* [stop\_http() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.stop_http)

* [stop\_ws() (in module web3.geth.admin)](web3.geth.html#web3.geth.admin.stop_ws)

* [strict\_bytes\_type\_checking (ens attribute)](ens_overview.html#ens.strict_bytes_type_checking)
* [(web3.w3 attribute)](web3.main.html#web3.w3.strict_bytes_type_checking)

* [subscribe() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.subscribe)

* [subscription\_id (web3.\_utils.caching.RequestInformation attribute)](internals.html#web3._utils.caching.RequestInformation.subscription_id)

* [subscriptions (web3.providers.persistent.persistent\_connection.PersistentConnection attribute)](providers.html#web3.providers.persistent.persistent_connection.PersistentConnection.subscriptions)

* [syncing (web3.eth.Eth attribute)](web3.eth.html#web3.eth.Eth.syncing) | T - | | | | --- | --- | | * [to\_bytes() (web3.Web3 method)](web3.main.html#web3.Web3.to_bytes)

* [to\_checksum\_address() (web3.Web3 method)](web3.main.html#web3.Web3.to_checksum_address)

* [to\_hex() (web3.Web3 method)](web3.main.html#web3.Web3.to_hex)

* [to\_int() (web3.Web3 method)](web3.main.html#web3.Web3.to_int)

* [to\_json() (web3.Web3 method)](web3.main.html#web3.Web3.to_json)

* [to\_text() (web3.Web3 method)](web3.main.html#web3.Web3.to_text)

* [to\_wei() (web3.Web3 method)](web3.main.html#web3.Web3.to_wei)

* [trace\_block() (in module web3.tracing)](web3.tracing.html#web3.tracing.trace_block)

* [trace\_call() (in module web3.tracing)](web3.tracing.html#web3.tracing.trace_call) | * [trace\_filter() (in module web3.tracing)](web3.tracing.html#web3.tracing.trace_filter)

* [trace\_raw\_transaction() (in module web3.tracing)](web3.tracing.html#web3.tracing.trace_raw_transaction)

* [trace\_replay\_block\_transactions() (in module web3.tracing)](web3.tracing.html#web3.tracing.trace_replay_block_transactions)

* [trace\_replay\_transaction() (in module web3.tracing)](web3.tracing.html#web3.tracing.trace_replay_transaction)

* [trace\_transaction() (in module web3.tracing)](web3.tracing.html#web3.tracing.trace_transaction)
* [(web3.geth.debug.Debug method)](web3.geth.html#web3.geth.debug.Debug.trace_transaction)

* [transact() (web3.contract.Contract.fallback method)](web3.contract.html#web3.contract.Contract.fallback.transact)
* [(web3.contract.ContractFunction method)](web3.contract.html#web3.contract.ContractFunction.transact)

* [TransactionFilter (class in web3.utils.filters)](filters.html#web3.utils.filters.TransactionFilter) | U - | | | | --- | --- | | * [UnauthorizedError](ens.html#ens.exceptions.UnauthorizedError)

* [UnderfundedBid](ens.html#ens.exceptions.UnderfundedBid)

* [uninstall\_filter() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.uninstall_filter) | * [UnownedName](ens.html#ens.exceptions.UnownedName)

* [unsubscribe() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.unsubscribe)

* [UnsupportedFunction](ens.html#ens.exceptions.UnsupportedFunction)

* [utils.SimpleCache (class in web3.utils.abi)](web3.utils.html#web3.utils.abi.utils.SimpleCache) | V - * [version() (in module web3.net)](web3.net.html#web3.net.version) W - | | | | --- | --- | | * [wait\_for\_transaction\_receipt() (web3.eth.Eth method)](web3.eth.html#web3.eth.Eth.wait_for_transaction_receipt)

* web3
* [module](web3.main.html#module-web3)

* [Web3 (class in web3)](web3.main.html#web3.Web3)

* [web3.\_utils.caching.RequestInformation (built-in class)](internals.html#web3._utils.caching.RequestInformation)

* web3.contract
* [module](web3.contract.html#module-web3.contract)

* web3.eth
* [module](web3.eth.html#module-web3.eth)

* web3.gas\_strategies.rpc
* [module](gas_price.html#module-web3.gas_strategies.rpc)

* web3.gas\_strategies.time\_based
* [module](gas_price.html#module-web3.gas_strategies.time_based)

* web3.geth
* [module](web3.geth.html#module-web3.geth)

* web3.geth.admin
* [module](web3.geth.html#module-web3.geth.admin)

* web3.geth.debug
* [module](web3.geth.html#module-web3.geth.debug)

* web3.geth.txpool
* [module](web3.geth.html#module-web3.geth.txpool)

* [web3.middleware.AttributeDictMiddleware (built-in class)](middleware.html#web3.middleware.AttributeDictMiddleware)

* [web3.middleware.BufferedGasEstimateMiddleware (built-in class)](middleware.html#web3.middleware.BufferedGasEstimateMiddleware) | * [web3.middleware.ENSNameToAddressMiddleware (built-in class)](middleware.html#web3.middleware.ENSNameToAddressMiddleware)

* [web3.middleware.ExtraDataToPOAMiddleware (built-in class)](middleware.html#web3.middleware.ExtraDataToPOAMiddleware)

* [web3.middleware.GasPriceStrategyMiddleware (built-in class)](middleware.html#web3.middleware.GasPriceStrategyMiddleware)

* [web3.middleware.ValidationMiddleware (built-in class)](middleware.html#web3.middleware.ValidationMiddleware)

* web3.net
* [module](web3.net.html#module-web3.net)

* [web3.providers.ipc.IPCProvider (built-in class)](providers.html#web3.providers.ipc.IPCProvider)

* [web3.providers.legacy\_websocket.LegacyWebSocketProvider (built-in class)](providers.html#web3.providers.legacy_websocket.LegacyWebSocketProvider)

* [web3.providers.persistent.AsyncIPCProvider (built-in class)](providers.html#web3.providers.persistent.AsyncIPCProvider)

* [web3.providers.persistent.persistent\_connection.PersistentConnection (built-in class)](providers.html#web3.providers.persistent.persistent_connection.PersistentConnection)

* [web3.providers.persistent.PersistentConnectionProvider (built-in class)](providers.html#web3.providers.persistent.PersistentConnectionProvider)

* [web3.providers.persistent.request\_processor.RequestProcessor (built-in class)](internals.html#web3.providers.persistent.request_processor.RequestProcessor)

* [web3.providers.persistent.WebSocketProvider (built-in class)](providers.html#web3.providers.persistent.WebSocketProvider)

* [web3.providers.rpc.AsyncHTTPProvider (built-in class)](providers.html#web3.providers.rpc.AsyncHTTPProvider)

* [web3.providers.rpc.HTTPProvider (built-in class)](providers.html#web3.providers.rpc.HTTPProvider)

* [web3.providers.rpc.utils.ExceptionRetryConfiguration (built-in class)](internals.html#web3.providers.rpc.utils.ExceptionRetryConfiguration)

* web3.tracing
* [module](web3.tracing.html#module-web3.tracing)

* web3.utils
* [module](web3.utils.html#module-web3.utils)

* web3.utils.abi
* [module](web3.utils.html#module-web3.utils.abi)

* web3.utils.filters
* [module](filters.html#module-web3.utils.filters) | --- # Unknown Migration Guide =============== .. \_migrating\_v6\_to\_v7: Migrating from v6 to v7 ----------------------- web3.py follows \`Semantic Versioning \`\_, which means that version 7 introduced backwards-incompatible changes. If you're upgrading from web3.py \`\`v6\`\` or earlier, you can expect to need to make some changes. Refer to this guide for a summary of breaking changes when updating from \`\`v6\`\` to \`\`v7\`\`. If you are more than one major version behind, you should also review the migration guides for the versions in between. Provider Updates ~~~~~~~~~~~~~~~~ WebSocketProvider \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` \`\`WebsocketProviderV2\`\`, introduced in web3.py \`\`v6\`\`, has taken priority over the legacy \`\`WebsocketProvider\`\`. The \`\`LegacyWebSocketProvider\`\` has been deprecated in \`\`v7\`\` and is slated for removal in the next major version of the library. In summary: - \`\`WebsocketProvider\`\` -> \`\`LegacyWebSocketProvider\`\` (and deprecated) - \`\`WebsocketProviderV2\`\` -> \`\`WebSocketProvider\`\` If migrating from \`\`WebSocketProviderV2\`\` to \`\`WebSocketProvider\`\`, you can expect the following changes: - Instantiation no longer requires the \`\`persistant\_websocket\`\` method: .. code-block:: python # WebsocketsProviderV2: AsyncWeb3.persistent\_websocket(WebsocketProviderV2('...')) # WebSocketProvider: AsyncWeb3(WebSocketProvider('...')) - Handling incoming subscription messages now occurs under a more flexible namespace: \`\`socket\`\`. The \`\`AsyncIPCProvider\`\` uses the same API to listen for messages via an IPC socket. .. code-block:: python # WebsocketsProviderV2: async for message in w3.ws.process\_subscriptions(): ... # WebSocketProvider: async for message in w3.socket.process\_subscriptions(): ... AsyncIPCProvider (non-breaking feature) \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` An asynchronous IPC provider, \`\`AsyncIPCProvider\`\`, is newly available in \`\`v7\`\`. This provider makes use of some of the same internals that the new \`\`WebSocketProvider\`\` introduced, allowing it to also support \`\`eth\_subscription\`\`. EthereumTesterProvider \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` \`\`EthereumTesterProvider\`\` now returns \`\`input\`\` instead of \`\`data\`\` for \`\`eth\_getTransaction\*\`\` calls, as expected. Middlewares -> Middleware ~~~~~~~~~~~~~~~~~~~~~~~~~ All references to \`\`middlewares\`\` have been replaced with the more grammatically correct \`\`middleware\`\`. Notably, this includes when a provider needs to be instantiated with custom middleware. Class-Based Middleware Model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The middleware model has been changed to a class-based model. .. code-block:: python # v6 (no longer supported) from web3.middleware import pythonic\_middleware w3.middleware\_onion.add(pythonic\_middleware) # v7 from web3.middleware import PythonicMiddleware w3.middleware\_onion.add(PythonicMiddleware) Previously, middleware were defined as functions that tightly wrapped the provider's \`\`make\_request\`\` function, where transformations could be conditionally applied before and after the request was made. Now, middleware logic can be separated into \`\`request\_processor\`\` and \`\`response\_processor\`\` functions that enable pre-request and post-response logic, respectively. This change offers a simpler, clearer interface for defining middleware, gives more flexibility for asynchronous operations and also paved the way for supporting :ref:\`batch\_requests\`. Major changes for migration are highlighted in this section. Consult the :ref:\`middleware\_internals\` section of the documentation for specifics and examples on the new class-based design. Middleware Builder Classes ~~~~~~~~~~~~~~~~~~~~~~~~~~ In \`\`v6\`\`, certain middleware needed to be constructed with parameters. This was done by passing the parameters to a constructor method. .. code-block:: python # v6 (no longer supported) from web3.middleware import construct\_sign\_and\_send\_raw\_middleware w3.middleware\_onion.add(construct\_sign\_and\_send\_raw\_middleware(private\_key)) In the class-based \`\`v7\`\` middleware model, a middleware builder class is instantiated with the necessary parameters via the \`\`build()\`\` method. .. code-block:: python # v7 from web3.middleware import SignAndSendRawMiddlewareBuilder w3.middleware\_onion.inject(SignAndSendRawMiddlewareBuilder.build(private\_key), layer=0) Middleware Renaming and Removals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following middleware have been renamed for generalization or clarity: - \`\`name\_to\_address\_middleware\`\` -> \`\`ENSNameToAddressMiddleware\`\` - \`\`geth\_poa\_middleware\`\` -> \`\`ExtraDataToPOAMiddleware\`\` The following middleware have been removed: ABI Middleware \`\`\`\`\`\`\`\`\`\`\`\`\`\` \`\`abi\_middleware\`\` is no longer necessary and has been removed. All of the functionality of the \`\`abi\_middleware\`\` was already handled by web3.py's ABI formatters. For additional context: a bug in the ENS name-to-address middleware would override the formatters. Fixing this bug has removed the need for the \`\`abi\_middleware\`\`. Caching Middleware \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The following middleware have been removed: - \`\`simple\_cache\_middleware\`\` - \`\`latest\_block\_based\_cache\_middleware\`\` - \`\`time\_based\_cache\_middleware\`\` All caching middleware has been removed in favor of a decorator/wrapper around the \`\`make\_request\`\` methods of providers with configuration options on the provider class. The configuration options are outlined in the documentation in the :ref:\`request\_caching\` section. If desired, the previous caching middleware can be re-created using the new class-based middleware model overriding the \`\`wrap\_make\_request\`\` (or \`\`async\_wrap\_make\_request\`\`) method in the middleware class. Result Generating Middleware \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The following middleware have been removed: - \`\`fixture\_middleware\`\` - \`\`result\_generator\_middleware\`\` The \`\`fixture\_middleware\`\` and \`\`result\_generator\_middleware\`\` which were used for testing/mocking purposes have been removed. These have been replaced internally by the \`\`RequestMocker\`\` class, utilized for testing via a \`\`request\_mocker\`\` pytest fixture. HTTP Retry Request Middleware \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The \`\`http\_retry\_request\_middleware\`\` has been removed in favor of a configuration option on the \`\`HTTPProvider\`\` and \`\`AsyncHTTPProvider\`\` classes. The configuration options are outlined in the documentation in the :ref:\`http\_retry\_requests\` section. Normalize Request Parameters Middleware \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The \`\`normalize\_request\_parameters\`\` middleware was not used anywhere internally and has been removed. Remaining camelCase -> snake\_case Updates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following arguments have been renamed across the library from camelCase to snake\_case in all methods where they are passed in as a kwarg. - \`\`fromBlock\`\` -> \`\`from\_block\`\` - \`\`toBlock\`\` -> \`\`to\_block\`\` - \`\`blockHash\`\` -> \`\`block\_hash\`\` Note that if a dictionary is used instead, say to a call such as \`eth\_getLogs\`, the keys in the dictionary should be camelCase. This is because the dictionary is passed directly to the JSON-RPC request, where the keys are expected to be in camelCase. Changes to Exception Handling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All Python standard library exceptions that were raised from within web3.py have been replaced with custom \`\`Web3Exception\`\` classes. This change allows for better control over exception handling, being able to distinguish between exceptions raised by web3.py and those raised from elsewhere in a codebase. The following exceptions have been replaced: - \`\`AssertionError\`\` -> \`\`Web3AssertionError\`\` - \`\`ValueError\`\` -> \`\`Web3ValueError\`\` - \`\`TypeError\`\` -> \`\`Web3TypeError\`\` - \`\`AttributeError\`\` -> \`\`Web3AttributeError\`\` A new \`\`MethodNotSupported\`\` exception is now raised when a method is not supported by web3.py. This allows a user to distinguish between when a method is not available on the current provider, \`\`MethodUnavailable\`\`, and when a method is not supported by web3.py under certain conditions, \`\`MethodNotSupported\`\`. A \`\`MismatchedABI\`\` exception is now raised instead of a \`\`Web3ValidationError\`\` in cases where an ABI is not compatible with the data being passed to it. This change allows for more specific error handling when using certain ABI types. JSON-RPC Error Handling \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Rather than a \`\`ValueError\`\` being replaced with a \`\`Web3ValueError\`\` when a JSON-RPC response comes back with an \`\`error\`\` object, a new \`\`Web3RPCError\`\` exception is now raised to provide more distinction for JSON-RPC error responses. Some previously existing exceptions now extend from this class since they too are related to JSON-RPC errors: - \`\`MethodUnavailable\`\` - \`\`BlockNotFound\`\` - \`\`TransactionNotFound\`\` - \`\`TransactionIndexingInProgress\`\` End of Support and Feature Removals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Python 3.7 Support Dropped \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Python 3.7 support has been dropped in favor of Python 3.8+. Python 3.7 is no longer supported by the Python core team, and we want to focus our efforts on supporting the latest versions of Python. EthPM Module Removed \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The EthPM module has been removed from the library. It was not widely used and has not been functional since around October 2022. It was deprecated in \`\`v6\`\` and has been completely removed in \`\`v7\`\`. Types in the \`eth\_typing.ethpm \`\_ module have been deprecated and will be removed from \`\`eth-typing\`\` in the next major release. Geth Miner Namespace Removed \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The \`\`geth.miner\`\` namespace, deprecated in \`\`v6\`\`, has been removed in \`\`v7\`\`. The \`\`miner\`\` namespace was used for managing the concept of a miner in geth. This is no longer a feature in geth and is planned for complete removal in the future, with Ethereum having transitioned to proof-of-stake. Geth Personal Namespace Removed \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The \`\`geth.personal\`\` namespace, deprecated in \`\`v6\`\`, has been removed in \`\`v7\`\`. The \`\`personal\`\` namespace was used for managing accounts and keys and was deprecated in geth in \`\`v1.11.0\`\`. Geth has moved to using \`\`clef\`\` for account and key management. ABI Types Removed \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The type definitions for ABIs, deprecated in \`\`v6\`\`, have been removed in \`\`v7\`\`. New types have been introduced in the \`\`eth\_typing\`\` \`\`v5\`\` package for ABIs. Improvements have been made to make required types more explicit and to offer better semantics. The following types from \`\`web3.types\`\` have been removed: - \`\`ABIEventParams\`\` is no longer avaiable. Use \`\`ABIComponentIndexed\`\` from \`\`eth\_typing\`\` to represent event input components. - \`\`ABIEvent\`\` now resides in \`\`eth\_typing\`\`. \`\`ABIEvent.type\`\` and \`\`ABIEvent.name\`\` are now required fields. - \`\`ABIFunctionComponents\`\` and \`\`ABIFunctionParams\`\` are no longer available. Use \`\`ABIComponent\`\` from \`\`eth\_typing\`\` to represent function input components. - \`\`ABIFunction\`\` now resides in \`\`eth\_typing\`\`. \`\`ABIFunction.type\`\` and \`\`ABIFunction.name\`\` are now required fields. - \`\`ABIElement\`\` now resides in \`\`eth\_typing\`\` and represents a \`\`Union\`\` of all valid ABI element types, \`\`ABICallable\`\`, \`\`ABIEvent\`\` and \`\`ABIError\`\`. Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`\`LRU\`\` has been removed from the library and dependency on \`\`lru-dict\`\` library was dropped. - \`\`CallOverride\`\` type was changed to \`\`StateOverride\`\` since more methods than \`\`eth\_call\`\` utilize the state override params. - \`\`User-Agent\`\` header was changed to a more readable format. - \`\`BaseContractFunctions\`\` iterator now returns instances of \`\`ContractFunction\`\` rather than the function names. - \`\`BaseContractFunction\`\` class attribute \`\`function\_identifier\`\` has been removed in favor of the \`\`abi\_element\_identifier\`\` attribute. - \`\`web3.contract.utils.call\_contract\_function()\`\` no longers uses \`\`fn\_abi\`\` as a parameter. Instead, the \`\`abi\_callable\`\` parameter of type \`\`ABICallable\`\` is used. - Beacon API filename change: \`\`beacon/main.py\`\` -> \`\`beacon/beacon.py\`\`. - The asynchronous version of \`\`w3.eth.wait\_for\_transaction\_receipt()\`\` changes its signature to use \`\`Optional\[float\]\`\` instead of \`\`float\`\` since it may be \`\`None\`\`. - \`\`get\_default\_ipc\_path()\`\` and \`\`get\_dev\_ipc\_path()\`\` now return the path value without checking if the \`\`geth.ipc\`\` file exists. - \`\`Web3.is\_address()\`\` returns \`\`True\`\` for non-checksummed addresses. - \`\`Contract.encodeABI()\`\` has been renamed to \`\`Contract.encode\_abi()\`\`. The \`\`fn\_name\`\` argument has been changed to \`\`abi\_element\_identifier\`\`. - JSON-RPC responses are now more strictly validated against the JSON-RPC 2.0 specification while providing more informative error messages for invalid responses. .. \_migrating\_v5\_to\_v6: Migrating from v5 to v6 ----------------------- web3.py follows \`Semantic Versioning \`\_, which means that version 6 introduced backwards-incompatible changes. If your project depends on web3.py v6, then you'll probably need to make some changes. Breaking Changes: Strict Bytes Checking by Default ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ web3.py v6 moved to requiring strict bytes checking by default. This means that if an ABI specifies a \`\`bytes4\`\` argument, web3.py will invalidate any entry that is not encodable as a bytes type with length of 4. This means only 0x-prefixed hex strings with a length of 4 and bytes types with a length of 4 will be considered valid. This removes doubt that comes from inferring values and assuming they should be padded. This behavior was previously available in via the \`\`w3.enable\_strict\_bytes\_checking()\`\` method. This is now, however, a toggleable flag on the \`\`Web3\`\` instance via the \`\`w3.strict\_bytes\_type\_checking\`\` property. As outlined above, this property is set to \`\`True\`\` by default but can be toggled on and off via the property's setter (e.g. \`\`w3.strict\_bytes\_type\_checking = False\`\`). Snake Case ~~~~~~~~~~ web3.py v6 moved to the more Pythonic convention of snake\_casing wherever possible. There are some exceptions to this pattern: - Contract methods and events use whatever is listed in the ABI. If the smart contract convention is to use camelCase for method and event names, web3.py won't do any magic to convert it to snake\_casing. - Arguments to JSON-RPC methods. For example: transaction and filter parameters still use camelCasing. The reason for this is primarily due to error messaging. It would be confusing to pass in a snake\_cased parameter and get an error message with a camelCased parameter. - Data that is returned from JSON-RPC methods. For example: The keys in a transaction receipt will still be returned as camelCase. Python 3.10 and 3.11 Support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support for Python 3.10 and 3.11 is here. In order to support Python 3.10, we had to update the \`\`websockets\`\` dependency to v10+. Exceptions ~~~~~~~~~~ Exceptions inherit from a base class \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` In v5, some web3.py exceptions inherited from \`\`AttributeError\`\`, namely: - \`\`NoABIFunctionsFound\`\` - \`\`NoABIFound\`\` - \`\`NoABIEventsFound\`\` Others inherited from \`\`ValueError\`\`, namely: - \`\`InvalidAddress\`\` - \`\`NameNotFound\`\` - \`\`LogTopicError\`\` - \`\`InvalidEventABI\`\` Now web3.py exceptions inherit from the same base \`\`Web3Exception\`\`. As such, any code that was expecting a \`\`ValueError\`\` or an \`\`AttributeError\`\` from web3.py must update to expecting one of the exceptions listed above, or \`\`Web3Exception\`\`. Similarly, exceptions raised in the EthPM and ENS modules inherit from the base \`\`EthPMException\`\` and \`\`ENSException\`\`, respectively. ValidationError \`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The Python dev tooling ecosystem is moving towards standardizing \`\`ValidationError\`\`, so users know that they're catching the correct \`\`ValidationError\`\`. The base \`\`ValidationError\`\` is imported from \`\`eth\_utils\`\`. However, we also wanted to empower users to catch all errors emitted by a particular module. So we now have a \`\`Web3ValidationError\`\`, \`\`EthPMValidationError\`\`, and an \`\`ENSValidationError\`\` that all inherit from the generic \`\`eth\_utils.exceptions.ValidationError\`\`. Web3 class split into Web3 and AsyncWeb3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The \`Web3\` class previously contained both sync and async methods. We've separated \`Web3\` and \`AsyncWeb3\` functionality to tighten up typing. For example: .. code-block:: python from web3 import Web3, AsyncWeb3 w3 = Web3(Web3.HTTPProvider()) async\_w3 = AsyncWeb3(AsyncWeb3.AsyncHTTPProvider()) \`dict\` to \`AttributeDict\` conversion moved to middleware ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \`Eth\` module data returned as key-value pairs was previously automatically converted to an \`AttributeDict\` by result formatters, which could cause problems with typing. This conversion has been moved to a default \`attrdict\_middleware\` where it can be easily removed if necessary. See the \`Eth module \`\_ docs for more detail. Other Misc Changes ~~~~~~~~~~~~~~~~~~ - \`\`InfuraKeyNotFound\`\` exception has been changed to \`\`InfuraProjectIdNotFound\`\` - \`\`SolidityError\`\` has been removed in favor of \`\`ContractLogicError\`\` - When a method is unavailable from a node provider (i.e. a response error code of -32601 is returned), a \`\`MethodUnavailable\`\` error is now raised instead of \`\`ValueError\`\` - Logs' \`data\` field was previously formatted with \`to\_ascii\_if\_bytes\`, now formatted to \`HexBytes\` - Receipts' \`type\` field was previously not formatted, now formatted with \`to\_integer\_if\_hex\` Removals ~~~~~~~~ - Removed unused IBAN module - Removed \`\`WEB3\_INFURA\_API\_KEY\`\` environment variable in favor of \`\`WEB3\_INFURA\_PROJECT\_ID\`\` - Removed Kovan auto provider - Removed deprecated \`\`sha3\`\` and \`\`soliditySha3\`\` methods in favor of \`\`keccak\`\` and \`\`solidityKeccak\`\` - Remove Parity Module and References Other notable changes ~~~~~~~~~~~~~~~~~~~~~ - The \`\`ipfshttpclient\`\` library is now opt-in via a web3 install extra. This only affects the ethpm ipfs backends, which rely on the library. .. \_migrating\_v4\_to\_v5: Migrating from v4 to v5 ----------------------- Web3.py follows \`Semantic Versioning \`\_, which means that version 5 introduced backwards-incompatible changes. If your project depends on Web3.py v4, then you'll probably need to make some changes. Here are the most common required updates: Python 3.5 no longer supported ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You will need to upgrade to either Python 3.6 or 3.7 \`\`eth-abi\`\` v1 no longer supported ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You will need to upgrade the \`\`eth-abi\`\` dependency to v2 Changes to base API ~~~~~~~~~~~~~~~~~~~ JSON-RPC Updates \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` In v4, JSON-RPC calls that looked up transactions or blocks and didn't find them, returned \`\`None\`\`. Now if a transaction or block is not found, a \`\`BlockNotFound\`\` or a \`\`TransactionNotFound\`\` error will be thrown as appropriate. This applies to the following web3 methods: - :meth:\`~web3.eth.Eth.getTransaction\` will throw a \`\`TransactionNotFound\`\` error - :meth:\`~web3.eth.Eth.getTransactionReceipt\` will throw a \`\`TransactionNotFound\`\` error - :meth:\`~web3.eth.Eth.getTransactionByBlock\` will throw a \`\`TransactionNotFound\`\` error - :meth:\`~web3.eth.Eth.getTransactionCount\` will throw a \`\`BlockNotFound\`\` error - :meth:\`~web3.eth.Eth.getBlock\` will throw a \`\`BlockNotFound\`\` error - :meth:\`~web3.eth.Eth.getUncleCount\` will throw a \`\`BlockNotFound\`\` error - :meth:\`~web3.eth.Eth.getUncleByBlock\` will throw a \`\`BlockNotFound\`\` error Removed Methods \`\`\`\`\`\`\`\`\`\`\`\`\`\`\` - \`\`contract.buildTransaction\`\` was removed for \`\`contract.functions.buildTransaction.\`\` - \`\`contract.deploy\`\` was removed for \`\`contract.constructor.transact\`\` - \`\`contract.estimateGas\`\` was removed for \`\`contract.functions..estimateGas\`\` - \`\`contract.call\`\` was removed for \`\`contract...call\`\` - \`\`contract.transact\`\` was removed for \`\`contract...transact\`\` - \`\`contract.eventFilter\`\` was removed for \`\`contract.events..createFilter\`\` - \`\`middleware\_stack\`\` was renamed to :meth:\`~Web3.middleware\_onion\` - \`\`web3.miner.hashrate\`\` was a duplicate of :meth:\`~web3.eth.Eth.hashrate\` and was removed. - \`\`web3.version.network\`\` was a duplicate of :meth:\`~web3.net.Net.version\` and was removed. - \`\`web3.providers.tester.EthereumTesterProvider\`\` and \`\`web3.providers.tester.TestRPCProvider\`\` have been removed for :meth:\`~web3.providers.eth\_tester.EthereumTesterProvider\` - \`\`web3.eth.enableUnauditedFeatures\`\` was removed - \`\`web3.txpool\`\` was moved to :meth:\`~web3.geth.txpool\` - \`\`web3.version.node\`\` was removed for \`\`web3.clientVersion\`\` - \`\`web3.version.ethereum\`\` was removed for :meth:\`~web3.eth.Eth.protocolVersion\` - Relocated personal RPC endpoints to reflect Parity and Geth implementations: - \`\`web3.personal.listAccounts\`\` was removed for :meth:\`~web3.geth.personal.listAccounts\` or :meth:\`~web3.parity.personal.listAccounts\` - \`\`web3.personal.importRawKey\`\` was removed for :meth:\`~web3.geth.personal.importRawKey\` or :meth:\`~web3.parity.personal.importRawKey\` - \`\`web3.personal.newAccount\`\` was removed for :meth:\`~web3.geth.personal.newAccount\` or :meth:\`~web3.parity.personal.newAccount\` - \`\`web3.personal.lockAccount\`\` was removed for :meth:\`~web3.geth.personal.lockAccount\` - \`\`web3.personal.unlockAccount\`\` was removed for :meth:\`~web3.geth.personal.unlockAccount\` or :meth:\`~web3.parity.personal.unlockAccount\` - \`\`web3.personal.sendTransaction\`\` was removed for :meth:\`~web3.geth.personal.sendTransaction\` or :meth:\`~web3.parity.personal.sendTransaction\` - Relocated \`\`web3.admin\`\` module to \`\`web3.geth\`\` namespace - Relocated \`\`web3.miner\`\` module to \`\`web3.geth\`\` namespace Deprecated Methods \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Expect the following methods to be removed in v6: - \`\`web3.sha3\`\` was deprecated for :meth:\`~Web3.keccak\` - \`\`web3.soliditySha3\`\` was deprecated for :meth:\`~Web3.solidityKeccak\` - :meth:\`~web3.net.Net.chainId\` was deprecated for :meth:\`~web3.eth.Eth.chainId\`. Follow issue \`#1293 \`\_ for details - \`\`web3.eth.getCompilers()\`\` was deprecated and will not be replaced - :meth:\`~web3.eth.getTransactionFromBlock()\` was deprecated for :meth:\`~Web3.getTransactionByBlock\` Deprecated ConciseContract and ImplicitContract \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` The ConciseContract and ImplicitContract have been deprecated and will be removed in v6. ImplicitContract instances will need to use the verbose syntax. For example: \`\`contract.functions..transact({})\`\` ConciseContract has been replaced with the ContractCaller API. Instead of using the ConciseContract factory, you can now use: \`\`contract.caller.\`\` or the classic contract syntax: \`\`contract.functions..call()\`\`. Some more concrete examples can be found in the \`ContractCaller docs \`\_ Manager Provider ~~~~~~~~~~~~~~~~ In v5, only a single provider will be allowed. While allowing multiple providers is a feature we'd like to support in the future, the way that multiple providers was handled in v4 wasn't ideal. The only thing they could do was fall back. There was no mechanism for any round robin, nor was there any control around which provider was chosen. Eventually, the idea is to expand the Manager API to support injecting custom logic into the provider selection process. For now, \`\`manager.providers\`\` has changed to \`\`manager.provider\`\`. Similarly, instances of \`\`web3.providers\`\` have been changed to \`\`web3.provider\`\`. Testnet Changes ~~~~~~~~~~~~~~~ Web3.py will no longer automatically look up a testnet connection in IPCProvider. ENS ~~~ Web3.py has stopped inferring the \`\`.eth\`\` TLD on domain names. If a domain name is used instead of an address, you'll need to specify the TLD. An \`\`InvalidTLD\`\` error will be thrown if the TLD is missing. Required Infura API Key ~~~~~~~~~~~~~~~~~~~~~~~ In order to interact with Infura after March 27, 2019, you'll need to set an environment variable called \`\`WEB3\_INFURA\_PROJECT\_ID\`\`. You can get a project id by visiting https://infura.io/register. Migrating from v3 to v4 ----------------------- Web3.py follows \`Semantic Versioning \`\_, which means that version 4 introduced backwards-incompatible changes. If your project depends on Web3.py v3, then you'll probably need to make some changes. Here are the most common required updates: Python 2 to Python 3 ~~~~~~~~~~~~~~~~~~~~ Only Python 3 is supported in v4. If you are running in Python 2, it's time to upgrade. We recommend using \`2to3\` which can make most of your code compatible with Python 3, automatically. The most important update, relevant to Web3.py, is the new :class:\`bytes\` type. It is used regularly, throughout the library, whenever dealing with data that is not guaranteed to be text. Many different methods in Web3.py accept text or binary data, like contract methods, transaction details, and cryptographic functions. The following example uses :meth:\`~Web3.sha3\`, but the same pattern applies elsewhere. In v3 & Python 2, you might have calculated the hash of binary data this way: .. code-block:: python >>> Web3.sha3('I\\xe2\\x99\\xa5SF') '0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e' Or, you might have calculated the hash of text data this way: .. code-block:: python >>> Web3.sha3(text=u'I♥SF') '0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e' After switching to Python 3, these would instead be executed as: .. code-block:: python >>> Web3.sha3(b'I\\xe2\\x99\\xa5SF') HexBytes('0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e') >>> Web3.sha3(text='I♥SF') HexBytes('0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e') Note that the return value is different too: you can treat :class:\`hexbytes.main.HexBytes\` like any other bytes value, but the representation on the console shows you the hex encoding of those bytes, for easier visual comparison. It takes a little getting used to, but the new py3 types are much better. We promise. Filters ~~~~~~~ Filters usually don't work quite the way that people want them to. The first step toward fixing them was to simplify them by removing the polling logic. Now, you must request an update on your filters explicitly. That means that any exceptions during the request will bubble up into your code. In v3, those exceptions (like "filter is not found") were swallowed silently in the automated polling logic. Here was the invocation for printing out new block hashes as they appear: .. code-block:: python >>> def new\_block\_callback(block\_hash): ... print(f"New Block: {block\_hash}") ... >>> new\_block\_filter = web3.eth.filter('latest') >>> new\_block\_filter.watch(new\_block\_callback) In v4, that same logic: .. code-block:: python >>> new\_block\_filter = web3.eth.filter('latest') >>> for block\_hash in new\_block\_filter.get\_new\_entries(): ... print(f"New Block: {block\_hash}") The caller is responsible for polling the results from \`\`get\_new\_entries()\`\`. See :ref:\`asynchronous\_filters\` for examples of filter-event handling with web3 v4. TestRPCProvider and EthereumTesterProvider ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ These providers are fairly uncommon. If you don't recognize the names, you can probably skip the section. However, if you were using web3.py for testing contracts, you might have been using TestRPCProvider or EthereumTesterProvider. In v4 there is a new :class:\`EthereumTesterProvider\`, and the old v3 implementation has been removed. Web3.py v4 uses :class:\`eth\_tester.main.EthereumTester\` under the hood, instead of eth-testrpc. While \`\`eth-tester\`\` is still in beta, many parts are already in better shape than testrpc, so we decided to replace it in v4. If you were using TestRPC, or were explicitly importing EthereumTesterProvider, like: \`\`from web3.providers.tester import EthereumTesterProvider\`\`, then you will need to update. With v4 you should import with \`\`from web3 import EthereumTesterProvider\`\`. As before, you'll need to install Web3.py with the \`\`tester\`\` extra to get these features, like: .. code-block:: bash $ pip install web3\[tester\] Changes to base API convenience methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Web3.toDecimal() \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` In v4 \`\`Web3.toDecimal()\`\` is renamed: :meth:\`~Web3.toInt\` for improved clarity. It does not return a :class:\`decimal.Decimal\`, it returns an :class:\`int\`. Removed Methods \`\`\`\`\`\`\`\`\`\`\`\`\`\`\` - \`\`Web3.toUtf8\`\` was removed for :meth:\`~Web3.toText\`. - \`\`Web3.fromUtf8\`\` was removed for :meth:\`~Web3.toHex\`. - \`\`Web3.toAscii\`\` was removed for :meth:\`~Web3.toBytes\`. - \`\`Web3.fromAscii\`\` was removed for :meth:\`~Web3.toHex\`. - \`\`Web3.fromDecimal\`\` was removed for :meth:\`~Web3.toHex\`. Provider Access ~~~~~~~~~~~~~~~~~ In v4, \`\`w3.currentProvider\`\` was removed, in favor of \`\`w3.providers\`\`. Disambiguating String Inputs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are a number of places where an arbitrary string input might be either a byte-string that has been hex-encoded, or unicode characters in text. These are named \`\`hexstr\`\` and \`\`text\`\` in Web3.py. You specify which kind of :class:\`str\` you have by using the appropriate keyword argument. See examples in :ref:\`overview\_type\_conversions\`. In v3, some methods accepted a :class:\`str\` as the first positional argument. In v4, you must pass strings as one of \`\`hexstr\`\` or \`\`text\`\` keyword arguments. Notable methods that no longer accept ambiguous strings: - :meth:\`~Web3.sha3\` - :meth:\`~Web3.toBytes\` Contracts ~~~~~~~~~ - When a contract returns the ABI type \`\`string\`\`, Web3.py v4 now returns a :class:\`str\` value by decoding the underlying bytes using UTF-8. - When a contract returns the ABI type \`\`bytes\`\` (of any length), Web3.py v4 now returns a :class:\`bytes\` value Personal API ~~~~~~~~~~~~ \`\`w3.personal.signAndSendTransaction\`\` is no longer available. Use :meth:\`w3.personal.sendTransaction() \` instead. --- # ENS API — web3.py 7.6.1 documentation * [](index.html) * ENS API * [View page source](_sources/ens.rst.txt) * * * ENS API[](#ens-api "Link to this heading") ============================================ [Ethereum Name Service (ENS)](ens_overview.html) has a friendly overview. Continue below for the detailed specs on each method and class in the ens module. ens.ens module[](#module-ens.ens "Link to this heading") ---------------------------------------------------------- _class_ ens.ens.ENS(_provider: BaseProvider \= None_, _addr: ChecksumAddress \= None_, _middleware: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.13)")\ \[Middleware, [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\ \]\] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_)[](#ens.ens.ENS "Link to this definition") Quick access to common Ethereum Name Service functions, like getting the address for a name. Unless otherwise specified, all addresses are assumed to be a str in [checksum format](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md) , # blocklint: pragma # noqa: E501 like: `"0x314159265dD8dbb310642f98f50C066173C1259b"` _classmethod_ from\_web3(_w3: [Web3](web3.main.html#web3.Web3 "web3.Web3") _, _addr: ChecksumAddress \= None_) → [ENS](#ens.ens.ENS "ens.ens.ENS") [](#ens.ens.ENS.from_web3 "Link to this definition") Generate an ENS instance from a Web3 instance Parameters: * **w3** ([_web3.Web3_](web3.main.html#web3.Web3 "web3.Web3") ) – to infer connection, middleware, and codec information * **addr** (_hex-string_) – the address of the ENS registry on-chain. If not provided, defaults to the mainnet ENS registry address. address(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _coin\_type: [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_) → ChecksumAddress | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.ens.ENS.address "Link to this definition") Look up the Ethereum address that name currently points to. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – an ENS name to look up * **coin\_type** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") ) – if provided, look up the address for this coin type Raises: * [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if name has invalid syntax * [**ResolverNotFound**](#ens.exceptions.ResolverNotFound "ens.exceptions.ResolverNotFound") – if no resolver found for name * [**UnsupportedFunction**](#ens.exceptions.UnsupportedFunction "ens.exceptions.UnsupportedFunction") – if the resolver does not support the `addr()` function setup\_address(_name: str_, _address: Address | ChecksumAddress | HexAddress \= _, _coin\_type: int | None \= None_, _transact: TxParams | None \= None_) → [HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.ens.ENS.setup_address "Link to this definition") Set up the name to point to the supplied address. The sender of the transaction must own the name, or its parent name. Example: If the caller owns `parentname.eth` with no subdomains and calls this method with `sub.parentname.eth`, then `sub` will be created as part of this call. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to set up * **address** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – name will point to this address, in checksum format. If `None`, erase the record. If not specified, name will point to the owner’s address. * **coin\_type** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") ) – if provided, set up the address for this coin type * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – the transaction configuration, like in [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") Raises: * [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if `name` has invalid syntax * [**UnauthorizedError**](#ens.exceptions.UnauthorizedError "ens.exceptions.UnauthorizedError") – if `'from'` in transact does not own name name(_address: ChecksumAddress_) → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.ens.ENS.name "Link to this definition") Look up the name that the address points to, using a reverse lookup. Reverse lookup is opt-in for name owners. Parameters: **address** (_hex-string_) setup\_name(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _address: ChecksumAddress | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_, _transact: TxParams | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_) → [HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)") [](#ens.ens.ENS.setup_name "Link to this definition") Set up the address for reverse lookup, aka “caller ID”. After successful setup, the method `name()` will return name when supplied with address. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name that address will point to * **address** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – address to set up, in checksum format * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – the transaction configuration, like in `send_transaction()` Raises: * [**AddressMismatch**](#ens.exceptions.AddressMismatch "ens.exceptions.AddressMismatch") – if the name does not already point to the address * [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if name has invalid syntax * [**UnauthorizedError**](#ens.exceptions.UnauthorizedError "ens.exceptions.UnauthorizedError") – if `'from'` in transact does not own name * [**UnownedName**](#ens.exceptions.UnownedName "ens.exceptions.UnownedName") – if no one owns name owner(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _) → ChecksumAddress[](#ens.ens.ENS.owner "Link to this definition") Get the owner of a name. Note that this may be different from the deed holder in the ‘.eth’ registrar. Learn more about the difference between deed and name ownership in the ENS [Managing Ownership docs](http://docs.ens.domains/en/latest/userguide.html#managing-ownership) Parameters: **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to look up Returns: owner address Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") setup\_owner(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _new\_owner: ChecksumAddress \= None_, _transact: TxParams | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_) → ChecksumAddress | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.ens.ENS.setup_owner "Link to this definition") Set the owner of the supplied name to new\_owner. For typical scenarios, you’ll never need to call this method directly, simply call [`setup_name()`](#ens.ens.ENS.setup_name "ens.ens.ENS.setup_name") or [`setup_address()`](#ens.ens.ENS.setup_address "ens.ens.ENS.setup_address") . This method does _not_ set up the name to point to an address. If new\_owner is not supplied, then this will assume you want the same owner as the parent domain. If the caller owns `parentname.eth` with no subdomains and calls this method with `sub.parentname.eth`, then `sub` will be created as part of this call. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to set up * **new\_owner** – account that will own name. If `None`, set owner to empty addr. If not specified, name will point to the parent domain owner’s address. * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – the transaction configuration, like in [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") Raises: * [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if name has invalid syntax * [**UnauthorizedError**](#ens.exceptions.UnauthorizedError "ens.exceptions.UnauthorizedError") – if `'from'` in transact does not own name Returns: the new owner’s address resolver(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _) → [Contract](web3.contract.html#web3.contract.Contract "web3.contract.Contract") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.ens.ENS.resolver "Link to this definition") Get the resolver for an ENS name. Parameters: **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – The ENS name get\_text(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _key: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _) → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") [](#ens.ens.ENS.get_text "Link to this definition") Get the value of a text record by key from an ENS name. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to look up * **key** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name’s text record key Returns: ENS name’s text record value Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") Raises: * [**UnsupportedFunction**](#ens.exceptions.UnsupportedFunction "ens.exceptions.UnsupportedFunction") – If the resolver does not support the “0x59d1d43c” interface id * [**ResolverNotFound**](#ens.exceptions.ResolverNotFound "ens.exceptions.ResolverNotFound") – If no resolver is found for the provided name set\_text(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _key: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _value: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _transact: TxParams \= None_) → [HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)") [](#ens.ens.ENS.set_text "Link to this definition") Set the value of a text record of an ENS name. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name * **key** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – Name of the attribute to set * **value** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – Value to set the attribute to * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – The transaction configuration, like in [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") Returns: Transaction hash Return type: HexBytes Raises: * [**UnsupportedFunction**](#ens.exceptions.UnsupportedFunction "ens.exceptions.UnsupportedFunction") – If the resolver does not support the “0x59d1d43c” interface id * [**ResolverNotFound**](#ens.exceptions.ResolverNotFound "ens.exceptions.ResolverNotFound") – If no resolver is found for the provided name ens.async\_ens module[](#module-ens.async_ens "Link to this heading") ----------------------------------------------------------------------- _class_ ens.async\_ens.AsyncENS(_provider: AsyncBaseProvider \= None_, _addr: ChecksumAddress \= None_, _middleware: [Sequence](https://docs.python.org/3/library/typing.html#typing.Sequence "(in Python v3.13)") \[[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.13)")\ \[Middleware, [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)")\ \]\] | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_)[](#ens.async_ens.AsyncENS "Link to this definition") Quick access to common Ethereum Name Service functions, like getting the address for a name. Unless otherwise specified, all addresses are assumed to be a str in [checksum format](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md) , # blocklint: pragma # noqa: E501 like: `"0x314159265dD8dbb310642f98f50C066173C1259b"` _classmethod_ from\_web3(_w3: AsyncWeb3_, _addr: ChecksumAddress \= None_) → [AsyncENS](#ens.async_ens.AsyncENS "ens.async_ens.AsyncENS") [](#ens.async_ens.AsyncENS.from_web3 "Link to this definition") Generate an AsyncENS instance with web3 Parameters: * **w3** ([_web3.Web3_](web3.main.html#web3.Web3 "web3.Web3") ) – to infer connection information * **addr** (_hex-string_) – the address of the ENS registry on-chain. If not provided, defaults to the mainnet ENS registry address. _async_ address(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _coin\_type: [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_) → ChecksumAddress | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.async_ens.AsyncENS.address "Link to this definition") Look up the Ethereum address that name currently points to. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – an ENS name to look up * **coin\_type** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") ) – if provided, look up the address for this coin type Raises: [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if name has invalid syntax _async_ setup\_address(_name: str_, _address: Address | ChecksumAddress | HexAddress \= _, _coin\_type: int | None \= None_, _transact: TxParams | None \= None_) → [HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.async_ens.AsyncENS.setup_address "Link to this definition") Set up the name to point to the supplied address. The sender of the transaction must own the name, or its parent name. Example: If the caller owns `parentname.eth` with no subdomains and calls this method with `sub.parentname.eth`, then `sub` will be created as part of this call. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to set up * **address** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – name will point to this address, in checksum format. If `None`, erase the record. If not specified, name will point to the owner’s address. * **coin\_type** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") ) – if provided, set up the address for this coin type * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – the transaction configuration, like in [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") Raises: * [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if `name` has invalid syntax * [**UnauthorizedError**](#ens.exceptions.UnauthorizedError "ens.exceptions.UnauthorizedError") – if `'from'` in transact does not own name _async_ name(_address: ChecksumAddress_) → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.async_ens.AsyncENS.name "Link to this definition") Look up the name that the address points to, using a reverse lookup. Reverse lookup is opt-in for name owners. Parameters: **address** (_hex-string_) _async_ setup\_name(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _address: ChecksumAddress | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_, _transact: TxParams | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_) → [HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)") [](#ens.async_ens.AsyncENS.setup_name "Link to this definition") Set up the address for reverse lookup, aka “caller ID”. After successful setup, the method `name()` will return name when supplied with address. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name that address will point to * **address** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – address to set up, in checksum format * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – the transaction configuration, like in `send_transaction()` Raises: * [**AddressMismatch**](#ens.exceptions.AddressMismatch "ens.exceptions.AddressMismatch") – if the name does not already point to the address * [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if name has invalid syntax * [**UnauthorizedError**](#ens.exceptions.UnauthorizedError "ens.exceptions.UnauthorizedError") – if `'from'` in transact does not own name * [**UnownedName**](#ens.exceptions.UnownedName "ens.exceptions.UnownedName") – if no one owns name _async_ owner(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _) → ChecksumAddress[](#ens.async_ens.AsyncENS.owner "Link to this definition") Get the owner of a name. Note that this may be different from the deed holder in the ‘.eth’ registrar. Learn more about the difference between deed and name ownership in the ENS [Managing Ownership docs](http://docs.ens.domains/en/latest/userguide.html#managing-ownership) Parameters: **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to look up Returns: owner address Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _async_ setup\_owner(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _new\_owner: ChecksumAddress \= None_, _transact: TxParams | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") \= None_) → ChecksumAddress | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.async_ens.AsyncENS.setup_owner "Link to this definition") Set the owner of the supplied name to new\_owner. For typical scenarios, you’ll never need to call this method directly, simply call [`setup_name()`](#ens.async_ens.AsyncENS.setup_name "ens.async_ens.AsyncENS.setup_name") or [`setup_address()`](#ens.async_ens.AsyncENS.setup_address "ens.async_ens.AsyncENS.setup_address") . This method does _not_ set up the name to point to an address. If new\_owner is not supplied, then this will assume you want the same owner as the parent domain. If the caller owns `parentname.eth` with no subdomains and calls this method with `sub.parentname.eth`, then `sub` will be created as part of this call. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to set up * **new\_owner** – account that will own name. If `None`, set owner to empty addr. If not specified, name will point to the parent domain owner’s address. * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – the transaction configuration, like in [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") Raises: * [**InvalidName**](#ens.exceptions.InvalidName "ens.exceptions.InvalidName") – if name has invalid syntax * [**UnauthorizedError**](#ens.exceptions.UnauthorizedError "ens.exceptions.UnauthorizedError") – if `'from'` in transact does not own name Returns: the new owner’s address _async_ resolver(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _) → AsyncContract | [None](https://docs.python.org/3/library/constants.html#None "(in Python v3.13)") [](#ens.async_ens.AsyncENS.resolver "Link to this definition") Get the resolver for an ENS name. Parameters: **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – The ENS name _async_ get\_text(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _key: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _) → [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") [](#ens.async_ens.AsyncENS.get_text "Link to this definition") Get the value of a text record by key from an ENS name. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name to look up * **key** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name’s text record key Returns: ENS name’s text record value Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") Raises: * [**UnsupportedFunction**](#ens.exceptions.UnsupportedFunction "ens.exceptions.UnsupportedFunction") – If the resolver does not support the “0x59d1d43c” interface id * [**ResolverNotFound**](#ens.exceptions.ResolverNotFound "ens.exceptions.ResolverNotFound") – If no resolver is found for the provided name _async_ set\_text(_name: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _key: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _value: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") _, _transact: TxParams \= None_) → [HexBytes](https://hexbytes.readthedocs.io/en/latest/hexbytes.html#hexbytes.main.HexBytes "(in HexBytes v1.2)") [](#ens.async_ens.AsyncENS.set_text "Link to this definition") Set the value of a text record of an ENS name. Parameters: * **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – ENS name * **key** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – The name of the attribute to set * **value** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.13)") ) – Value to set the attribute to * **transact** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.13)") ) – The transaction configuration, like in [`send_transaction()`](web3.eth.html#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") Returns: Transaction hash Return type: HexBytes Raises: * [**UnsupportedFunction**](#ens.exceptions.UnsupportedFunction "ens.exceptions.UnsupportedFunction") – If the resolver does not support the “0x59d1d43c” interface id * [**ResolverNotFound**](#ens.exceptions.ResolverNotFound "ens.exceptions.ResolverNotFound") – If no resolver is found for the provided name ens.exceptions module[](#module-ens.exceptions "Link to this heading") ------------------------------------------------------------------------ _exception_ ens.exceptions.ENSException[](#ens.exceptions.ENSException "Link to this definition") Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.13)") Base class for all ENS Errors _exception_ ens.exceptions.ENSValueError[](#ens.exceptions.ENSValueError "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") , [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.13)") An ENS exception wrapper for ValueError, for better control over exception handling. _exception_ ens.exceptions.ENSTypeError[](#ens.exceptions.ENSTypeError "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") , [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.13)") An ENS exception wrapper for TypeError, for better control over exception handling. _exception_ ens.exceptions.AddressMismatch[](#ens.exceptions.AddressMismatch "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") In order to set up reverse resolution correctly, the ENS name should first point to the address. This exception is raised if the name does not currently point to the address. _exception_ ens.exceptions.InvalidName[](#ens.exceptions.InvalidName "Link to this definition") Bases: `IDNAError`, [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if the provided name does not meet the normalization standards specified in [ENSIP-15](https://docs.ens.domains/ens-improvement-proposals/ensip-15-normalization-standard) . _exception_ ens.exceptions.UnauthorizedError[](#ens.exceptions.UnauthorizedError "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if the sending account is not the owner of the name you are trying to modify. Make sure to set `from` in the `transact` keyword argument to the owner of the name. _exception_ ens.exceptions.UnownedName[](#ens.exceptions.UnownedName "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if you are trying to modify a name that no one owns. If working on a subdomain, make sure the subdomain gets created first with `setup_address()`. _exception_ ens.exceptions.ResolverNotFound[](#ens.exceptions.ResolverNotFound "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if no resolver was found for the name you are trying to resolve. _exception_ ens.exceptions.UnsupportedFunction[](#ens.exceptions.UnsupportedFunction "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if a resolver does not support a particular method. _exception_ ens.exceptions.BidTooLow[](#ens.exceptions.BidTooLow "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if you bid less than the minimum amount _exception_ ens.exceptions.InvalidBidHash[](#ens.exceptions.InvalidBidHash "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if you supply incorrect data to generate the bid hash. _exception_ ens.exceptions.InvalidLabel[](#ens.exceptions.InvalidLabel "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if you supply an invalid label _exception_ ens.exceptions.OversizeTransaction[](#ens.exceptions.OversizeTransaction "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if a transaction you are trying to create would cost so much gas that it could not fit in a block. For example: when you try to start too many auctions at once. _exception_ ens.exceptions.UnderfundedBid[](#ens.exceptions.UnderfundedBid "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if you send less wei with your bid than you declared as your intent to bid. _exception_ ens.exceptions.ENSValidationError[](#ens.exceptions.ENSValidationError "Link to this definition") Bases: [`ENSException`](#ens.exceptions.ENSException "ens.exceptions.ENSException") Raised if there is a validation error --- # web3.eth API — web3.py 7.6.1 documentation * [](index.html) * web3.eth API * [View page source](_sources/web3.eth.rst.txt) * * * web3.eth API[](#module-web3.eth "Link to this heading") ========================================================= _class_ web3.eth.Eth[](#web3.eth.Eth "Link to this definition") The `web3.eth` object exposes the following properties and methods to interact with the RPC APIs under the `eth_` namespace. By default, when a property or method returns a mapping of keys to values, it will return an `AttributeDict` which acts like a `dict` but you can access the keys as attributes and cannot modify its fields. For example, you can find the latest block number in these two ways: > \>>> block \= web3.eth.get\_block('latest') > AttributeDict({ > 'hash': '0xe8ad537a261e6fff80d551d8d087ee0f2202da9b09b64d172a5f45e818eb472a', > 'number': 4022281, > # ... etc ... > }) > > \>>> block\['number'\] > 4022281 > \>>> block.number > 4022281 > > \>>> block.number \= 4022282 > Traceback # ... etc ... > TypeError: This data is immutable -- create a copy instead of modifying This feature is available via the `AttributeDictMiddleware` which is a default middleware. Note Accessing an `AttributeDict` property via attribute will break type hinting. If typing is crucial for your application, accessing via key / value, as well as removing the `AttributeDictMiddleware` altogether, may be desired. Properties[](#properties "Link to this heading") -------------------------------------------------- The following properties are available on the `web3.eth` namespace. Eth.default\_account[](#web3.eth.Eth.default_account "Link to this definition") The ethereum address that will be used as the default `from` address for all transactions. Defaults to empty. Eth.default\_block[](#web3.eth.Eth.default_block "Link to this definition") The default block number that will be used for any RPC methods that accept a block identifier. Defaults to `'latest'`. Eth.syncing[](#web3.eth.Eth.syncing "Link to this definition") * Delegates to `eth_syncing` RPC Method Returns either `False` if the node is not syncing or a dictionary showing sync status. \>>> web3.eth.syncing AttributeDict({ 'currentBlock': 2177557, 'highestBlock': 2211611, 'knownStates': 0, 'pulledStates': 0, 'startingBlock': 2177365, }) Eth.max\_priority\_fee[](#web3.eth.Eth.max_priority_fee "Link to this definition") * Delegates to `eth_maxPriorityFeePerGas` RPC Method Returns a suggestion for a max priority fee for dynamic fee transactions in Wei. \>>> web3.eth.max\_priority\_fee 2000000000 Eth.gas\_price[](#web3.eth.Eth.gas_price "Link to this definition") * Delegates to `eth_gasPrice` RPC Method Returns the current gas price in Wei. \>>> web3.eth.gas\_price 20000000000 Eth.accounts[](#web3.eth.Eth.accounts "Link to this definition") * Delegates to `eth_accounts` RPC Method Returns the list of known accounts. \>>> web3.eth.accounts \['0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD'\] Eth.block\_number[](#web3.eth.Eth.block_number "Link to this definition") * Delegates to `eth_blockNumber` RPC Method Returns the number of the most recent block Alias for [`get_block_number()`](#web3.eth.Eth.get_block_number "web3.eth.Eth.get_block_number") \>>> web3.eth.block\_number 2206939 Eth.chain\_id[](#web3.eth.Eth.chain_id "Link to this definition") > * Delegates to `eth_chainId` RPC Method > > > Returns an integer value for the currently configured “Chain Id” value introduced in [EIP-155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md) > . Returns `None` if no Chain Id is available. > > \>>> web3.eth.chain\_id > 61 Note This property gets called frequently in validation middleware, but eth\_chainId is an allowed method for caching by default. Simply turn on request caching to avoid repeated calls to this method. > \>>> w3.provider.cache\_allowed\_requests \= True Methods[](#methods "Link to this heading") -------------------------------------------- The following methods are available on the `web3.eth` namespace. Eth.get\_balance(_account_, _block\_identifier\=eth.default\_block_)[](#web3.eth.Eth.get_balance "Link to this definition") * Delegates to `eth_getBalance` RPC Method Returns the balance of the given `account` at the block specified by `block_identifier`. `account` may be a checksum address or an ENS name \>>> web3.eth.get\_balance('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') 77320681768999138915 Eth.get\_block\_number()[](#web3.eth.Eth.get_block_number "Link to this definition") * Delegates to `eth_blockNumber` RPC Method Returns the number of the most recent block. \>>> web3.eth.get\_block\_number() 2206939 Eth.get\_storage\_at(_account_, _position_, _block\_identifier\=eth.default\_block_)[](#web3.eth.Eth.get_storage_at "Link to this definition") * Delegates to `eth_getStorageAt` RPC Method Returns the value from a storage position for the given `account` at the block specified by `block_identifier`. `account` may be a checksum address or an ENS name \>>> web3.eth.get\_storage\_at('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B', 0) '0x00000000000000000000000000000000000000000000000000120a0b063499d4' Eth.blob\_base\_fee()[](#web3.eth.Eth.blob_base_fee "Link to this definition") Fetches the expected base fee for blobs in the next block. * Delegates to `eth_blobBaseFee` RPC Method Returns the expected base fee in Wei. \>>> web3.eth.blob\_base\_fee() 537070730 Eth.get\_proof(_account_, _positions_, _block\_identifier\=eth.default\_block_)[](#web3.eth.Eth.get_proof "Link to this definition") * Delegates to `eth_getProof` RPC Method Returns the values from an array of storage positions for the given `account` at the block specified by `block_identifier`. `account` may be a checksum address or an ENS name \>>> web3.eth.get\_proof('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B', \[0\], 3391) AttributeDict({ 'address': '0x4CB06C43fcdABeA22541fcF1F856A6a296448B6c', 'accountProof': \['0xf90211a03841a7ddd65c70c94b8efa79190d00f0ab134b26f18dcad508f60a7e74559d0ba0464b07429a05039e22931492d6c6251a860c018ea390045d596b1ac11b5c7aa7a011f4b89823a03c9c4b5a8ab079ee1bc0e2a83a508bb7a5dc7d7fb4f2e95d3186a0b5f7c51c3b2d51d97f171d2b38a4df1a7c0acc5eb0de46beeff4d07f5ed20e19a0b591a2ce02367eda31cf2d16eca7c27fd44dbf0864b64ea8259ad36696eb2a04a02b646a7552b8392ae94263757f699a27d6e9176b4c06b9fc0a722f893b964795a02df05d68bceb88eebf68aafde61d10ab942097afc1c58b8435ffd3895358a742a0c2f16143c4d1db03276c433696dddb3e9f3b113bcd854b127962262e98f43147a0828820316cc02bfefd899aba41340659fd06df1e0a0796287ec2a4110239f6d2a050496598670b04df7bbff3718887fa36437d6d8c7afb4eff86f76c5c7097dcc4a0c14e9060c6b3784e35b9e6ae2ad2984142a75910ccc89eb89dc1e2f44b6c58c2a009804db571d0ce07913e1cbacc4f1dc4fb8265c936f5c612e3a47e91c64d8e9fa063d96f38b3cb51b1665c6641e25ffe24803f2941e5df79942f6a53b7169647e4a0899f71abb18c6c956118bf567fac629b75f7e9526873e429d3d8abb6dbb58021a00fd717235298742623c0b3cafb3e4bd86c0b5ab1f71097b4dd19f3d6925d758da0096437146c16097f2ccc1d3e910d65a4132803baee2249e72c8bf0bcaaeb37e580',\ '0xf90151a097b17a89fd2c03ee98cb6459c08f51b269da5cee46650e84470f62bf83b43efe80a03b269d284a4c3cf8f8deacafb637c6d77f607eec8d75e8548d778e629612310480a01403217a7f1416830c870087c524dabade3985271f6f369a12b010883c71927aa0f592ac54c879817389663be677166f5022943e2fe1b52617a1d15c2f353f27dda0ac8d015a9e668f5877fcc391fae33981c00577096f0455b42df4f8e8089ece24a003ba34a13e2f2fb4bf7096540b42d4955c5269875b9cf0f7b87632585d44c9a580a0b179e3230b07db294473ae57f0170262798f8c551c755b5665ace1215cee10ca80a0552d24252639a6ae775aa1df700ffb92c2411daea7286f158d44081c8172d072a0772a87d08cf38c4c68bfde770968571abd16fd3835cb902486bd2e515d53c12d80a0413774f3d900d2d2be7a3ad999ffa859a471dc03a74fb9a6d8275455f5496a548080',\ '0xf869a020d13b52a61d3c1325ce3626a51418adebd6323d4840f1bdd93906359d11c933b846f8440180a01ab7c0b0a2a4bbb5a1495da8c142150891fc64e0c321e1feb70bd5f881951f7ea0551332d96d085185ab4019ad8bcf89c45321e136c261eb6271e574a2edf1461f'\ \], 'balance': 0, 'codeHash': '0x551332d96d085185ab4019ad8bcf89c45321e136c261eb6271e574a2edf1461f', 'nonce': 1, 'storageHash': '0x1ab7c0b0a2a4bbb5a1495da8c142150891fc64e0c321e1feb70bd5f881951f7e', 'storageProof': \[\ AttributeDict({\ 'key': '0x00',\ 'value': '0x48656c6c6f00000000000000000000000000000000000000000000000000000a',\ 'proof': \['0xf9019180a01ace80e7bed79fbadbe390876bd1a7d9770edf9462049ef8f4b555d05715d53ea049347a3c2eac6525a3fd7e3454dab19d73b4adeb9aa27d29493b9843f3f88814a085079b4abcd07fd4a5d6c52d35f4c4574aecc85830e90c478ca8c18fcbe590de80a02e3f8ad7ea29e784007f51852b9c3e470aef06b11bac32586a8b691134e4c27da064d2157a14bc31f195f73296ea4dcdbe7698edbf3ca81c44bf7730179d98d94ca09e7dc2597c9b7f72ddf84d7eebb0fe2a2fa2ab54fe668cd14fee44d9b40b1a53a0aa5d4acc7ac636d16bc9655556770bc325e1901fb62dc53770ef9110009e080380a0d5fde962bd2fb5326ddc7a9ca7fe0ee47c5bb3227f838b6d73d3299c22457596a08691410eff46b88f929ef649ea25025f62a5362ca8dc8876e5e1f4fc8e79256d80a0673e88d3a8a4616f676793096b5ae87cff931bd20fb8dd466f97809a1126aad8a08b774a45c2273553e2daf4bbc3a8d44fb542ea29b6f125098f79a4d211b3309ca02fed3139c1791269acb9365eddece93e743900eba6b42a6a8614747752ba268f80',\ '0xf891808080a0c7d094301e0c54da37b696d85f72de5520b224ab2cf4f045d8db1a3374caf0488080a0fc5581783bfe27fab9423602e1914d719fd71433e9d7dd63c95fe7e58d10c9c38080a0c64f346fc7a21f6679cba8abdf37ca2de8c4fcd8f8bcaedb261b5f77627c93908080808080a0ddef2936a67a3ac7d3d4ff15a935a45f2cc4976c8f0310aed85daf763780e2b480',\ '0xf843a0200decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563a1a048656c6c6f00000000000000000000000000000000000000000000000000000a'\ \]\ })\ \] }) * Merkle proof verification using py-trie. The following example verifies that the values returned in the `AttributeDict` are included in the state of given trie `root`. from eth\_utils import ( keccak, ) import rlp from rlp.sedes import ( Binary, big\_endian\_int, ) from trie import ( HexaryTrie, ) from web3.\_utils.encoding import ( pad\_bytes, ) def format\_proof\_nodes(proof): trie\_proof \= \[\] for rlp\_node in proof: trie\_proof.append(rlp.decode(bytes(rlp\_node))) return trie\_proof def verify\_eth\_get\_proof(proof, root): trie\_root \= Binary.fixed\_length(32, allow\_empty\=True) hash32 \= Binary.fixed\_length(32) class \_Account(rlp.Serializable): fields \= \[\ ('nonce', big\_endian\_int),\ ('balance', big\_endian\_int),\ ('storage', trie\_root),\ ('code\_hash', hash32)\ \] acc \= \_Account( proof.nonce, proof.balance, proof.storageHash, proof.codeHash ) rlp\_account \= rlp.encode(acc) trie\_key \= keccak(bytes.fromhex(proof.address\[2:\])) assert rlp\_account \== HexaryTrie.get\_from\_proof( root, trie\_key, format\_proof\_nodes(proof.accountProof) ), f"Failed to verify account proof {proof.address}" for storage\_proof in proof.storageProof: trie\_key \= keccak(pad\_bytes(b'\\x00', 32, storage\_proof.key)) root \= proof.storageHash if storage\_proof.value \== b'\\x00': rlp\_value \= b'' else: rlp\_value \= rlp.encode(storage\_proof.value) assert rlp\_value \== HexaryTrie.get\_from\_proof( root, trie\_key, format\_proof\_nodes(storage\_proof.proof) ), f"Failed to verify storage proof {storage\_proof.key}" return True block \= w3.eth.get\_block(3391) proof \= w3.eth.get\_proof('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B', \[0, 1\], 3391) assert verify\_eth\_get\_proof(proof, block.stateRoot) Eth.get\_code(_account_, _block\_identifier\=eth.default\_block_)[](#web3.eth.Eth.get_code "Link to this definition") * Delegates to `eth_getCode` RPC Method Returns the bytecode for the given `account` at the block specified by `block_identifier`. `account` may be a checksum address or an ENS name \# For a contract address. \>>> web3.eth.get\_code('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B') '0x6060604052361561027c5760e060020a60003504630199.....' \# For a private key address. \>>> web3.eth.get\_code('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') '0x' Eth.get\_block(_block\_identifier\=eth.default\_block_, _full\_transactions\=False_)[](#web3.eth.Eth.get_block "Link to this definition") * Delegates to `eth_getBlockByNumber` or `eth_getBlockByHash` RPC Methods Returns the block specified by `block_identifier`. Delegates to `eth_getBlockByNumber` if `block_identifier` is an integer or one of the predefined block parameters `'latest', 'earliest', 'pending', 'safe', 'finalized'` - otherwise delegates to `eth_getBlockByHash`. Throws `BlockNotFound` error if the block is not found. If `full_transactions` is `True` then the `'transactions'` key will contain full transactions objects. Otherwise it will be an array of transaction hashes. \>>> web3.eth.get\_block(2000000) AttributeDict({ 'difficulty': 49824742724615, 'extraData': '0xe4b883e5bda9e7a59ee4bb99e9b1bc', 'gasLimit': 4712388, 'gasUsed': 21000, 'hash': '0xc0f4906fea23cf6f3cce98cb44e8e1449e455b28d684dfa9ff65426495584de6', 'logsBloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', 'miner': '0x61c808d82a3ac53231750dadc13c777b59310bd9', 'nonce': '0x3b05c6d5524209f1', 'number': 2000000, 'parentHash': '0x57ebf07eb9ed1137d41447020a25e51d30a0c272b5896571499c82c33ecb7288', 'receiptsRoot': '0x84aea4a7aad5c5899bd5cfc7f309cc379009d30179316a2a7baa4a2ea4a438ac', 'sha3Uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 'size': 650, 'stateRoot': '0x96dbad955b166f5119793815c36f11ffa909859bbfeb64b735cca37cbf10bef1', 'timestamp': 1470173578, 'totalDifficulty': 44010101827705409388, 'transactions': \['0xc55e2b90168af6972193c1f86fa4d7d7b31a29c156665d15b9cd48618b5177ef'\], 'transactionsRoot': '0xb31f174d27b99cdae8e746bd138a01ce60d8dd7b224f7c60845914def05ecc58', 'uncles': \[\], }) Eth.get\_block\_transaction\_count(_block\_identifier_)[](#web3.eth.Eth.get_block_transaction_count "Link to this definition") * Delegates to `eth_getBlockTransactionCountByNumber` or `eth_getBlockTransactionCountByHash` RPC Methods Returns the number of transactions in the block specified by `block_identifier`. Delegates to `eth_getBlockTransactionCountByNumber` if `block_identifier` is an integer or one of the predefined block parameters `'latest', 'earliest', 'pending', 'safe', 'finalized'`, otherwise delegates to `eth_getBlockTransactionCountByHash`. Throws `BlockNotFoundError` if transactions are not found. \>>> web3.eth.get\_block\_transaction\_count(46147) 1 \>>> web3.eth.get\_block\_transaction\_count('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd') \# block 46147 1 Eth.get\_uncle\_by\_block(_block\_identifier_, _uncle\_index_)[](#web3.eth.Eth.get_uncle_by_block "Link to this definition") * Delegates to `eth_getUncleByBlockHashAndIndex` or `eth_getUncleByBlockNumberAndIndex` RPC methods Returns the uncle at the index specified by `uncle_index` from the block specified by `block_identifier`. Delegates to `eth_getUncleByBlockNumberAndIndex` if `block_identifier` is an integer or one of the predefined block parameters `'latest', 'earliest', 'pending'`, otherwise delegates to `eth_getUncleByBlockHashAndIndex`. Throws `BlockNotFound` if the block is not found. \>>> web3.eth.get\_uncle\_by\_block(56160, 0) AttributeDict({ 'author': '0xbe4532e1b1db5c913cf553be76180c1777055403', 'difficulty': '0x17dd9ca0afe', 'extraData': '0x476574682f686261722f76312e302e312f6c696e75782f676f312e342e32', 'gasLimit': '0x2fefd8', 'gasUsed': '0x0', 'hash': '0xc78c35720d930f9ef34b4e6fb9d02ffec936f9b02a8f0fa858456e4afd4d5614', 'logsBloom':'0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', 'miner': '0xbe4532e1b1db5c913cf553be76180c1777055403', 'mixHash': '0x041e14603f35a82f6023802fec96ef760433292434a39787514f140950597e5e', 'nonce': '0x5d2b7e3f1af09995', 'number': '0xdb5e', 'parentHash': '0xcc30e8a9b15c548d5bf113c834143a8f0e1909fbfea96b2a208dc154293a78cf', 'receiptsRoot': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', 'sealFields': \['0xa0041e14603f35a82f6023802fec96ef760433292434a39787514f140950597e5e', '0x885d2b7e3f1af09995'\], 'sha3Uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 'size': None, 'stateRoot': '0x8ce2b1bf8e25a06a8ca34c647ff5fd0fa48ac725cc07f657ae1645ab8ef68c91', 'timestamp': '0x55c6a972', 'totalDifficulty': '0xce4c4f0a0b810b', 'transactions': \[\], 'transactionsRoot': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', 'uncles': \[\] }) \# You can also refer to the block by hash: \>>> web3.eth.get\_uncle\_by\_block('0x685b2226cbf6e1f890211010aa192bf16f0a0cba9534264a033b023d7367b845', 0) AttributeDict({ ... }) Eth.get\_uncle\_count(_block\_identifier_)[](#web3.eth.Eth.get_uncle_count "Link to this definition") * Delegates to `eth_getUncleCountByBlockHash` or `eth_getUncleCountByBlockNumber` RPC methods Returns the (integer) number of uncles associated with the block specified by `block_identifier`. Delegates to `eth_getUncleCountByBlockNumber` if `block_identifier` is an integer or one of the predefined block parameters `'latest', 'earliest', 'pending'`, otherwise delegates to `eth_getUncleCountByBlockHash`. Throws `BlockNotFound` if the block is not found. \>>> web3.eth.get\_uncle\_count(56160) 1 \# You can also refer to the block by hash: \>>> web3.eth.get\_uncle\_count('0x685b2226cbf6e1f890211010aa192bf16f0a0cba9534264a033b023d7367b845') 1 Eth.get\_transaction(_transaction\_hash_)[](#web3.eth.Eth.get_transaction "Link to this definition") * Delegates to `eth_getTransactionByHash` RPC Method Returns the transaction specified by `transaction_hash`. If the transaction cannot be found throws `web3.exceptions.TransactionNotFound`. \>>> web3.eth.get\_transaction('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') AttributeDict({'blockHash': HexBytes('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd'), 'blockNumber': 46147, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gas': 21000, 'gasPrice': 50000000000000, 'hash': HexBytes('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060'), 'input': HexBytes('0x'), 'nonce': 0, 'r': HexBytes('0x88ff6cf0fefd94db46111149ae4bfc179e9b94721fffd821d38d16464b3f71d0'), 's': HexBytes('0x45e0aff800961cfce805daef7016b9b675c137a6a41a548f7b60a3484c06a33a'), 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionIndex': 0, 'type': 0, 'v': 28, 'value': 31337 }) Eth.get\_raw\_transaction(_transaction\_hash_)[](#web3.eth.Eth.get_raw_transaction "Link to this definition") * Delegates to `eth_getRawTransactionByHash` RPC Method Returns the raw form of transaction specified by `transaction_hash`. If no transaction is found, `TransactionNotFound` is raised. \>>> web3.eth.get\_raw\_transaction('0x86fbfe56cce542ff0a2a2716c31675a0c9c43701725c4a751d20ee2ddf8a733d') HexBytes('0xf86907843b9aca0082520894dc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd018086eecac466e115a0f9db4e25484b28f486b247a372708d4cd0643fc63e604133afac577f4cc1eab8a044841d84e799d4dc18ba146816a937e8a0be8bc296bd8bb8aea126de5e627e06') Eth.get\_transaction\_by\_block(_block\_identifier_, _transaction\_index_)[](#web3.eth.Eth.get_transaction_by_block "Link to this definition") * Delegates to `eth_getTransactionByBlockNumberAndIndex` or `eth_getTransactionByBlockHashAndIndex` RPC Methods Returns the transaction at the index specified by `transaction_index` from the block specified by `block_identifier`. Delegates to `eth_getTransactionByBlockNumberAndIndex` if `block_identifier` is an integer or one of the predefined block parameters `'latest', 'earliest', 'pending', 'safe', 'finalized'`, otherwise delegates to `eth_getTransactionByBlockHashAndIndex`. If a transaction is not found at specified arguments, throws `web3.exceptions.TransactionNotFound`. \>>> web3.eth.get\_transaction\_by\_block(46147, 0) AttributeDict({ 'blockHash': '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 'blockNumber': 46147, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gas': 21000, 'gasPrice': None, 'hash': '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060', 'input': '0x', 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'nonce': 0, 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionIndex': 0, 'value': 31337, }) \>>> web3.eth.get\_transaction\_by\_block('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 0) AttributeDict({ 'blockHash': '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 'blockNumber': 46147, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gas': 21000, 'gasPrice': None, 'hash': '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060', 'input': '0x', 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'nonce': 0, 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionIndex': 0, 'value': 31337, }) Eth.get\_raw\_transaction\_by\_block(_block\_identifier_, _transaction\_index_)[](#web3.eth.Eth.get_raw_transaction_by_block "Link to this definition") * Delegates to `eth_getRawTransactionByBlockNumberAndIndex` or `eth_getRawTransactionByBlockHashAndIndex` RPC Methods Returns the raw transaction at the index specified by `transaction_index` from the block specified by `block_identifier`. Delegates to `eth_getRawTransactionByBlockNumberAndIndex` if `block_identifier` is an integer or one of the predefined block parameters `'latest', 'earliest', 'pending', 'safe', 'finalized'`, otherwise delegates to `eth_getRawTransactionByBlockHashAndIndex`. If a transaction is not found at specified arguments, throws `web3.exceptions.TransactionNotFound`. \>>> web3.eth.get\_raw\_transaction\_by\_block('latest', 0) HexBytes('0x02f87582053901843b9aca00843b9aca008301d8a894e2dfcfa89a45abdc3de91f7a2844b276b8451d2e888ac7230489e8000080c001a028dcd2e11682288c00237f377280bc6a478a6b27e9c2d745262152add1b1dfcba04e7a33b7ce2a37fc3cd3af7bdc7d7beff721664d56508defa188df35afd77c2c') \>>> web3.eth.get\_raw\_transaction\_by\_block(2, 0) HexBytes('0x02f87582053901843b9aca00843b9aca008301d8a894e2dfcfa89a45abdc3de91f7a2844b276b8451d2e888ac7230489e8000080c001a028dcd2e11682288c00237f377280bc6a478a6b27e9c2d745262152add1b1dfcba04e7a33b7ce2a37fc3cd3af7bdc7d7beff721664d56508defa188df35afd77c2c') \>>> web3.eth.get\_raw\_transaction\_by\_block('0xca609fb606a04ce6aaec76415cd0b9d8c2bc83ad2a4d17db7fd403ee7d97bf40', 0) HexBytes('0x02f87582053901843b9aca00843b9aca008301d8a894e2dfcfa89a45abdc3de91f7a2844b276b8451d2e888ac7230489e8000080c001a028dcd2e11682288c00237f377280bc6a478a6b27e9c2d745262152add1b1dfcba04e7a33b7ce2a37fc3cd3af7bdc7d7beff721664d56508defa188df35afd77c2c') Eth.wait\_for\_transaction\_receipt(_transaction\_hash_, _timeout\=120_, _poll\_latency\=0.1_)[](#web3.eth.Eth.wait_for_transaction_receipt "Link to this definition") Waits for the transaction specified by `transaction_hash` to be included in a block, then returns its transaction receipt. Optionally, specify a `timeout` in seconds. If timeout elapses before the transaction is added to a block, then [`wait_for_transaction_receipt()`](#web3.eth.Eth.wait_for_transaction_receipt "web3.eth.Eth.wait_for_transaction_receipt") raises a `web3.exceptions.TimeExhausted` exception. \>>> web3.eth.wait\_for\_transaction\_receipt('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') \# If transaction is not yet in a block, time passes, while the thread sleeps... \# ... \# Then when the transaction is added to a block, its receipt is returned: AttributeDict({ 'blockHash': HexBytes('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd'), 'blockNumber': 46147, 'contractAddress': None, 'cumulativeGasUsed': 21000, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gasUsed': 21000, 'logs': \[\], 'logsBloom': HexBytes('0x000000000000000000000000000000000000000000000000...0000'), 'status': 1, 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionHash': HexBytes('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060'), 'transactionIndex': 0, }) Eth.get\_transaction\_receipt(_transaction\_hash_)[](#web3.eth.Eth.get_transaction_receipt "Link to this definition") * Delegates to `eth_getTransactionReceipt` RPC Method Returns the transaction receipt specified by `transaction_hash`. If the transaction cannot be found throws `web3.exceptions.TransactionNotFound`. If `status` in response equals 1 the transaction was successful. If it is equals 0 the transaction was reverted by EVM. \>>> web3.eth.get\_transaction\_receipt('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') \# not yet mined Traceback # ... etc ... TransactionNotFound: Transaction with hash: 0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060 not found. \# wait for it to be mined.... \>>> web3.eth.get\_transaction\_receipt('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') AttributeDict({ 'blockHash': '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 'blockNumber': 46147, 'contractAddress': None, 'cumulativeGasUsed': 21000, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gasUsed': 21000, 'logs': \[\], 'logsBloom': '0x000000000000000000000000000000000000000000000000...0000', 'status': 1, # 0 or 1 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionHash': '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060', 'transactionIndex': 0, }) Eth.get\_transaction\_count(_account_, _block\_identifier\=web3.eth.default\_block_)[](#web3.eth.Eth.get_transaction_count "Link to this definition") * Delegates to `eth_getTransactionCount` RPC Method Returns the number of transactions that have been sent from `account` as of the block specified by `block_identifier`. `account` may be a checksum address or an ENS name \>>> web3.eth.get\_transaction\_count('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') 340 Eth.send\_transaction(_transaction_)[](#web3.eth.Eth.send_transaction "Link to this definition") * Delegates to `eth_sendTransaction` RPC Method Signs and sends the given `transaction` The `transaction` parameter should be a dictionary with the following fields. * `from`: `bytes or text`, checksum address or ENS name - (optional, default: `web3.eth.defaultAccount`) The address the transaction is sent from. * `to`: `bytes or text`, checksum address or ENS name - (optional when creating new contract) The address the transaction is directed to. * `gas`: `integer` - (optional) Integer of the gas provided for the transaction execution. It will return unused gas. * `maxFeePerGas`: `integer or hex` - (optional) maximum amount you’re willing to pay, inclusive of `baseFeePerGas` and `maxPriorityFeePerGas`. The difference between `maxFeePerGas` and `baseFeePerGas + maxPriorityFeePerGas` is refunded to the user. * `maxPriorityFeePerGas`: `integer or hex` - (optional) the part of the fee that goes to the miner * `gasPrice`: `integer` - Integer of the gasPrice used for each paid gas **LEGACY** - unless you have a good reason to use `gasPrice`, use `maxFeePerGas` and `maxPriorityFeePerGas` instead. * `value`: `integer` - (optional) Integer of the value send with this transaction * `data`: `bytes or text` - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see [Ethereum Contract ABI](https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI) . * `nonce`: `integer` - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. If the `transaction` specifies a `data` value but does not specify `gas` then the `gas` value will be populated using the [`estimate_gas()`](#web3.eth.Eth.estimate_gas "web3.eth.Eth.estimate_gas") function with an additional buffer of `100000` gas up to the `gasLimit` of the latest block. In the event that the value returned by [`estimate_gas()`](#web3.eth.Eth.estimate_gas "web3.eth.Eth.estimate_gas") method is greater than the `gasLimit` a `ValueError` will be raised. \# simple example (web3.py and / or client determines gas and fees, typically defaults to a dynamic fee transaction post London fork) \>>> web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 12345 }) \# Dynamic fee transaction, introduced by EIP-1559: HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') \>>> web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 12345, 'gas': 21000, 'maxFeePerGas': web3.to\_wei(250, 'gwei'), 'maxPriorityFeePerGas': web3.to\_wei(2, 'gwei'), }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') \# Legacy transaction (less efficient) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') \>>> web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 12345, 'gas': 21000, 'gasPrice': web3.to\_wei(50, 'gwei'), }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') Eth.sign\_transaction(_transaction_)[](#web3.eth.Eth.sign_transaction "Link to this definition") * Delegates to `eth_signTransaction` RPC Method. Returns a transaction that’s been signed by the node’s private key, but not yet submitted. The signed tx can be submitted with `Eth.send_raw_transaction` \>>> signed\_txn \= w3.eth.sign\_transaction(dict( nonce=w3.eth.get\_transaction\_count(w3.eth.accounts\[0\]), maxFeePerGas=2000000000, maxPriorityFeePerGas=1000000000, gas=100000, to='0xd3CdA913deB6f67967B99D67aCDFa1712C293601', value=1, data=b'', ) ) b"\\xf8d\\x80\\x85\\x040\\xe24\\x00\\x82R\\x08\\x94\\xdcTM\\x1a\\xa8\\x8f\\xf8\\xbb\\xd2\\xf2\\xae\\xc7T\\xb1\\xf1\\xe9\\x9e\\x18\\x12\\xfd\\x01\\x80\\x1b\\xa0\\x11\\r\\x8f\\xee\\x1d\\xe5=\\xf0\\x87\\x0en\\xb5\\x99\\xed;\\xf6\\x8f\\xb3\\xf1\\xe6,\\x82\\xdf\\xe5\\x97lF|\\x97%;\\x15\\xa04P\\xb7=\*\\xef \\t\\xf0&\\xbc\\xbf\\tz%z\\xe7\\xa3~\\xb5\\xd3\\xb7=\\xc0v\\n\\xef\\xad+\\x98\\xe3'" # noqa: E501 Eth.send\_raw\_transaction(_raw\_transaction_)[](#web3.eth.Eth.send_raw_transaction "Link to this definition") * Delegates to `eth_sendRawTransaction` RPC Method Sends a signed and serialized transaction. Returns the transaction hash as a HexBytes object. \>>> signed\_txn \= w3.eth.account.sign\_transaction(dict( nonce=w3.eth.get\_transaction\_count(public\_address\_of\_senders\_account), maxFeePerGas=3000000000, maxPriorityFeePerGas=2000000000, gas=100000, to='0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', value=12345, data=b'', type=2, # (optional) the type is now implicitly set based on appropriate transaction params chainId=1, ), private\_key\_for\_senders\_account, ) \>>> w3.eth.send\_raw\_transaction(signed\_txn.raw\_transaction) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') Eth.replace\_transaction(_transaction\_hash_, _new\_transaction_)[](#web3.eth.Eth.replace_transaction "Link to this definition") * Delegates to `eth_sendTransaction` RPC Method Sends a transaction that replaces the transaction with `transaction_hash`. The `transaction_hash` must be the hash of a pending transaction. The `new_transaction` parameter should be a dictionary with transaction fields as required by [`send_transaction()`](#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") . It will be used to entirely replace the transaction of `transaction_hash` without using any of the pending transaction’s values. If the `new_transaction` specifies a `nonce` value, it must match the pending transaction’s nonce. If the `new_transaction` specifies `maxFeePerGas` and `maxPriorityFeePerGas` values, they must be greater than the pending transaction’s values for each field, respectively. * Legacy Transaction Support (Less Efficient - Not Recommended) If the pending transaction specified a `gasPrice` value (legacy transaction), the `gasPrice` value for the `new_transaction` must be greater than the pending transaction’s `gasPrice`. If the `new_transaction` does not specify any of `gasPrice`, `maxFeePerGas`, or `maxPriorityFeePerGas` values, one of the following will happen: * If the pending transaction has a `gasPrice` value, this value will be used with a multiplier of 1.125 - This is typically the minimum `gasPrice` increase a node requires before it accepts a replacement transaction. * If a gas price strategy is set, the `gasPrice` value from the gas price strategy(See [Gas Price API](gas_price.html#gas-price) ) will be used. * If none of the above, the client will ultimately decide appropriate values for `maxFeePerGas` and `maxPriorityFeePerGas`. These will likely be default values and may result in an unsuccessful replacement of the pending transaction. This method returns the transaction hash of the replacement transaction as a HexBytes object. \>>> tx \= web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 1000 }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') \>>> web3.eth.replace\_transaction('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331', { 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 2000 }) HexBytes('0x4177e670ec6431606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1528989') Eth.modify\_transaction(_transaction\_hash_, _\*\*transaction\_params_)[](#web3.eth.Eth.modify_transaction "Link to this definition") * Delegates to `eth_sendTransaction` RPC Method Sends a transaction that modifies the transaction with `transaction_hash`. `transaction_params` are keyword arguments that correspond to valid transaction parameters as required by [`send_transaction()`](#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") . The parameter values will override the pending transaction’s values to create the replacement transaction to send. The same validation and defaulting rules of [`replace_transaction()`](#web3.eth.Eth.replace_transaction "web3.eth.Eth.replace_transaction") apply. This method returns the transaction hash of the newly modified transaction as a HexBytes object. \>>> tx \= web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 1000 }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') \>>> web3.eth.modify\_transaction('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331', value\=2000) HexBytes('0xec6434e6701771606e55d6b4ca35a1a6b75ee3d73315145a921026d15299d05') Eth.sign(_account_, _data\=None_, _hexstr\=None_, _text\=None_)[](#web3.eth.Eth.sign "Link to this definition") * Delegates to `eth_sign` RPC Method Caller must specify exactly one of: `data`, `hexstr`, or `text`. Signs the given data with the private key of the given `account`. The account must be unlocked. `account` may be a checksum address or an ENS name \>>> web3.eth.sign( '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', text='some-text-tö-sign') '0x1a8bbe6eab8c72a219385681efefe565afd3accee35f516f8edf5ae82208fbd45a58f9f9116d8d88ba40fcd29076d6eada7027a3b412a9db55a0164547810cc401' \>>> web3.eth.sign( '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', data=b'some-text-t\\xc3\\xb6-sign') '0x1a8bbe6eab8c72a219385681efefe565afd3accee35f516f8edf5ae82208fbd45a58f9f9116d8d88ba40fcd29076d6eada7027a3b412a9db55a0164547810cc401' \>>> web3.eth.sign( '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', hexstr='0x736f6d652d746578742d74c3b62d7369676e') '0x1a8bbe6eab8c72a219385681efefe565afd3accee35f516f8edf5ae82208fbd45a58f9f9116d8d88ba40fcd29076d6eada7027a3b412a9db55a0164547810cc401' Eth.sign\_typed\_data(_account_, _jsonMessage_)[](#web3.eth.Eth.sign_typed_data "Link to this definition") * Delegates to `eth_signTypedData` RPC Method Note `eth_signTypedData` is not currently supported by any major client (Besu, Erigon, Geth, or Nethermind) Please note that the `jsonMessage` argument is the loaded JSON Object and **NOT** the JSON String itself. Signs the `Structured Data` (or `Typed Data`) with the private key of the given `account`. The account must be unlocked. `account` may be a checksum address or an ENS name Eth.call(_transaction_, _block\_identifier\=web3.eth.default\_block_, _state\_override\=None_, _ccip\_read\_enabled\=True_)[](#web3.eth.Eth.call "Link to this definition") * Delegates to `eth_call` RPC Method Executes the given transaction locally without creating a new transaction on the blockchain. Returns the return value of the executed contract. The `transaction` parameter is handled in the same manner as the [`send_transaction()`](#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") method. \>>> myContract.functions.setVar(1).transact() HexBytes('0x79af0c7688afba7588c32a61565fd488c422da7b5773f95b242ea66d3d20afda') \>>> myContract.functions.getVar().call() 1 \# The above call equivalent to the raw call: \>>> web3.eth.call({'value': 0, 'gas': 21736, 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'to': '0xc305c901078781C232A2a521C2aF7980f8385ee9', 'data': '0x477a5c98'}) HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001') In most cases it is better to make contract function call through the [`web3.contract.Contract`](web3.contract.html#web3.contract.Contract "web3.contract.Contract") interface. Overriding state is a debugging feature available in Geth clients. View their [usage documentation](https://geth.ethereum.org/docs/rpc/ns-eth#3-object---state-override-set) for a list of possible parameters. [EIP-3668](https://eips.ethereum.org/EIPS/eip-3668) introduced support for the `OffchainLookup` revert / CCIP Read support. In order to properly handle a call to a contract function that reverts with an `OffchainLookup` error for offchain data retrieval, the `ccip_read_enabled` flag has been added to the `eth_call` method. `ccip_read_enabled` is optional, yielding the default value for CCIP Read on calls to a global `global_ccip_read_enabled` flag on the provider which is set to `True` by default. This means CCIP Read is enabled by default for calls, as is recommended in EIP-3668. Therefore, calls to contract functions that revert with an `OffchainLookup` will be handled appropriately by default. The `ccip_read_enabled` flag on the call will always override the value of the global flag on the provider for explicit control over specific calls. If the flag on the call is set to `False`, the call will raise the `OffchainLookup` instead of properly handling the exception according to EIP-3668. This may be useful for “preflighting” a transaction with a call (see [CCIP Read support for offchain lookup](web3.contract.html#ccip-read-example) within the examples section). If the function called results in a `revert` error, a `ContractLogicError` will be raised. If there is an error message with the error, web3.py attempts to parse the message that comes back and return it to the user as the error string. As of v6.3.0, the raw data is also returned and can be accessed via the `data` attribute on `ContractLogicError`. Eth.create\_access\_list(_transaction_, _block\_identifier\=web3.eth.default\_block_)[](#web3.eth.Eth.create_access_list "Link to this definition") * Delegates to `eth_createAccessList` RPC Method This method creates an [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) type `accessList` based on a given `transaction`. The `accessList` contains all storage slots and addresses read and written by the transaction, except for the sender account and the precompiles. This method uses the same `transaction` call object and `block_identifier` object as [`call()`](#web3.eth.Eth.call "web3.eth.Eth.call") . An `accessList` can be used to access contracts that became inaccessible due to gas cost increases. The `transaction` parameter is handled in the same manner as the [`send_transaction()`](#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") method. The optional `block_identifier` parameter is a block\_number or `latest` or `pending`. Default is `latest`. \>>> w3.eth.create\_access\_list( ... { ... "to": to\_checksum\_address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"), ... "gasPrice": 10\*\*11, ... "value": 0, ... "data": "0x608060806080608155", ... }, ... "pending", ... ) AttributeDict({ "accessList": \[\ AttributeDict({\ "address": "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe",\ "storageKeys": \[\ "0x0000000000000000000000000000000000000000000000000000000000000003",\ "0x0000000000000000000000000000000000000000000000000000000000000007",\ \]\ }),\ AttributeDict({\ "address": "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413",\ "storageKeys": \[\]\ }),\ \], "gasUsed": 21000 }) The method `eth_createAccessList` returns a list of addresses and storage keys used by the transaction, plus the gas consumed when the `accessList` is included. Like `eth_estimateGas`, this is an estimation; the list could change when the transaction is actually finalized. Adding an `accessList` to your transaction does not necessarily result in lower gas usage compared to a transaction without an `accessList`. Eth.fee\_history(_block\_count_, _newest\_block_, _reward\_percentiles\=None_)[](#web3.eth.Eth.fee_history "Link to this definition") * Delegates to `eth_feeHistory` RPC Method Returns transaction fee data for up to 1,024 blocks. Parameters: * **block\_count** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") _or_ _hexstring_) – The number of blocks in the requested range. Depending on the client, this value should be either a [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") between 1 and 1024 or a hexstring. Less than requested may be returned if not all blocks are available. * **newest\_block** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") _or_ _BlockParams_) – The newest, highest-numbered, block in the requested range. This value may be an [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") or one of the predefined block parameters `'latest'`, `'earliest'`, or `'pending'`. * **reward\_percentiles** (_List__\[_[_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.13)")\ _\] or_ _None_) – _(optional)_ A monotonically increasing list of percentile [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.13)") values to sample from each block’s effective priority fees per gas in ascending order, weighted by gas used. Returns: An `AttributeDict` containing the following keys: * **oldestBlock** _(int)_ – The oldest, lowest-numbered, block in the range requested as a `BlockNumber` type with [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.13)") value. * **baseFeePerGas** _(List\[Wei\])_ – An array of block base fees per gas. This includes the next block after the newest of the returned range, because this value can be derived from the newest block. Zeroes are returned for pre-EIP-1559 blocks. * **gasUsedRatio** _(List\[float\])_ – An array of `gasUsed`/`gasLimit` float values for the requested blocks. * **reward** _(List\[List\[Wei\]\])_ – _(optional)_ A two-dimensional array of effective priority fees per gas at the requested block percentiles. \>>> w3.eth.fee\_history(4, 'latest', \[10, 90\]) AttributeDict({ 'oldestBlock': 3, 'reward': \[\[220, 7145389\], \[1000000, 6000213\], \[550, 550\], \[125, 12345678\]\], 'baseFeePerGas': \[202583058, 177634473, 155594425, 136217133, 119442408\], 'gasUsedRatio': \[0.007390479689642084, 0.0036988514889990873, 0.0018512333048507866, 0.00741217041320997\] }) Eth.estimate\_gas(_transaction_, _block\_identifier\=None_, _state\_override\=None_)[](#web3.eth.Eth.estimate_gas "Link to this definition") * Delegates to `eth_estimateGas` RPC Method Executes the given transaction locally without creating a new transaction on the blockchain. Returns amount of gas consumed by execution which can be used as a gas estimate. The `transaction` and `block_identifier` parameters are handled in the same manner as the [`send_transaction()`](#web3.eth.Eth.send_transaction "web3.eth.Eth.send_transaction") method. The `state_override` is useful when there is a chain of transaction calls. It overrides state so that the gas estimate of a transaction is accurate in cases where prior calls produce side effects. \>>> web3.eth.estimate\_gas({'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'from':web3.eth.accounts\[0\], 'value': 12345}) 21000 Eth.generate\_gas\_price(_transaction\_params\=None_)[](#web3.eth.Eth.generate_gas_price "Link to this definition") Uses the selected gas price strategy to calculate a gas price. This method returns the gas price denominated in wei. The `transaction_params` argument is optional however some gas price strategies may require it to be able to produce a gas price. \>>> web3.eth.generate\_gas\_price() 20000000000 Note For information about how gas price can be customized in web3 see [Gas Price API](gas_price.html#gas-price) . Eth.set\_gas\_price\_strategy(_gas\_price\_strategy_)[](#web3.eth.Eth.set_gas_price_strategy "Link to this definition") Set the selected gas price strategy. It must be a method of the signature `(web3, transaction_params)` and return a gas price denominated in wei. Eth.subscribe(_subscription\_identifier_, _subscription\_params_)[](#web3.eth.Eth.subscribe "Link to this definition") * Delegates to `eth_subscribe` RPC Method Only available on persistent connection providers: [`WebSocketProvider`](providers.html#web3.providers.persistent.WebSocketProvider "web3.providers.persistent.WebSocketProvider") and [`AsyncIPCProvider`](providers.html#web3.providers.persistent.AsyncIPCProvider "web3.providers.persistent.AsyncIPCProvider") . Returns a subscription ID that can be used to track a particular subscription to, or unsubscribe from, an event. For usage examples see the docs on [Using Persistent Connection Providers](providers.html#subscription-examples) . \>>> subscription\_id \= await web3.eth.subscribe('newHeaders') \>>> subscription\_id '0xbd63bb89e7475591a0a6fc9014307bc4' Eth.unsubscribe(_subscription\_id_)[](#web3.eth.Eth.unsubscribe "Link to this definition") * Delegates to `eth_unsubscribe` RPC Method Only available on persistent connection providers: [`WebSocketProvider`](providers.html#web3.providers.persistent.WebSocketProvider "web3.providers.persistent.WebSocketProvider") and [`AsyncIPCProvider`](providers.html#web3.providers.persistent.AsyncIPCProvider "web3.providers.persistent.AsyncIPCProvider") . Returns `True` if successfully unsubscribed. For usage examples see the docs on [Using Persistent Connection Providers](providers.html#subscription-examples) . \>>> result \= await web3.eth.unsubscribe(subscription\_id) \>>> result True Filters[](#filters "Link to this heading") -------------------------------------------- The following methods are available on the `web3.eth` object for interacting with the filtering API. Eth.filter(_filter\_params_)[](#web3.eth.Eth.filter "Link to this definition") * Delegates to `eth_newFilter`, `eth_newBlockFilter`, and `eth_newPendingTransactionFilter` RPC Methods. This method delegates to one of three RPC methods depending on the value of `filter_params`. * If `filter_params` is the string `'pending'` then a new filter is registered using the `eth_newPendingTransactionFilter` RPC method. This will create a new filter that will be called for each new unmined transaction that the node receives. * If `filter_params` is the string `'latest'` then a new filter is registered using the `eth_newBlockFilter` RPC method. This will create a new filter that will be called each time the node receives a new block. * If `filter_params` is a dictionary then a new filter is registered using the `eth_newFilter` RPC method. This will create a new filter that will be called for all log entries that match the provided `filter_params`. This method returns a `web3.utils.filters.Filter` object which can then be used to either directly fetch the results of the filter or to register callbacks which will be called with each result of the filter. When creating a new log filter, the `filter_params` should be a dictionary with the following keys. Note that the keys are camel-cased strings, as is expected in a JSON-RPC request. * `fromBlock`: `integer/tag` - (optional, default: “latest”) Integer block number, or one of predefined block identifiers “latest”, “pending”, “earliest”, “safe”, or “finalized”. * `toBlock`: `integer/tag` - (optional, default: “latest”) Integer block number, or one of predefined block identifiers “latest”, “pending”, “earliest”, “safe”, or “finalized”. * `address`: `string` or list of `strings`, each 20 Bytes - (optional) Contract address or a list of addresses from which logs should originate. * `topics`: list of 32 byte `strings` or `null` - (optional) Array of topics that should be used for filtering. Topics are order-dependent. This parameter can also be a list of topic lists in which case filtering will match any of the provided topic arrays. Note Though `"latest"` and `"safe"` block identifiers are not yet part of the specifications for `eth_newFilter`, they are supported by web3.py and may or may not yield expected results depending on the node being accessed. See [Events and Logs](filters.html) for more information about filtering. \>>> web3.eth.filter('latest') \>>> web3.eth.filter('pending') \>>> web3.eth.filter({'fromBlock': 1000000, 'toBlock': 1000100, 'address': '0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B'}) Eth.get\_filter\_changes(_self_, _filter\_id_)[](#web3.eth.Eth.get_filter_changes "Link to this definition") * Delegates to `eth_getFilterChanges` RPC Method. Returns all new entries which occurred since the last call to this method for the given `filter_id` \>>> filter \= web3.eth.filter() \>>> web3.eth.get\_filter\_changes(filter.filter\_id) \[\ {\ 'address': '0xDc3A9Db694BCdd55EBaE4A89B22aC6D12b3F0c24',\ 'blockHash': '0xb72256286ca528e09022ffd408856a73ef90e7216ac560187c6e43b4c4efd2f0',\ 'blockNumber': 2217196,\ 'data': '0x0000000000000000000000000000000000000000000000000000000000000001',\ 'logIndex': 0,\ 'topics': \['0xe65b00b698ba37c614af350761c735c5f4a82b4ab365a1f1022d49d9dfc8e930',\ '0x000000000000000000000000754c50465885f1ed1fa1a55b95ee8ecf3f1f4324',\ '0x296c7fb6ccafa3e689950b947c2895b07357c95b066d5cdccd58c301f41359a3'\],\ 'transactionHash': '0xfe1289fd3915794b99702202f65eea2e424b2f083a12749d29b4dd51f6dce40d',\ 'transactionIndex': 1,\ },\ ...\ \] Eth.get\_filter\_logs(_self_, _filter\_id_)[](#web3.eth.Eth.get_filter_logs "Link to this definition") * Delegates to `eth_getFilterLogs` RPC Method. Returns all entries for the given `filter_id` \>>> filter \= web3.eth.filter() \>>> web3.eth.get\_filter\_logs(filter.filter\_id) \[\ {\ 'address': '0xDc3A9Db694BCdd55EBaE4A89B22aC6D12b3F0c24',\ 'blockHash': '0xb72256286ca528e09022ffd408856a73ef90e7216ac560187c6e43b4c4efd2f0',\ 'blockNumber': 2217196,\ 'data': '0x0000000000000000000000000000000000000000000000000000000000000001',\ 'logIndex': 0,\ 'topics': \['0xe65b00b698ba37c614af350761c735c5f4a82b4ab365a1f1022d49d9dfc8e930',\ '0x000000000000000000000000754c50465885f1ed1fa1a55b95ee8ecf3f1f4324',\ '0x296c7fb6ccafa3e689950b947c2895b07357c95b066d5cdccd58c301f41359a3'\],\ 'transactionHash': '0xfe1289fd3915794b99702202f65eea2e424b2f083a12749d29b4dd51f6dce40d',\ 'transactionIndex': 1,\ },\ ...\ \] Eth.uninstall\_filter(_self_, _filter\_id_)[](#web3.eth.Eth.uninstall_filter "Link to this definition") * Delegates to `eth_uninstallFilter` RPC Method. Uninstalls the filter specified by the given `filter_id`. Returns boolean as to whether the filter was successfully uninstalled. \>>> filter \= web3.eth.filter() \>>> web3.eth.uninstall\_filter(filter.filter\_id) True \>>> web3.eth.uninstall\_filter(filter.filter\_id) False # already uninstalled. Eth.get\_logs(_filter\_params_)[](#web3.eth.Eth.get_logs "Link to this definition") This is the equivalent of: creating a new filter, running [`get_filter_logs()`](#web3.eth.Eth.get_filter_logs "web3.eth.Eth.get_filter_logs") , and then uninstalling the filter. See [`filter()`](#web3.eth.Eth.filter "web3.eth.Eth.filter") for details on allowed filter parameters. Contracts[](#contracts "Link to this heading") ------------------------------------------------ Eth.contract(_address\=None_, _contract\_name\=None_, _ContractFactoryClass\=Contract_, _\*\*contract\_factory\_kwargs_)[](#web3.eth.Eth.contract "Link to this definition") If `address` is provided, then this method will return an instance of the contract defined by `abi`. The address may be a checksum string, or an ENS name like `'mycontract.eth'`. from web3 import Web3 w3 \= Web3(...) contract \= w3.eth.contract(address\='0x000000000000000000000000000000000000dEaD', abi\=...) \# alternatively: contract \= w3.eth.contract(address\='mycontract.eth', abi\=...) Note If you use an ENS name to initialize a contract, the contract will be looked up by name on each use. If the name could ever change maliciously, first [Get the Address for an ENS Name](ens_overview.html#ens-get-address) , and then create the contract with the checksum address. If `address` is _not_ provided, the newly created contract class will be returned. That class will then be initialized by supplying the address. from web3 import Web3 w3 \= Web3(...) Contract \= w3.eth.contract(abi\=...) \# later, initialize contracts with the same metadata at different addresses: contract1 \= Contract(address\='0x000000000000000000000000000000000000dEaD') contract2 \= Contract(address\='mycontract.eth') `contract_name` will be used as the name of the contract class. If it is `None` then the name of the `ContractFactoryClass` will be used. `ContractFactoryClass` will be used as the base Contract class. The following arguments are accepted for contract class creation. Parameters: * **abi** (_ABI_) – Application Binary Interface. Usually provided since an `abi` is required to interact with any contract. * **asm** – Assembly code generated by the compiler * **ast** – Abstract Syntax Tree of the contract generated by the compiler * **bytecode** – Bytecode of the contract generated by the compiler * **bytecode\_runtime** – Bytecode stored at the contract address, excludes the constructor and initialization code * **clone\_bin** * **dev\_doc** * **decode\_tuples** – Optionally convert tuples/structs to named tuples * **interface** * **metadata** – Contract Metadata generated by the compiler * **opcodes** – Opcodes for the contract generated by the compiler * **src\_map** * **src\_map\_runtime** * **user\_doc** Returns: Instance of the contract Return type: [Contract](web3.contract.html#web3.contract.Contract "web3.contract.Contract") Raises: * [**TypeError**](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.13)") – If the address is not provided * [**AttributeError**](https://docs.python.org/3/library/exceptions.html#AttributeError "(in Python v3.13)") – If the contract class is not initialized See the [Contracts](web3.contract.html) documentation for more information about Contracts. Eth.set\_contract\_factory(_contractFactoryClass_)[](#web3.eth.Eth.set_contract_factory "Link to this definition") Modify the default contract factory from `Contract` to `contractFactoryClass`. Future calls to `Eth.contract()` will then default to `contractFactoryClass`. --- # Contributing — web3.py 7.6.1 documentation * [](index.html) * Contributing * [View page source](_sources/contributing.rst.txt) * * * Contributing[](#contributing "Link to this heading") ====================================================== Thanks for your interest in contributing to web3.py! Read on to learn what would be helpful and how to go about it. If you get stuck along the way, reach for help in the [Python Discord server](https://discord.gg/GHryRvPB84) . How to Help[](#how-to-help "Link to this heading") ---------------------------------------------------- Without code: * Answer user questions within GitHub issues, Stack Overflow, or the [Python Discord server](https://discord.gg/GHryRvPB84) . * Write or record tutorial content. * Improve our documentation (including typo fixes). * [Open an issue](https://github.com/ethereum/web3.py/issues/new) on GitHub to document a bug. Include as much detail as possible, e.g., how to reproduce the issue and any exception messages. With code: * Fix a bug that has been reported in an issue. * Add a feature that has been documented in an issue. * Add a missing test case. Warning **Before you start:** always ask if a change would be desirable or let us know that you plan to work on something! We don’t want to waste your time on changes we can’t accept or duplicated effort. Your Development Environment[](#your-development-environment "Link to this heading") -------------------------------------------------------------------------------------- Note Use of a virtual environment is strongly advised for minimizing dependency issues. See [this article](https://realpython.com/effective-python-environment/#virtual-environments) for usage patterns. All pull requests are made from a fork of the repository; use the GitHub UI to create a fork. web3.py depends on [submodules](https://gist.github.com/gitaarik/8735255) , so when you clone your fork to your local machine, include the `--recursive` flag: $ git clone \--recursive https://github.com//web3.py.git $ cd web3.py Finally, install all development dependencies: $ pip install \-e ".\[dev\]" ### Using Docker[](#using-docker "Link to this heading") Developing within Docker is not required, but if you prefer that workflow, use the _sandbox_ container provided in the **docker-compose.yml** file. To start up the test environment, run: $ docker compose up \-d This will build a Docker container set up with an environment to run the Python test code. Note This container does not have go-ethereum installed, so you cannot run the go-ethereum test suite. To run the Python tests from your local machine: $ docker compose exec sandbox bash \-c 'pytest -n 4 -f -k "not goethereum"' You can run arbitrary commands inside the Docker container by using the bash -c prefix. $ docker compose exec sandbox bash \-c '' Or, if you would like to open a session to the container, run: $ docker compose exec sandbox bash Code Style[](#code-style "Link to this heading") -------------------------------------------------- We value code consistency. To ensure your contribution conforms to the style being used in this project, we encourage you to read our [style guide](https://github.com/ethereum/snake-charmers-tactical-manual/blob/main/style-guide.md) . We use Black for linting. To ignore the commits that introduced Black in git history, you can configure your git environment like so: git config blame.ignoreRevsFile .git-blame-ignore-revs Type Hints[](#type-hints "Link to this heading") -------------------------------------------------- This code base makes use of [type hints](https://www.python.org/dev/peps/pep-0484/) . Type hints make it easy to prevent certain types of bugs, enable richer tooling, and enhance the documentation, making the code easier to follow. All new code is required to include type hints, with the exception of tests. All parameters, as well as the return type of functions, are expected to be typed, with the exception of `self` and `cls` as seen in the following example. def \_\_init\_\_(self, wrapped\_db: DatabaseAPI) \-> None: self.wrapped\_db \= wrapped\_db self.reset() Running The Tests[](#running-the-tests "Link to this heading") ---------------------------------------------------------------- A great way to explore the code base is to run the tests. First, install the test dependencies: $ pip install \-e ".\[test\]" You can run all tests with: $ pytest However, running the entire test suite takes a very long time and is generally impractical. Typically, you’ll just want to run a subset instead, like: $ pytest tests/core/eth-module/test\_accounts.py You can use `tox` to run all the tests for a given version of Python: $ tox \-e py38-core Linting is also performed by the CI. You can save yourself some time by checking for linting errors locally: $ make lint It is important to understand that each pull request must pass the full test suite as part of the CI check. This test suite will run in the CI anytime a pull request is opened or updated. Writing Tests[](#writing-tests "Link to this heading") -------------------------------------------------------- We strongly encourage contributors to write good tests for their code as part of the code review process. This helps ensure that your code is doing what it should be doing. We strongly encourage you to use our existing tests for both guidance and homogeneity / consistency across our tests. We use `pytest` for our tests. For more specific pytest guidance, please refer to the [pytest documentation](https://docs.pytest.org/en/latest) . Within the `pytest` scope, `conftest.py` files are used for common code shared between modules that exist within the same directory as that particular `conftest.py` file. ### Unit Testing and eth-tester Tests[](#unit-testing-and-eth-tester-tests "Link to this heading") Our unit tests are grouped together with tests against the `eth-tester` library, using the `py-evm` library as a backend, via the `EthereumTesterProvider`. These tests live under appropriately named child directories within the `/tests` directory. The core of these tests live under `/tests/core`. Do your best to follow the existing structure when adding a test and make sure that its location makes sense. ### Integration Testing[](#integration-testing "Link to this heading") Our integration test suite setup lives under the `/tests/integration` directory. The integration test suite is dependent on what we call “fixtures” (not to be confused with pytest fixtures). These zip file fixtures, which also live in the `/tests/integration` directory, are configured to run the specific client we are testing against along with a genesis configuration that gives our tests some pre-determined useful objects (like unlocked, pre-loaded accounts) to be able to interact with the client when we run our tests. The parent `/integration` directory houses some common configuration shared across all client tests, whereas the `/go_ethereum` directory houses common code to be shared across geth-specific provider tests. Though the setup and run configurations exist across the different files within `/tests/integration`, our integration module tests are written across different files within `/web3/_utils/module_testing`. * `common.py` files within the client directories contain code that is shared across all provider tests (http, ipc, and ws). This is mostly used to override tests that span across all providers. * `conftest.py` files within each of these directories contain mostly code that can be _used_ by all test files that exist within the same directory or subdirectories of the `conftest.py` file. This is mostly used to house pytest fixtures to be shared among our tests. Refer to the [pytest documentation on fixtures](https://docs.pytest.org/en/latest/how-to/fixtures.html) for more information. * `test_{client}_{provider}.py` files (e.g. `test_goethereum_http.py`) are where client-and-provider-specific test configurations exist. This is mostly used to override tests specific to the provider type for the respective client. ### Working With Test Contracts[](#working-with-test-contracts "Link to this heading") Contracts used for testing exist under `web3/_utils/contract_sources`. These contracts get compiled via the `compile_contracts.py` script in the same directory. To use this script, simply pass the Solidity version to be used to compile the contracts as an argument at the command line. Arguments for the script are: \-v or –version Solidity version to be used to compile the contracts. If blank, the script uses the latest available version from solcx. \-f or –filename If left blank, all .sol files will be compiled and the respective contract data will be generated. Pass in a specific `.sol` filename here to compile just one file. To run the script, you will need the `py-solc-x` library for compiling the files as well as `black` for code formatting. You can install those independently or install the full `[dev]` package extra as shown below. $ pip install "web3\[dev\]" The following example compiles all the contracts and generates their respective contract data that is used across our test files for the test suites. This data gets generated within the `contract_data` subdirectory within the `contract_sources` folder. $ cd ../web3.py/web3/\_utils/contract\_sources $ python compile\_contracts.py \-v 0.8.17 Compiling OffchainLookup ... ... reformatted ... To compile and generate contract data for only one `.sol` file, specify using the filename with the `-f` (or `--filename`) argument flag. $ cd ../web3.py/web3/\_utils/contract\_sources $ python compile\_contracts.py \-v 0.8.17 \-f OffchainLookup.sol Compiling OffchainLookup.sol reformatted ... If there is any contract data that is not generated via the script but is important to pass on to the integration tests, the `_custom_contract_data.py` file within the `contract_data` subdirectory can be used to store that information when appropriate. Be sure to re-generate the integration test fixture after running the script to update the contract bytecodes for the integration test suite - see the [Generating New Fixtures](#generating-fixtures) section below. Manual Testing[](#manual-testing "Link to this heading") ---------------------------------------------------------- To import and test an unreleased version of web3.py in another context, you can install it from your development directory: $ pip install \-e ../path/to/web3py Documentation[](#documentation "Link to this heading") -------------------------------------------------------- Good documentation will lead to quicker adoption and happier users. Please check out our guide on [how to create documentation](https://github.com/ethereum/snake-charmers-tactical-manual/blob/main/documentation.md) for the Python Ethereum ecosystem. Pull requests generate their own preview of the latest documentation at `https://web3py--.org.readthedocs.build/en//`. Pull Requests[](#pull-requests "Link to this heading") -------------------------------------------------------- It’s a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn’t necessarily need to be the final, finished submission. See GitHub’s documentation for [working on pull requests](https://help.github.com/articles/about-pull-requests/) . Once you’ve made a pull request take a look at the Circle CI build status in the GitHub interface and make sure all tests are passing. In general, pull requests that do not pass the CI build yet won’t get reviewed unless explicitly requested. If the pull request introduces changes that should be reflected in the release notes, please add a **newsfragment** file as explained [here](https://github.com/ethereum/web3.py/blob/main/newsfragments/README.md) . If possible, the change to the release notes file should be included in the commit that introduces the feature or bugfix. Generating New Fixtures[](#generating-new-fixtures "Link to this heading") ---------------------------------------------------------------------------- Our integration tests make use of Geth private networks. When new versions of the client software are introduced, new fixtures should be generated. Before generating new fixtures, make sure you have the test dependencies installed: $ pip install \-e ".\[test\]" Note A “fixture” is a pre-synced network. It’s the result of configuring and running a client, deploying the test contracts, and saving the resulting state for testing web3.py functionality against. ### Geth Fixtures[](#geth-fixtures "Link to this heading") 1. Install the desired Geth version on your machine locally. We recommend [py-geth](https://github.com/ethereum/py-geth) for this purpose, because it enables you to easily manage multiple versions of Geth. Note that `py-geth` will need updating to support each new Geth version as well. Adding newer Geth versions to py-geth is straightforward; see past commits for a template. If py-geth has the Geth version you need, install that version locally. For example: $ python \-m geth.install v1.14.12 2. Specify the Geth binary and run the fixture creation script (from within the web3.py directory): $ GETH\_BINARY\=~/.py-geth/geth-v1.14.12/bin/geth python ./tests/integration/generate\_fixtures/go\_ethereum.py 3. The output of this script is your fixture, a zip file, which is now stored in `/tests/integration/`. The `/tests/integration/go_ethereum/conftest.py` and `/web3/tools/benchmark/node.py` files should be updated automatically to point to this new fixture. Delete the old fixture. 4. Run the tests. To ensure that the tests run with the correct Geth version locally, you may again include the `GETH_BINARY` environment variable. 5. The `geth_version` and `pygeth_version` parameter defaults in `/.circleci/config.yml` should be automatically updated to match the `go-ethereum` version used to generate the test fixture and the `py-geth` version that supports installing it. ### CI Testing With a Nightly Geth Build[](#ci-testing-with-a-nightly-geth-build "Link to this heading") Occasionally you’ll want to have CI run the test suite against an unreleased version of Geth - e.g. to test upcoming hard fork changes. The workflow described below is for testing only, as updates will only be merged into main once the Geth release is published and the test runs are updated to use the new stable version. 1. Configure `tests/integration/generate_fixtures/go_ethereum/common.py` as needed. 2. Geth automagically compiles new builds for every commit that gets merged into the codebase. Download the desired build from the [develop builds](https://geth.ethereum.org/downloads/) . 3. Build your test fixture, passing in the binary you just downloaded via `GETH_BINARY`. Don’t forget to update the `/tests/integration/go_ethereum/conftest.py` file to point to your new fixture. 4. Our CI runs on Ubuntu, so download the corresponding 64-bit Linux [develop build](https://geth.ethereum.org/downloads/) , then add it to the root of your web3.py directory. Rename the binary `custom_geth`. 5. In `.circleci/config.yml`, update the `geth_version` pipeline parameter to “custom”. This will trigger the custom Geth build to be used in the CI test suite. 6. Create a PR and let CI do its thing. Releasing[](#releasing "Link to this heading") ------------------------------------------------ ### Final Test Before Each Release[](#final-test-before-each-release "Link to this heading") Before releasing a new version, build and test the package that will be released. There’s a script to build and install the wheel locally, then generate a temporary virtualenv for smoke testing: $ git checkout main && git pull $ make package \# in another shell, navigate to the virtualenv mentioned in output of ^ \# load the virtualenv with the packaged web3.py release $ source package-smoke-test/bin/activate \# smoke test the release $ pip install ipython $ ipython >>> from web3 import Web3, IPCProvider >>> w3 \= Web3(IPCProvider(provider\_url)) >>> w3.is\_connected() >>> ... ### Verify The Latest Documentation[](#verify-the-latest-documentation "Link to this heading") To preview the documentation that will get published: $ make docs ### Preview The Release Notes[](#preview-the-release-notes "Link to this heading") $ towncrier build \--draft ### Compile The Release Notes[](#compile-the-release-notes "Link to this heading") After confirming that the release package looks okay, compile the release notes: $ make notes bump\=$$VERSION\_PART\_TO\_BUMP$$ You may need to fix up any broken release note fragments before committing. Keep running `make build-docs` until it passes, then commit and carry on. ### Push The Release to GitHub & PyPI[](#push-the-release-to-github-pypi "Link to this heading") After committing the compiled release notes and pushing them to the main branch, release a new version: $ make release bump\=$$VERSION\_PART\_TO\_BUMP$$ ### Which Version Part to Bump[](#which-version-part-to-bump "Link to this heading") The version format for this repo is `{major}.{minor}.{patch}` for stable, and `{major}.{minor}.{patch}-{stage}.{devnum}` for unstable (`stage` can be alpha or beta). During a release, specify which part to bump, like `make release bump=minor` or `make release bump=devnum`. If you are in an alpha version, `make release bump=stage` will bump to beta. If you are in a beta version, `make release bump=stage` will bump to a stable version. To issue an unstable version when the current version is stable, specify the new version explicitly, like `make release bump="--new-version 4.0.0-alpha.1 devnum"`. --- # Search — web3.py 7.6.1 documentation * [](index.html) * Search * * * --- # Python Module Index — web3.py 7.6.1 documentation * [](index.html) * Python Module Index * * * Python Module Index =================== [**e**](#cap-e) | [**w**](#cap-w) | | | | | --- | --- | --- | | | | | | | **e** | | | ![-](_static/minus.png) | [`ens`](ens.html#module-ens) | | | | [`ens.async_ens`](ens.html#module-ens.async_ens) | | | | [`ens.ens`](ens.html#module-ens.ens) | | | | [`ens.exceptions`](ens.html#module-ens.exceptions) | | | | | | | | **w** | | | ![-](_static/minus.png) | [`web3`](web3.main.html#module-web3) | | | | [`web3.contract`](web3.contract.html#module-web3.contract) | | | | [`web3.eth`](web3.eth.html#module-web3.eth) | | | | [`web3.gas_strategies.rpc`](gas_price.html#module-web3.gas_strategies.rpc) | | | | [`web3.gas_strategies.time_based`](gas_price.html#module-web3.gas_strategies.time_based) | | | | [`web3.geth`](web3.geth.html#module-web3.geth) | | | | [`web3.geth.admin`](web3.geth.html#module-web3.geth.admin) | | | | [`web3.geth.debug`](web3.geth.html#module-web3.geth.debug) | | | | [`web3.geth.txpool`](web3.geth.html#module-web3.geth.txpool) | | | | [`web3.net`](web3.net.html#module-web3.net) | | | | [`web3.tracing`](web3.tracing.html#module-web3.tracing) | | | | [`web3.utils`](web3.utils.html#module-web3.utils) | | | | [`web3.utils.abi`](web3.utils.html#module-web3.utils.abi) | | | | [`web3.utils.filters`](filters.html#module-web3.utils.filters) | | --- # Unknown Troubleshooting =============== .. \_setup\_environment: Set up a clean environment -------------------------- Many things can cause a broken environment. You might be on an unsupported version of Python. Another package might be installed that has a name or version conflict. Often, the best way to guarantee a correct environment is with \`\`virtualenv\`\`, like: .. code-block:: 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 .. NOTE:: Remember that each new terminal session requires you to reactivate your virtualenv, like: \`\`$ source ~/.venv-py3/bin/activate\`\` .. \_instance\_troubleshooting: Why can't I use a particular function? -------------------------------------- Note that a web3.py instance must be configured before you can use most of its capabilities. One symptom of not configuring the instance first is an error that looks something like this: \`\`AttributeError: type object 'Web3' has no attribute 'eth'\`\`. To properly configure your web3.py instance, specify which provider you're using to connect to the Ethereum network. An example configuration, if you're connecting to a locally run node, might be: .. code-block:: 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(...) Refer to the :ref:\`providers\` documentation for further help with configuration. .. \_use\_metamask\_accounts: Why isn't my web3 instance connecting to the network? ----------------------------------------------------- You can check that your instance is connected via the \`\`is\_connected\`\` method: .. code-block:: python >>> w3.is\_connected() False There are a variety of explanations for why you may see \`\`False\`\` here. To help you diagnose the problem, \`\`is\_connected\`\` has an optional \`\`show\_traceback\`\` argument: .. code-block:: python >>> w3.is\_connected(show\_traceback=True) # this is an example, your error may differ # ProviderConnectionError: Problem connecting to provider with error: : cannot connect to IPC socket at path: None If you're running a local node, such as Geth, double-check that you've indeed started the binary and that you've started it from the intended directory - particularly if you've specified a relative path to its ipc file. If that does not address your issue, it's probable that you still have a Provider configuration issue. There are several options for configuring a Provider, detailed :ref:\`here\`. .. \_faucets: How do I get ether for my test network? --------------------------------------- Test networks usually have something called a "faucet" to help get test ether to people who want to use it. The faucet simply sends you test ether when you visit a web page, or ping a chat bot, etc. Each test network has its own version of test ether, so each one must maintain its own faucet. Faucet mechanisms tend to come and go, so a web search for "ethereum testnet faucet" should give you the most up-to-date options. How do I use my MetaMask accounts from web3.py? ----------------------------------------------- Export your private key from MetaMask, and use the local private key tools in web3.py to sign and send transactions. See \`how to export your private key \`\_ and :ref:\`eth-account\`. .. \_account\_troubleshooting: How do I create an account? --------------------------- In general, your options for accounts are: - Import a keystore file for an account and :ref:\`extract the private key\`. - Create an account via the :ref:\`eth-account \` API, e.g., \`\`new\_acct = w3.eth.account.create()\`\`. - Use an external service (e.g. Metamask) to generate a new account, then securely import its private key. .. Warning:: Don't store real value in an account until you are familiar with security best practices. If you lose your private key, you lose your account! Why doesn't my transaction work on another network? --------------------------------------------------- web3.py is an Ethereum-specific library, which defaults to \`"type 2" EIP-1559 transactions \`\_ as of the London network upgrade. Some chains (including Ethereum L2s) do not support the same transaction types. If your chain doesn't support this transaction type, you likely need to create a "legacy" transaction, i.e., include \`\`gasPrice\`\`, but not \`\`type\`\`, \`\`maxFeePerGas\`\`, or \`\`maxPriorityFeePerGas\`\` in your transaction body. If that doesn't resolve your issue, open a GitHub issue or reach out for help in the community \`Discord\`\_ server if you're having trouble with an Ethereum-ecosystem chain. If you're debugging in an alternative ecosystem, please find another appropriate forum to raise your question. .. \_Discord: https://discord.gg/GHryRvPB84 How do I conform to ABI types? ------------------------------ The web3 library follows the following conventions: Bytes vs Text ~~~~~~~~~~~~~ \* The term \*bytes\* is used to refer to the binary representation of a string. \* The term \*text\* is used to refer to unicode representations of strings. Hexadecimal Representations ~~~~~~~~~~~~~~~~~~~~~~~~~~~ \* All hexadecimal values will be returned as text. \* All hexadecimal values will be \`\`0x\`\` prefixed. Ethereum Addresses ~~~~~~~~~~~~~~~~~~ All addresses must be supplied in one of three ways: \* A 20-byte hexadecimal that is checksummed using the \`EIP-55 \`\_ spec. \* A 20-byte binary address (python bytes type). \* While connected to an Ethereum Name Service (ENS) supported chain, an ENS name (often in the form \`\`myname.eth\`\`). Disabling Strict Bytes Type Checking ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is a boolean flag on the \`\`Web3\`\` class and the \`\`ENS\`\` class that will disable strict bytes type checking. This allows bytes values of Python strings and allows byte strings less than the specified byte size, appropriately padding values that need padding. To disable stricter checks, set the \`\`w3.strict\_bytes\_type\_checking\`\` (or \`\`ns.strict\_bytes\_type\_checking\`\`) flag to \`\`False\`\`. This will no longer cause the \`\`Web3\`\` / \`\`ENS\`\` instance to raise an error if a Python string is passed in without a "0x" prefix. It will also render valid byte strings or hex strings that are below the exact number of bytes specified by the ABI type by padding the value appropriately, according to the ABI type. See the :ref:\`disable-strict-byte-check\` section for an example on using the flag and more details. .. note:: If a standalone \`\`ENS\`\` instance is instantiated from a \`\`Web3\`\` instance, i.e. \`\`ns = ENS.from\_web3(w3)\`\`, it will inherit the value of the \`\`w3.strict\_bytes\_type\_checking\`\` flag from the \`\`Web3\`\` instance at the time of instantiation. Also of note, all modules on the \`\`Web3\`\` class will inherit the value of this flag, since all modules use the parent \`\`w3\`\` object reference under the hood. This means that \`\`w3.eth.w3.strict\_bytes\_type\_checking\`\` will always have the same value as \`\`w3.strict\_bytes\_type\_checking\`\`. For more details on the ABI specification, refer to the \`Solidity ABI Spec \`\_. Types by Example ~~~~~~~~~~~~~~~~ Let's use a contrived contract to demonstrate input types in web3.py: .. code-block:: none contract ManyTypes { // booleans bool public b; // unsigned ints uint8 public u8; uint256 public u256; uint256\[\] public u256s; // signed ints int8 public i8; // addresses address public addr; address\[\] public addrs; // bytes bytes1 public b1; // structs struct S { address sa; bytes32 sb; } mapping(address => S) addrStructs; function updateBool(bool x) public { b = x; } function updateUint8(uint8 x) public { u8 = x; } function updateUint256(uint256 x) public { u256 = x; } function updateUintArray(uint256\[\] memory x) public { u256s = x; } function updateInt8(int8 x) public { i8 = x; } function updateAddr(address x) public { addr = x; } function updateBytes1(bytes1 x) public { b1 = x; } function updateMapping(S memory x) public { addrStructs\[x.sa\] = x; } } Booleans \`\`\`\`\`\`\`\` .. code-block:: python contract\_instance.functions.updateBool(True).transact() Unsigned Integers \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` .. code-block:: python contract\_instance.functions.updateUint8(255).transact() contract\_instance.functions.updateUint256(2\*\*256 - 1).transact() contract\_instance.functions.updateUintArray(\[1, 2, 3\]).transact() Signed Integers \`\`\`\`\`\`\`\`\`\`\`\`\`\`\` .. code-block:: python contract\_instance.functions.updateInt8(-128).transact() Addresses \`\`\`\`\`\`\`\`\` .. code-block:: python contract\_instance.functions.updateAddr("0x0000000000000000000000000000000000000000").transact() Bytes \`\`\`\`\` .. code-block:: python contract\_instance.functions.updateBytes1(HexBytes(255)).transact() Structs \`\`\`\`\`\`\` .. code-block:: python contract\_instance.functions.updateMapping({"sa": "0x0000000000000000000000000000000000000000", "sb": HexBytes(123)}).transact() How can I optimize Ethereum JSON-RPC API access? ------------------------------------------------ Your Ethereum node JSON-RPC API might be slow when fetching multiple and large requests, especially when running batch jobs. Here are some tips for how to speed up your web3.py application. - Run your client locally, e.g., \`Go Ethereum \`\_ or \`TurboGeth \`\_. The network latency and speed are the major limiting factors for fast API access. - Use IPC communication instead of HTTP/WebSockets. See :ref:\`choosing\_provider\`. - Use an optimised JSON decoder. A future iteration of web3.py may change the default decoder or provide an API to configure one, but for now, you may patch the provider class to use \`ujson \`\_. .. code-block:: python """JSON-RPC decoding optimised for web3.py""" from typing import cast import ujson from web3.providers import JSONBaseProvider from web3.types import RPCResponse def \_fast\_decode\_rpc\_response(raw\_response: bytes) -> RPCResponse: decoded = ujson.loads(raw\_response) return cast(RPCResponse, decoded) def patch\_provider(provider: JSONBaseProvider): """Monkey-patch web3.py provider for faster JSON decoding. Call this on your provider after construction. This greatly improves JSON-RPC API access speeds, when fetching multiple and large responses. """ provider.decode\_rpc\_response = \_fast\_decode\_rpc\_response Why am I getting Visual C++ or Cython not installed error? ---------------------------------------------------------- Some Windows users that do not have Microsoft Visual C++ version 14.0 or greater installed may see an error message when installing web3.py as shown below: .. code-block:: shell error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ To fix this error, download and install Microsoft Visual C++ from here : \`Microsoft Visual C++ Redistributable for Visual Studio \`\_ - \`x64 Visual C++ \`\_ - \`x86 Visual C++ \`\_ - \`ARM64 Visual C++ \`\_ How do I convert currency denominations? ---------------------------------------- The following denominations are supported: +--------------+---------------------------------+ | denomination | amount in wei | +--------------+---------------------------------+ | wei | 1 | +--------------+---------------------------------+ | kwei | 1000 | +--------------+---------------------------------+ | babbage | 1000 | +--------------+---------------------------------+ | femtoether | 1000 | +--------------+---------------------------------+ | mwei | 1000000 | +--------------+---------------------------------+ | lovelace | 1000000 | +--------------+---------------------------------+ | picoether | 1000000 | +--------------+---------------------------------+ | gwei | 1000000000 | +--------------+---------------------------------+ | shannon | 1000000000 | +--------------+---------------------------------+ | nanoether | 1000000000 | +--------------+---------------------------------+ | nano | 1000000000 | +--------------+---------------------------------+ | szabo | 1000000000000 | +--------------+---------------------------------+ | microether | 1000000000000 | +--------------+---------------------------------+ | micro | 1000000000000 | +--------------+---------------------------------+ | finney | 1000000000000000 | +--------------+---------------------------------+ | milliether | 1000000000000000 | +--------------+---------------------------------+ | milli | 1000000000000000 | +--------------+---------------------------------+ | ether | 1000000000000000000 | +--------------+---------------------------------+ | kether | 1000000000000000000000 | +--------------+---------------------------------+ | grand | 1000000000000000000000 | +--------------+---------------------------------+ | mether | 1000000000000000000000000 | +--------------+---------------------------------+ | gether | 1000000000000000000000000000 | +--------------+---------------------------------+ | tether | 1000000000000000000000000000000 | +--------------+---------------------------------+ You can use the :meth:\`~web3.from\_wei\` method to convert a balance to ether (or another denomination). .. code-block:: python >>> web3.from\_wei(3841357360894980500000001, 'ether') Decimal('3841357.360894980500000001') To convert back to wei, you can use the inverse function, :meth:\`~web3.to\_wei\`. Note that Python's default floating point precision is insufficient for this use case, so it's necessary to cast the value to a \`Decimal \`\_ if it isn't already. .. code-block:: python >>> from decimal import Decimal >>> web3.to\_wei(Decimal('3841357.360894980500000001'), 'ether') 3841357360894980500000001 Best practice: If you need to work with multiple currency denominations, default to wei. A typical workflow may require a conversion from some denomination to wei, then from wei to whatever you need. .. code-block:: python >>> web3.to\_wei(Decimal('0.000000005'), 'ether') 5000000000 >>> web3.from\_wei(5000000000, 'gwei') Decimal('5') How do I adjust the log levels? ------------------------------- web3.py internally uses \`Python logging subsystem \`\_. If you want to run your application logging in debug mode, below is an example of how to make some JSON-RPC traffic quieter. .. code-block:: python import logging import coloredlogs def setup\_logging(log\_level=logging.DEBUG): """Setup root logger and quiet some levels.""" logger = logging.getLogger() # Set log format to display the logger name to hunt down verbose logging modules fmt = "%(name)-25s %(levelname)-8s %(message)s" # Use colored logging output for console with the coloredlogs package # https://pypi.org/project/coloredlogs/ coloredlogs.install(level=log\_level, fmt=fmt, logger=logger) # Disable logging of JSON-RPC requests and replies logging.getLogger("web3.RequestManager").setLevel(logging.WARNING) logging.getLogger("web3.providers.HTTPProvider").setLevel(logging.WARNING) # logging.getLogger("web3.RequestManager").propagate = False # Disable all internal debug logging of requests and urllib3 # E.g. HTTP traffic logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) return logger --- # Unknown .. \_filtering: Events and Logs =============== If you're on this page, you're likely looking for an answer to this question: \*\*How do I know when a specific contract is used?\*\* You have several options: 1. Query blocks for transactions that include the contract address in the \`\`"to"\`\` field. This contrived example is searching the latest block for any transactions sent to the WETH\_ contract. .. code-block:: python WETH\_ADDRESS = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' block = w3.eth.get\_block('latest') for tx\_hash in block.transactions: tx = w3.eth.get\_transaction(tx\_hash) if tx\['to'\] == WETH\_ADDRESS: print(f'Found interaction with WETH contract! {tx}') 2. Query for logs emitted by a contract. After instantiating a web3.py Contract object, you can :ref:\`fetch logs \` for any event listed in the ABI. In this example, we query for \`\`Transfer\`\` events in the latest block and log out the results. .. code-block:: python WETH\_ADDRESS = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' WETH\_ABI = '\[{"constant":true,"inputs":\[\],"name":"name","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}\],"name":"approve","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":\[\],"name":"totalSupply","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"src","type":"address"},{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}\],"name":"transferFrom","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":\[{"name":"wad","type":"uint256"}\],"name":"withdraw","outputs":\[\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":\[\],"name":"decimals","outputs":\[{"name":"","type":"uint8"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":\[{"name":"","type":"address"}\],"name":"balanceOf","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":\[\],"name":"symbol","outputs":\[{"name":"","type":"string"}\],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":\[{"name":"dst","type":"address"},{"name":"wad","type":"uint256"}\],"name":"transfer","outputs":\[{"name":"","type":"bool"}\],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":\[\],"name":"deposit","outputs":\[\],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":\[{"name":"","type":"address"},{"name":"","type":"address"}\],"name":"allowance","outputs":\[{"name":"","type":"uint256"}\],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"guy","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Approval","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"src","type":"address"},{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"dst","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":\[{"indexed":true,"name":"src","type":"address"},{"indexed":false,"name":"wad","type":"uint256"}\],"name":"Withdrawal","type":"event"}\]' weth\_contract = w3.eth.contract(address=WETH\_ADDRESS, abi=WETH\_ABI) # fetch transfer events in the last block logs = weth\_contract.events.Transfer().get\_logs(from\_block=w3.eth.block\_number) for log in logs: print(f"Transfer of {w3.from\_wei(log.args.wad, 'ether')} WETH from {log.args.src} to {log.args.dst}") See an advanced example of fetching log history :ref:\`here \`. 3. Subscribe to events for real-time updates. When using a persistent connection provider (:class:\`~web3.providers.persistent.WebSocketProvider\` or :class:\`~web3.providers.persistent.AsyncIPCProvider\`), the :meth:\`subscribe() \` method can be used to establish a new event subscription. This example subscribes to \`\`Transfer\`\` events of the WETH contract. .. code-block:: python import asyncio from web3 import AsyncWeb3, WebSocketProvider from eth\_abi.abi import decode WETH\_ADDRESS = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" async def subscribe\_to\_transfer\_events(): async with AsyncWeb3(WebSocketProvider("...")) as w3: transfer\_event\_topic = w3.keccak(text="Transfer(address,address,uint256)") filter\_params = { "address": WETH\_ADDRESS, "topics": \[transfer\_event\_topic\], } subscription\_id = await w3.eth.subscribe("logs", filter\_params) print(f"Subscribing to transfer events for WETH at {subscription\_id}") async for payload in w3.socket.process\_subscriptions(): result = payload\["result"\] from\_addr = decode(\["address"\], result\["topics"\]\[1\])\[0\] to\_addr = decode(\["address"\], result\["topics"\]\[2\])\[0\] amount = decode(\["uint256"\], result\["data"\])\[0\] print(f"{w3.from\_wei(amount, 'ether')} WETH from {from\_addr} to {to\_addr}") asyncio.run(subscribe\_to\_transfer\_events()) For more usage examples see the docs on :ref:\`subscription-examples\`. 4. Use a filter. .. warning :: While filters can be a very convenient way to monitor for blocks, transactions, or events, they are notoriously unreliable. Both remote and locally hosted nodes have a reputation for occasionally dropping filters, and some remote node providers don't support filter-related RPC calls at all. .. py:module:: web3.utils.filters The :meth:\`web3.eth.Eth.filter\` method can be used to set up filters for: \* Pending Transactions: \`\`w3.eth.filter("pending")\`\` \* New Blocks \`\`w3.eth.filter("latest")\`\` \* Event Logs Through the contract instance api: .. code-block:: python event\_filter = my\_contract.events.myEvent.create\_filter(from\_block='latest', argument\_filters={'arg1':10}) Or built manually by supplying \`valid filter params \`\_: .. code-block:: python event\_filter = w3.eth.filter({"address": contract\_address}) \* Attaching to an existing filter .. code-block:: python existing\_filter = w3.eth.filter(filter\_id="0x0") .. note :: Creating event filters requires that your Ethereum node has an API support enabled for filters. Note that Infura support for filters does not offer access to \`pending\` filters. To get event logs on other stateless nodes please see :class:\`web3.contract.ContractEvents\`. Filter Class ------------ .. py:class:: Filter(web3, filter\_id) .. py:attribute:: Filter.filter\_id The \`\`filter\_id\`\` for this filter as returned by the \`\`eth\_newFilter\`\` RPC method when this filter was created. .. py:method:: Filter.get\_new\_entries() Retrieve new entries for this filter. Logs will be retrieved using the :func:\`web3.eth.Eth.get\_filter\_changes\` which returns only new entries since the last poll. .. py:method:: Filter.get\_all\_entries() Retrieve all entries for this filter. Logs will be retrieved using the :func:\`web3.eth.Eth.get\_filter\_logs\` which returns all entries that match the given filter. .. py:method:: Filter.format\_entry(entry) Hook for subclasses to modify the format of the log entries this filter returns, or passes to its callback functions. By default this returns the \`\`entry\`\` parameter unmodified. .. py:method:: Filter.is\_valid\_entry(entry) Hook for subclasses to add additional programmatic filtering. The default implementation always returns \`\`True\`\`. Block and Transaction Filter Classes ------------------------------------ .. py:class:: BlockFilter(...) \`\`BlockFilter\`\` is a subclass of :class:\`Filter\`. You can setup a filter for new blocks using \`\`web3.eth.filter('latest')\`\` which will return a new :class:\`BlockFilter\` object. .. code-block:: python new\_block\_filter = w3.eth.filter('latest') new\_block\_filter.get\_new\_entries() .. note:: \`\`"safe"\`\` and \`\`"finalized"\`\` block identifiers are not yet supported for \`\`eth\_newBlockFilter\`\`. .. py:class:: TransactionFilter(...) \`\`TransactionFilter\`\` is a subclass of :class:\`Filter\`. You can setup a filter for new blocks using \`\`web3.eth.filter('pending')\`\` which will return a new :class:\`TransactionFilter\` object. .. code-block:: python new\_transaction\_filter = w3.eth.filter('pending') new\_transaction\_filter.get\_new\_entries() Event Log Filters ----------------- You can set up a filter for event logs using the web3.py contract api: :meth:\`web3.contract.Contract.events.your\_event\_name.create\_filter\`, which provides some conveniences for creating event log filters. Refer to the following example: .. code-block:: python event\_filter = my\_contract.events..create\_filter(from\_block="latest", argument\_filters={'arg1':10}) event\_filter.get\_new\_entries() See :meth:\`web3.contract.Contract.events.your\_event\_name.create\_filter()\` documentation for more information. You can set up an event log filter like the one above with \`\`web3.eth.filter\`\` by supplying a dictionary containing the standard filter parameters. Assuming that \`\`arg1\`\` is indexed, the equivalent filter creation would look like: .. code-block:: python event\_signature\_hash = web3.keccak(text="eventName(uint32)").hex() event\_filter = web3.eth.filter({ "address": myContract\_address, "topics": \[event\_signature\_hash, "0x000000000000000000000000000000000000000000000000000000000000000a"\], }) The \`\`topics\`\` argument is order-dependent. For non-anonymous events, the first item in the topic list is always the keccack hash of the event signature. Subsequent topic items are the hex encoded values for indexed event arguments. In the above example, the second item is the \`\`arg1\`\` value \`\`10\`\` encoded to its hex string representation. In addition to being order-dependent, there are a few more points to recognize when specifying topic filters: Given a transaction log with topics \[A, B\], the following topic filters will yield a match: - \[\] "anything" - \[A\] "A in first position (and anything after)" - \[None, B\] "anything in first position AND B in second position (and anything after)" - \[A, B\] "A in first position AND B in second position (and anything after)" - \[\[A, B\], \[A, B\]\] "(A OR B) in first position AND (A OR B) in second position (and anything after)" See the JSON-RPC documentation for \`eth\_newFilter \`\_ more information on the standard filter parameters. .. note:: Though \`\`"finalized"\`\` and \`\`"safe"\`\` block identifiers are not yet part of the specifications for \`\`eth\_newFilter\`\`, they are supported by web3.py and may or may not yield expected results depending on the node being accessed. Creating a log filter by either of the above methods will return a :class:\`LogFilter\` instance. .. py:class:: LogFilter(web3, filter\_id, log\_entry\_formatter=None, data\_filter\_set=None) The :py:class:\`LogFilter\` class is a subclass of :class:\`Filter\`. See the :class:\`Filter\` documentation for inherited methods. :class:\`LogFilter\` provides the following additional methods: .. py:method:: LogFilter.set\_data\_filters(data\_filter\_set) Provides a means to filter on the log data, in other words the ability to filter on values from un-indexed event arguments. The parameter \`\`data\_filter\_set\`\` should be a list or set of 32-byte hex encoded values. Examples: Listening For Events ------------------------------ Synchronous ~~~~~~~~~~~ .. code-block:: 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() .. \_asynchronous\_filters: Asynchronous Filter Polling ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting with web3 version 4, the \`\`watch\`\` method was taken out of the web3 filter objects. There are many decisions to be made when designing a system regarding threading and concurrency. Rather than force a decision, web3 leaves these choices up to the user. Below are some example implementations of asynchronous filter-event handling that can serve as starting points. Single threaded concurrency with \`\`async\`\` and \`\`await\`\` \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Beginning in python 3.5, the \`\`async\`\` and \`\`await\`\` built-in keywords were added. These provide a shared api for coroutines that can be utilized by modules such as the built-in asyncio\_. Below is an example event loop using asyncio\_, that polls multiple web3 filter object, and passes new entries to a handler. .. code-block:: python from web3 import Web3, IPCProvider import asyncio # instantiate Web3 instance w3 = Web3(IPCProvider(...)) def handle\_event(event): print(event) # and whatever async def log\_loop(event\_filter, poll\_interval): while True: for event in event\_filter.get\_new\_entries(): handle\_event(event) await asyncio.sleep(poll\_interval) def main(): block\_filter = w3.eth.filter('latest') tx\_filter = w3.eth.filter('pending') loop = asyncio.get\_event\_loop() try: loop.run\_until\_complete( asyncio.gather( log\_loop(block\_filter, 2), log\_loop(tx\_filter, 2))) finally: loop.close() if \_\_name\_\_ == '\_\_main\_\_': main() Read the asyncio\_ documentation for more information. Running the event loop in a separate thread \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Here is an extended version of above example, where the event loop is run in a separate thread, releasing the \`\`main\`\` function for other tasks. .. code-block:: 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() Here are some other libraries that provide frameworks for writing asynchronous python: \* gevent\_ \* twisted\_ \* celery\_ Examples -------- .. \_advanced\_token\_fetch: Advanced example: Fetching all token transfer events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In this example, we show how to fetch all events of a certain event type from the Ethereum blockchain. There are three challenges when working with a large set of events: \* How to incrementally update an existing database of fetched events \* How to deal with interruptions in long running processes \* How to deal with \`eth\_getLogs\` JSON-RPC call query limitations \* How to handle Ethereum minor chain reorganisations in (near) real-time data eth\_getLogs limitations \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\`\` Ethereum JSON-RPC API servers, like Geth, do not provide an easy way to paginate over events, only over blocks. There's no request that can find the first block with an event or how many events occur within a range of blocks. The only feedback the JSON-RPC service will give you is whether the \`\`eth\_getLogs\`\` call failed. In this example script, we provide two kinds of heuristics to deal with this issue. The script scans events in a chunk of blocks (start block number - end block number). Then it uses two methods to find how many events there are likely to be in a block window: \* Dynamically set the block range window size, while never exceeding a threshold (e.g., 10,000 blocks). \* In the case of \`\`eth\_getLogs\`\`, the JSON-RPC call gives a timeout error, decrease the end block number and tries again with a smaller block range window. Example code \`\`\`\`\`\`\`\`\`\`\`\` The following example code is divided into a reusable \`\`EventScanner\`\` class and then a demo script that: \* fetches all transfer events for \`RCC token \`\_, \* can incrementally run again to check if there are new events, \* handles interruptions (e.g., CTRL+C abort) gracefully, \* writes all \`\`Transfer\`\` events in a single file JSON database, so that other process can consume them, \* uses the \`tqdm \`\_ library for progress bar output in a console, \* only supports \`\`HTTPS\`\` providers, because JSON-RPC retry logic depends on the implementation details of the underlying protocol, \* disables the default exception retry configuration because it does not know how to handle the shrinking block range window for \`\`eth\_getLogs\`\`, and \* consumes around 20k JSON-RPC API calls. The script can be run with: \`\`python ./eventscanner.py \`\`. .. code-block:: python """A stateful event scanner for Ethereum-based blockchains using web3.py. With the stateful mechanism, you can do one batch scan or incremental scans, where events are added wherever the scanner left off. """ import datetime import time import logging from abc import ABC, abstractmethod from typing import Tuple, Optional, Callable, List, Iterable, Dict, Any from web3 import Web3 from web3.contract import Contract from web3.datastructures import AttributeDict from web3.exceptions import BlockNotFound from eth\_abi.codec import ABICodec # Currently this method is not exposed over official web3 API, # but we need it to construct eth\_getLogs parameters from web3.\_utils.filters import construct\_event\_filter\_params from web3.\_utils.events import get\_event\_data logger = logging.getLogger(\_\_name\_\_) class EventScannerState(ABC): """Application state that remembers what blocks we have scanned in the case of crash. """ @abstractmethod def get\_last\_scanned\_block(self) -> int: """Number of the last block we have scanned on the previous cycle. :return: 0 if no blocks scanned yet """ @abstractmethod def start\_chunk(self, block\_number: int): """Scanner is about to ask data of multiple blocks over JSON-RPC. Start a database session if needed. """ @abstractmethod def end\_chunk(self, block\_number: int): """Scanner finished a number of blocks. Persistent any data in your state now. """ @abstractmethod def process\_event(self, block\_when: datetime.datetime, event: AttributeDict) -> object: """Process incoming events. This function takes raw events from Web3, transforms them to your application internal format, then saves them in a database or some other state. :param block\_when: When this block was mined :param event: Symbolic dictionary of the event data :return: Internal state structure that is the result of event transformation. """ @abstractmethod def delete\_data(self, since\_block: int) -> int: """Delete any data since this block was scanned. Purges any potential minor reorg data. """ class EventScanner: """Scan blockchain for events and try not to abuse JSON-RPC API too much. Can be used for real-time scans, as it detects minor chain reorganisation and rescans. Unlike the easy web3.contract.Contract, this scanner can scan events from multiple contracts at once. For example, you can get all transfers from all tokens in the same scan. You \*should\* disable the default \`\`exception\_retry\_configuration\`\` on your provider for Web3, because it cannot correctly throttle and decrease the \`eth\_getLogs\` block number range. """ def \_\_init\_\_(self, w3: Web3, contract: Contract, state: EventScannerState, events: List, filters: Dict\[str, Any\], max\_chunk\_scan\_size: int = 10000, max\_request\_retries: int = 30, request\_retry\_seconds: float = 3.0): """ :param contract: Contract :param events: List of web3 Event we scan :param filters: Filters passed to get\_logs :param max\_chunk\_scan\_size: JSON-RPC API limit in the number of blocks we query. (Recommendation: 10,000 for mainnet, 500,000 for testnets) :param max\_request\_retries: How many times we try to reattempt a failed JSON-RPC call :param request\_retry\_seconds: Delay between failed requests to let JSON-RPC server to recover """ self.logger = logger self.contract = contract self.w3 = w3 self.state = state self.events = events self.filters = filters # Our JSON-RPC throttling parameters self.min\_scan\_chunk\_size = 10 # 12 s/block = 120 seconds period self.max\_scan\_chunk\_size = max\_chunk\_scan\_size self.max\_request\_retries = max\_request\_retries self.request\_retry\_seconds = request\_retry\_seconds # Factor how fast we increase the chunk size if results are found # # (slow down scan after starting to get hits) self.chunk\_size\_decrease = 0.5 # Factor how fast we increase chunk size if no results found self.chunk\_size\_increase = 2.0 @property def address(self): return self.token\_address def get\_block\_timestamp(self, block\_num) -> datetime.datetime: """Get Ethereum block timestamp""" try: block\_info = self.w3.eth.get\_block(block\_num) except BlockNotFound: # Block was not mined yet, # minor chain reorganisation? return None last\_time = block\_info\["timestamp"\] return datetime.datetime.utcfromtimestamp(last\_time) def get\_suggested\_scan\_start\_block(self): """Get where we should start to scan for new token events. If there are no prior scans, start from block 1. Otherwise, start from the last end block minus ten blocks. We rescan the last ten scanned blocks in the case there were forks to avoid misaccounting due to minor single block works (happens once in an hour in Ethereum). These heuristics could be made more robust, but this is for the sake of simple reference implementation. """ end\_block = self.get\_last\_scanned\_block() if end\_block: return max(1, end\_block - self.NUM\_BLOCKS\_RESCAN\_FOR\_FORKS) return 1 def get\_suggested\_scan\_end\_block(self): """Get the last mined block on Ethereum chain we are following.""" # Do not scan all the way to the final block, as this # block might not be mined yet return self.w3.eth.block\_number - 1 def get\_last\_scanned\_block(self) -> int: return self.state.get\_last\_scanned\_block() def delete\_potentially\_forked\_block\_data(self, after\_block: int): """Purge old data in the case of blockchain reorganisation.""" self.state.delete\_data(after\_block) def scan\_chunk(self, start\_block, end\_block) -> Tuple\[int, datetime.datetime, list\]: """Read and process events between to block numbers. Dynamically decrease the size of the chunk if the case JSON-RPC server pukes out. :return: tuple(actual end block number, when this block was mined, processed events) """ block\_timestamps = {} get\_block\_timestamp = self.get\_block\_timestamp # Cache block timestamps to reduce some RPC overhead # Real solution might include smarter models around block def get\_block\_when(block\_num): if block\_num not in block\_timestamps: block\_timestamps\[block\_num\] = get\_block\_timestamp(block\_num) return block\_timestamps\[block\_num\] all\_processed = \[\] for event\_type in self.events: # Callable that takes care of the underlying web3 call def \_fetch\_events(\_start\_block, \_end\_block): return \_fetch\_events\_for\_all\_contracts(self.w3, event\_type, self.filters, from\_block=\_start\_block, to\_block=\_end\_block) # Do \`n\` retries on \`eth\_getLogs\`, # throttle down block range if needed end\_block, events = \_retry\_web3\_call( \_fetch\_events, start\_block=start\_block, end\_block=end\_block, retries=self.max\_request\_retries, delay=self.request\_retry\_seconds) for evt in events: idx = evt\["logIndex"\] # Integer of the log index position in the block, null when its pending # We cannot avoid minor chain reorganisations, but # at least we must avoid blocks that are not mined yet assert idx is not None, "Somehow tried to scan a pending block" block\_number = evt\["blockNumber"\] # Get UTC time when this event happened (block mined timestamp) # from our in-memory cache block\_when = get\_block\_when(block\_number) logger.debug(f"Processing event {evt\['event'\]}, block: {evt\['blockNumber'\]} count: {evt\['blockNumber'\]}") processed = self.state.process\_event(block\_when, evt) all\_processed.append(processed) end\_block\_timestamp = get\_block\_when(end\_block) return end\_block, end\_block\_timestamp, all\_processed def estimate\_next\_chunk\_size(self, current\_chuck\_size: int, event\_found\_count: int): """Try to figure out optimal chunk size Our scanner might need to scan the whole blockchain for all events \* We want to minimize API calls over empty blocks \* We want to make sure that one scan chunk does not try to process too many entries once, as we try to control commit buffer size and potentially asynchronous busy loop \* Do not overload node serving JSON-RPC API by asking data for too many events at a time Currently Ethereum JSON-API does not have an API to tell when a first event occurred in a blockchain and our heuristics try to accelerate block fetching (chunk size) until we see the first event. These heuristics exponentially increase the scan chunk size depending on if we are seeing events or not. When any transfers are encountered, we are back to scanning only a few blocks at a time. It does not make sense to do a full chain scan starting from block 1, doing one JSON-RPC call per 20 blocks. """ if event\_found\_count > 0: # When we encounter first events, reset the chunk size window current\_chuck\_size = self.min\_scan\_chunk\_size else: current\_chuck\_size \*= self.chunk\_size\_increase current\_chuck\_size = max(self.min\_scan\_chunk\_size, current\_chuck\_size) current\_chuck\_size = min(self.max\_scan\_chunk\_size, current\_chuck\_size) return int(current\_chuck\_size) def scan(self, start\_block, end\_block, start\_chunk\_size=20, progress\_callback=Optional\[Callable\]) -> Tuple\[ list, int\]: """Perform a token balances scan. Assumes all balances in the database are valid before start\_block (no forks sneaked in). :param start\_block: The first block included in the scan :param end\_block: The last block included in the scan :param start\_chunk\_size: How many blocks we try to fetch over JSON-RPC on the first attempt :param progress\_callback: If this is an UI application, update the progress of the scan :return: \[All processed events, number of chunks used\] """ assert start\_block <= end\_block current\_block = start\_block # Scan in chunks, commit between chunk\_size = start\_chunk\_size last\_scan\_duration = last\_logs\_found = 0 total\_chunks\_scanned = 0 # All processed entries we got on this scan cycle all\_processed = \[\] while current\_block <= end\_block: self.state.start\_chunk(current\_block, chunk\_size) # Print some diagnostics to logs to try to fiddle with real world JSON-RPC API performance estimated\_end\_block = min(current\_block + chunk\_size, end\_block) logger.debug( f"Scanning token transfers for blocks: {current\_block} - {estimated\_end\_block}, chunk size {chunk\_size}, last chunk scan took {last\_scan\_duration}, last logs found {last\_logs\_found}" ) start = time.time() actual\_end\_block, end\_block\_timestamp, new\_entries = self.scan\_chunk(current\_block, estimated\_end\_block) # Where does our current chunk scan ends - are we out of chain yet? current\_end = actual\_end\_block last\_scan\_duration = time.time() - start all\_processed += new\_entries # Print progress bar if progress\_callback: progress\_callback(start\_block, end\_block, current\_block, end\_block\_timestamp, chunk\_size, len(new\_entries)) # Try to guess how many blocks to fetch over \`eth\_getLogs\` API next time chunk\_size = self.estimate\_next\_chunk\_size(chunk\_size, len(new\_entries)) # Set where the next chunk starts current\_block = current\_end + 1 total\_chunks\_scanned += 1 self.state.end\_chunk(current\_end) return all\_processed, total\_chunks\_scanned def \_retry\_web3\_call(func, start\_block, end\_block, retries, delay) -> Tuple\[int, list\]: """A custom retry loop to throttle down block range. If our JSON-RPC server cannot serve all incoming \`eth\_getLogs\` in a single request, we retry and throttle down block range for every retry. For example, Go Ethereum does not indicate what is an acceptable response size. It just fails on the server-side with a "context was cancelled" warning. :param func: A callable that triggers Ethereum JSON-RPC, as func(start\_block, end\_block) :param start\_block: The initial start block of the block range :param end\_block: The initial start block of the block range :param retries: How many times we retry :param delay: Time to sleep between retries """ for i in range(retries): try: return end\_block, func(start\_block, end\_block) except Exception as e: # Assume this is HTTPConnectionPool(host='localhost', port=8545): Read timed out. (read timeout=10) # from Go Ethereum. This translates to the error "context was cancelled" on the server side: # https://github.com/ethereum/go-ethereum/issues/20426 if i < retries - 1: # Give some more verbose info than the default middleware logger.warning( f"Retrying events for block range {start\_block} - {end\_block} ({end\_block-start\_block}) failed with {e} , retrying in {delay} seconds") # Decrease the \`eth\_getBlocks\` range end\_block = start\_block + ((end\_block - start\_block) // 2) # Let the JSON-RPC to recover e.g. from restart time.sleep(delay) continue else: logger.warning("Out of retries") raise def \_fetch\_events\_for\_all\_contracts( w3, event, argument\_filters: Dict\[str, Any\], from\_block: int, to\_block: int) -> Iterable: """Get events using eth\_getLogs API. This method is detached from any contract instance. This is a stateless method, as opposed to create\_filter. It can be safely called against nodes which do not provide \`eth\_newFilter\` API, like Infura. """ if from\_block is None: raise Web3TypeError("Missing mandatory keyword argument to get\_logs: from\_block") # Currently no way to poke this using a public web3.py API. # This will return raw underlying ABI JSON object for the event abi = event.\_get\_event\_abi() # Depending on the Solidity version used to compile # the contract that uses the ABI, # it might have Solidity ABI encoding v1 or v2. # We just assume the default that you set on Web3 object here. # More information here https://eth-abi.readthedocs.io/en/latest/index.html codec: ABICodec = w3.codec # Here we need to poke a bit into Web3 internals, as this # functionality is not exposed by default. # Construct JSON-RPC raw filter presentation based on human readable Python descriptions # Namely, convert event names to their keccak signatures # More information here: # https://github.com/ethereum/web3.py/blob/e176ce0793dafdd0573acc8d4b76425b6eb604ca/web3/\_utils/filters.py#L71 data\_filter\_set, event\_filter\_params = construct\_event\_filter\_params( abi, codec, address=argument\_filters.get("address"), argument\_filters=argument\_filters, from\_block=from\_block, to\_block=to\_block ) logger.debug(f"Querying eth\_getLogs with the following parameters: {event\_filter\_params}") # Call JSON-RPC API on your Ethereum node. # get\_logs() returns raw AttributedDict entries logs = w3.eth.get\_logs(event\_filter\_params) # Convert raw binary data to Python proxy objects as described by ABI all\_events = \[\] for log in logs: # Convert raw JSON-RPC log result to human readable event by using ABI data # More information how process\_log works here # https://github.com/ethereum/web3.py/blob/fbaf1ad11b0c7fac09ba34baff2c256cffe0a148/web3/\_utils/events.py#L200 evt = get\_event\_data(codec, abi, log) # Note: This was originally yield, # but deferring the timeout exception caused the throttle logic not to work all\_events.append(evt) return all\_events if \_\_name\_\_ == "\_\_main\_\_": # Simple demo that scans all the token transfers of RCC token (11k). # The demo supports persistent state by using a JSON file. # You will need an Ethereum node for this. # Running this script will consume around 20k JSON-RPC calls. # With locally running Geth, the script takes 10 minutes. # The resulting JSON state file is 2.9 MB. import sys import json from web3.providers.rpc import HTTPProvider # We use tqdm library to render a nice progress bar in the console # https://pypi.org/project/tqdm/ from tqdm import tqdm # RCC has around 11k Transfer events # https://etherscan.io/token/0x9b6443b0fb9c241a7fdac375595cea13e6b7807a RCC\_ADDRESS = "0x9b6443b0fb9c241a7fdac375595cea13e6b7807a" # Reduced ERC-20 ABI, only Transfer event ABI = """\[ { "anonymous": false, "inputs": \[ { "indexed": true, "name": "from", "type": "address" }, { "indexed": true, "name": "to", "type": "address" }, { "indexed": false, "name": "value", "type": "uint256" } \], "name": "Transfer", "type": "event" } \] """ class JSONifiedState(EventScannerState): """Store the state of scanned blocks and all events. All state is an in-memory dict. Simple load/store massive JSON on start up. """ def \_\_init\_\_(self): self.state = None self.fname = "test-state.json" # How many second ago we saved the JSON file self.last\_save = 0 def reset(self): """Create initial state of nothing scanned.""" self.state = { "last\_scanned\_block": 0, "blocks": {}, } def restore(self): """Restore the last scan state from a file.""" try: self.state = json.load(open(self.fname, "rt")) print(f"Restored the state, previously {self.state\['last\_scanned\_block'\]} blocks have been scanned") except (IOError, json.decoder.JSONDecodeError): print("State starting from scratch") self.reset() def save(self): """Save everything we have scanned so far in a file.""" with open(self.fname, "wt") as f: json.dump(self.state, f) self.last\_save = time.time() # # EventScannerState methods implemented below # def get\_last\_scanned\_block(self): """The number of the last block we have stored.""" return self.state\["last\_scanned\_block"\] def delete\_data(self, since\_block): """Remove potentially reorganised blocks from the scan data.""" for block\_num in range(since\_block, self.get\_last\_scanned\_block()): if block\_num in self.state\["blocks"\]: del self.state\["blocks"\]\[block\_num\] def start\_chunk(self, block\_number, chunk\_size): pass def end\_chunk(self, block\_number): """Save at the end of each block, so we can resume in the case of a crash or CTRL+C""" # Next time the scanner is started we will resume from this block self.state\["last\_scanned\_block"\] = block\_number # Save the database file for every minute if time.time() - self.last\_save > 60: self.save() def process\_event(self, block\_when: datetime.datetime, event: AttributeDict) -> str: """Record a ERC-20 transfer in our database.""" # Events are keyed by their transaction hash and log index # One transaction may contain multiple events # and each one of those gets their own log index # event\_name = event.event # "Transfer" log\_index = event.logIndex # Log index within the block # transaction\_index = event.transactionIndex # Transaction index within the block txhash = event.transactionHash.hex() # Transaction hash block\_number = event.blockNumber # Convert ERC-20 Transfer event to our internal format args = event\["args"\] transfer = { "from": args\["from"\], "to": args.to, "value": args.value, "timestamp": block\_when.isoformat(), } # Create empty dict as the block that contains all transactions by txhash if block\_number not in self.state\["blocks"\]: self.state\["blocks"\]\[block\_number\] = {} block = self.state\["blocks"\]\[block\_number\] if txhash not in block: # We have not yet recorded any transfers in this transaction # (One transaction may contain multiple events if executed by a smart contract). # Create a tx entry that contains all events by a log index self.state\["blocks"\]\[block\_number\]\[txhash\] = {} # Record ERC-20 transfer in our database self.state\["blocks"\]\[block\_number\]\[txhash\]\[log\_index\] = transfer # Return a pointer that allows us to look up this event later if needed return f"{block\_number}-{txhash}-{log\_index}" 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") else: formatted\_time = "no block time available" progress\_bar.set\_description(f"Current block: {current} ({formatted\_time}), blocks in a scan batch: {chunk\_size}, events processed in a batch {events\_count}") progress\_bar.update(chunk\_size) # Run the scan result, total\_chunks\_scanned = scanner.scan(start\_block, end\_block, progress\_callback=\_update\_progress) state.save() duration = time.time() - start print(f"Scanned total {len(result)} Transfer events, in {duration} seconds, total {total\_chunks\_scanned} chunk scans performed") run() .. \_WETH: https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code .. \_asyncio: https://docs.python.org/3/library/asyncio.html .. \_gevent: https://www.gevent.org/ .. \_twisted: https://twistedmatrix.com/ .. \_celery: https://www.celeryproject.org/ --- # Unknown Net API ======= .. py:module:: web3.net The \`\`web3.net\`\` object exposes methods to interact with the RPC APIs under the \`\`net\_\`\` namespace. Properties ---------- The following properties are available on the \`\`web3.net\`\` namespace. .. py:method:: listening ..py:property:: \* Delegates to \`\`net\_listening\`\` RPC method Returns true if client is actively listening for network connections. .. code-block:: python >>> web3.net.listening True .. py:method:: peer\_count ..py:property:: \* Delegates to \`\`net\_peerCount\`\` RPC method Returns number of peers currently connected to the client. .. code-block:: python >>> web3.net.peer\_count 1 .. py:method:: version ..py:property:: \* Delegates to \`\`net\_version\`\` RPC Method Returns the current network id. .. code-block:: python >>> web3.net.version '8996' --- # Unknown Tracing API =========== .. py:module:: web3.tracing The \`\`web3.tracing\`\` object exposes modules that enable you to interact with the JSON-RPC \`\`trace\_\`\` endpoints supported by Erigon and Nethermind. The following methods are available on the \`\`web3.tracing\`\` namespace: .. py:method:: trace\_replay\_transaction .. py:method:: trace\_replay\_block\_transactions .. py:method:: trace\_filter .. py:method:: trace\_block .. py:method:: trace\_transaction .. py:method:: trace\_call .. py:method:: trace\_raw\_transaction --- # Unknown .. \_Gas\_Price: Gas Price API =============== .. warning:: Gas price strategy is only supported for legacy transactions. The London fork introduced \`\`maxFeePerGas\`\` and \`\`maxPriorityFeePerGas\`\` transaction parameters which should be used over \`\`gasPrice\`\` whenever possible. For Ethereum (legacy) transactions, gas price is a delicate property. For this reason, Web3 includes an API for configuring it. The Gas Price API allows you to define Web3's behaviour for populating the gas price. This is done using a "Gas Price Strategy" - a method which takes the Web3 object and a transaction dictionary and returns a gas price (denominated in wei). Retrieving gas price -------------------- To retrieve the gas price using the selected strategy simply call :meth:\`~web3.eth.Eth.generate\_gas\_price\` .. code-block:: python >>> web3.eth.generate\_gas\_price() 20000000000 Creating a gas price strategy ------------------------------- A gas price strategy is implemented as a python method with the following signature: .. code-block:: python def gas\_price\_strategy(web3, transaction\_params=None): ... The method must return a positive integer representing the gas price in wei. To demonstrate, here is a rudimentary example of a gas price strategy that returns a higher gas price when the value of the transaction is higher than 1 Ether. .. code-block:: python from web3 import Web3 def value\_based\_gas\_price\_strategy(web3, transaction\_params): if transaction\_params\['value'\] > Web3.to\_wei(1, 'ether'): return Web3.to\_wei(20, 'gwei') else: return Web3.to\_wei(5, 'gwei') Selecting the gas price strategy -------------------------------- The gas price strategy can be set by calling :meth:\`~web3.eth.Eth.set\_gas\_price\_strategy\`. .. code-block:: python from web3 import Web3 def value\_based\_gas\_price\_strategy(web3, transaction\_params): ... w3 = Web3(...) w3.eth.set\_gas\_price\_strategy(value\_based\_gas\_price\_strategy) Available gas price strategies ------------------------------ .. py:module:: web3.gas\_strategies.rpc .. py:method:: rpc\_gas\_price\_strategy(web3, transaction\_params=None) Makes a call to the \`JSON-RPC eth\_gasPrice method \`\_ which returns the gas price configured by the connected Ethereum node. .. py:module:: web3.gas\_strategies.time\_based .. py:method:: construct\_time\_based\_gas\_price\_strategy(max\_wait\_seconds, sample\_size=120, probability=98, weighted=False) Constructs a strategy which will compute a gas price such that the transaction will be mined within a number of seconds defined by \`\`max\_wait\_seconds\`\` with a probability defined by \`\`probability\`\`. The gas price is computed by sampling \`\`sample\_size\`\` of the most recently mined blocks. If \`\`weighted=True\`\`, the block time will be weighted towards more recently mined blocks. \* \`\`max\_wait\_seconds\`\` The desired maximum number of seconds the transaction should take to mine. \* \`\`sample\_size\`\` The number of recent blocks to sample \* \`\`probability\`\` An integer representation of the desired probability that the transaction will be mined within \`\`max\_wait\_seconds\`\`. 0 means 0% and 100 means 100%. The following ready to use versions of this strategy are available. \* \`\`web3.gas\_strategies.time\_based.fast\_gas\_price\_strategy\`\`: Transaction mined within 60 seconds. \* \`\`web3.gas\_strategies.time\_based.medium\_gas\_price\_strategy\`\`: Transaction mined within 5 minutes. \* \`\`web3.gas\_strategies.time\_based.slow\_gas\_price\_strategy\`\`: Transaction mined within 1 hour. \* \`\`web3.gas\_strategies.time\_based.glacial\_gas\_price\_strategy\`\`: Transaction mined within 24 hours. .. warning:: Due to the overhead of sampling the recent blocks it is recommended that a caching solution be used to reduce the amount of chain data that needs to be re-fetched for each request. .. code-block:: python from web3 import Web3 from web3.gas\_strategies.time\_based import medium\_gas\_price\_strategy w3 = Web3(...) w3.eth.set\_gas\_price\_strategy(medium\_gas\_price\_strategy) w3.provider.cache\_allowed\_requests = True --- # Unknown .. \_constants: Constants ========= The web3.constants module contains commonly used values. Strings \*\*\*\*\*\*\* .. code-block:: python #The Address Zero, which is 20 bytes (40 nibbles) of zero. web3.constants.ADDRESS\_ZERO #The hexadecimal version of Max uint256. web3.constants.MAX\_INT #The Hash Zero, which is 32 bytes (64 nibbles) of zero. web3.constants.HASH\_ZERO Int \*\*\* .. code-block:: python #The amount of Wei in one Ether web3.constants.WEI\_PER\_ETHER --- # Unknown Geth API ======== .. py:module:: web3.geth The \`\`web3.geth\`\` object exposes modules that enable you to interact with the JSON-RPC endpoints supported by \`Geth \`\_ that are not defined in the standard set of Ethereum JSONRPC endpoints according to \`EIP 1474 \`\_. GethAdmin API ~~~~~~~~~~~~~ The following methods are available on the \`\`web3.geth.admin\`\` namespace. .. py:module:: web3.geth.admin The \`\`web3.geth.admin\`\` object exposes methods to interact with the RPC APIs under the \`\`admin\_\`\` namespace that are supported by the Geth client. .. py:method:: datadir() \* Delegates to \`\`admin\_datadir\`\` RPC Method Returns the system path of the node's data directory. .. code-block:: python >>> web3.geth.admin.datadir() '/Users/snakecharmers/Library/Ethereum' .. py:method:: node\_info() \* Delegates to \`\`admin\_nodeInfo\`\` RPC Method Returns information about the currently running node. .. code-block:: python >>> web3.geth.admin.node\_info() { 'enode': 'enode://e54eebad24dce1f6d246bea455ffa756d97801582420b9ed681a2ea84bf376d0bd87ae8dd6dc06cdb862a2ca89ecabe1be1050be35b4e70d62bc1a092cb7e2d3@\[::\]:30303', 'id': 'e54eebad24dce1f6d246bea455ffa756d97801582420b9ed681a2ea84bf376d0bd87ae8dd6dc06cdb862a2ca89ecabe1be1050be35b4e70d62bc1a092cb7e2d3', 'ip': '::', 'listenAddr': '\[::\]:30303', 'name': 'Geth/v1.4.11-stable-fed692f6/darwin/go1.7', 'ports': {'discovery': 30303, 'listener': 30303}, 'protocols': { 'eth': { 'difficulty': 57631175724744612603, 'genesis': '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3', 'head': '0xaaef6b9dd0d34088915f4c62b6c166379da2ad250a88f76955508f7cc81fb796', 'network': 1, }, }, } .. py:method:: peers() \* Delegates to \`\`admin\_peers\`\` RPC Method Returns the current peers the node is connected to. .. code-block:: python >>> web3.geth.admin.peers() \[ { 'caps': \['eth/63'\], 'id': '146e8e3e2460f1e18939a5da37c4a79f149c8b9837240d49c7d94c122f30064e07e4a42ae2c2992d0f8e7e6f68a30e7e9ad31d524349ec9d17effd2426a37b40', 'name': 'Geth/v1.4.10-stable/windows/go1.6.2', 'network': { 'localAddress': '10.0.3.115:64478', 'remoteAddress': '72.208.167.127:30303', }, 'protocols': { 'eth': { 'difficulty': 17179869184, 'head': '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3', 'version': 63, }, } }, { 'caps': \['eth/62', 'eth/63'\], 'id': '76cb6cd3354be081923a90dfd4cda40aa78b307cc3cf4d5733dc32cc171d00f7c08356e9eb2ea47eab5aad7a15a3419b859139e3f762e1e1ebf5a04f530dcef7', 'name': 'Geth/v1.4.10-stable-5f55d95a/linux/go1.5.1', 'network': { 'localAddress': '10.0.3.115:64784', 'remoteAddress': '60.205.92.119:30303', }, 'protocols': { 'eth': { 'difficulty': 57631175724744612603, 'head': '0xaaef6b9dd0d34088915f4c62b6c166379da2ad250a88f76955508f7cc81fb796', 'version': 63, }, }, }, ... \] .. py:method:: add\_peer(node\_url) \* Delegates to \`\`admin\_addPeer\`\` RPC Method Requests adding a new remote node to the list of tracked static nodes. .. code-block:: python >>> web3.geth.admin.add\_peer('enode://e54eebad24dce1f6d246bea455ffa756d97801582420b9ed681a2ea84bf376d0bd87ae8dd6dc06cdb862a2ca89ecabe1be1050be35b4e70d62bc1a092cb7e2d3@52.71.255.237:30303') True .. py:method:: start\_http(host='localhost', port=8545, cors="", apis="eth,net,web3") \* 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. .. code-block:: python >>> web3.geth.admin.start\_http() True .. py:method:: start\_ws(host='localhost', port=8546, cors="", apis="eth,net,web3") \* 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. .. code-block:: python >>> web3.geth.admin.start\_ws() True .. py:method:: stop\_http() \* Delegates to \`\`admin\_stopHTTP\`\` RPC Method Stops the HTTP based JSON RPC server. .. code-block:: python >>> web3.geth.admin.stop\_http() True .. py:method:: stop\_ws() \* Delegates to \`\`admin\_stopWS\`\` RPC Method Stops the WebSocket based JSON RPC server. .. code-block:: python >>> web3.geth.admin.stop\_ws() True .. py:module:: web3.geth.txpool GethTxPool API ~~~~~~~~~~~~~~ The \`\`web3.geth.txpool\`\` object exposes methods to interact with the RPC APIs under the \`\`txpool\_\`\` namespace. These methods are only exposed under the \`\`geth\`\` namespace since they are not standard. The following methods are available on the \`\`web3.geth.txpool\`\` namespace. .. py:method:: TxPool.inspect() \* Delegates to \`\`txpool\_inspect\`\` RPC Method Returns a textual summary of all transactions currently pending for inclusion in the next block(s) as well as ones that are scheduled for future execution. .. code-block:: python >>> web3.geth.txpool.inspect() { 'pending': { '0x26588a9301b0428d95e6Fc3A5024fcE8BEc12D51': { 31813: \["0x3375Ee30428b2A71c428afa5E89e427905F95F7e: 0 wei + 500000 × 20000000000 gas"\] }, '0x2a65Aca4D5fC5B5C859090a6c34d164135398226': { 563662: \["0x958c1Fa64B34db746925c6F8a3Dd81128e40355E: 1051546810000000000 wei + 90000 × 20000000000 gas"\], 563663: \["0x77517B1491a0299A44d668473411676f94e97E34: 1051190740000000000 wei + 90000 × 20000000000 gas"\], 563664: \["0x3E2A7Fe169c8F8eee251BB00d9fb6d304cE07d3A: 1050828950000000000 wei + 90000 × 20000000000 gas"\], 563665: \["0xAF6c4695da477F8C663eA2D8B768Ad82Cb6A8522: 1050544770000000000 wei + 90000 × 20000000000 gas"\], 563666: \["0x139B148094C50F4d20b01cAf21B85eDb711574dB: 1048598530000000000 wei + 90000 × 20000000000 gas"\], 563667: \["0x48B3Bd66770b0D1EeceFCe090daFeE36257538aE: 1048367260000000000 wei + 90000 × 20000000000 gas"\], 563668: \["0x468569500925D53e06Dd0993014aD166fD7Dd381: 1048126690000000000 wei + 90000 × 20000000000 gas"\], 563669: \["0x3DcB4C90477a4b8Ff7190b79b524773CbE3bE661: 1047965690000000000 wei + 90000 × 20000000000 gas"\], 563670: \["0x6DfeF5BC94b031407FFe71ae8076CA0FbF190963: 1047859050000000000 wei + 90000 × 20000000000 gas"\] }, '0x9174E688d7dE157C5C0583Df424EAAB2676aC162': { 3: \["0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413: 30000000000000000000 wei + 85000 × 21000000000 gas"\] }, '0xb18F9d01323e150096650ab989CfecD39D757Aec': { 777: \["0xcD79c72690750F079ae6AB6ccd7e7aEDC03c7720: 0 wei + 1000000 × 20000000000 gas"\] }, '0xB2916C870Cf66967B6510B76c07E9d13a5D23514': { 2: \["0x576f25199D60982A8f31A8DfF4da8aCB982e6ABa: 26000000000000000000 wei + 90000 × 20000000000 gas"\] }, '0xBc0CA4f217E052753614d6B019948824d0d8688B': { 0: \["0x2910543Af39abA0Cd09dBb2D50200b3E800A63D2: 1000000000000000000 wei + 50000 × 1171602790622 gas"\] }, '0xea674fdde714fd979de3edf0f56aa9716b898ec8': { 70148: \["0xe39c55ead9f997f7fa20ebe40fb4649943d7db66: 1000767667434026200 wei + 90000 × 20000000000 gas"\] } }, 'queued': { '0x0F6000De1578619320aBA5e392706b131FB1dE6f': { 6: \["0x8383534d0bcd0186d326C993031311c0Ac0D9B2d: 9000000000000000000 wei + 21000 × 20000000000 gas"\] }, '0x5b30608c678e1ac464A8994C3B33E5CdF3497112': { 6: \["0x9773547e27f8303C87089dc42D9288aa2B9d8F06: 50000000000000000000 wei + 90000 × 50000000000 gas"\] }, '0x976A3Fc5d6f7d259EBfb4cc2Ae75115475E9867C': { 3: \["0x346FB27dE7E7370008f5da379f74dd49F5f2F80F: 140000000000000000 wei + 90000 × 20000000000 gas"\] }, '0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A': { 2: \["0x24a461f25eE6a318BDef7F33De634A67bb67Ac9D: 17000000000000000000 wei + 90000 × 50000000000 gas"\], 6: \["0x6368f3f8c2B42435D6C136757382E4A59436a681: 17990000000000000000 wei + 90000 × 20000000000 gas", "0x8db7b4e0ecb095fbd01dffa62010801296a9ac78: 16998950000000000000 wei + 90000 × 20000000000 gas"\], 7: \["0x6368f3f8c2B42435D6C136757382E4A59436a681: 17900000000000000000 wei + 90000 × 20000000000 gas"\] } } } .. py:method:: TxPool.status() \* Delegates to \`\`txpool\_status\`\` RPC Method Returns a textual summary of all transactions currently pending for inclusion in the next block(s) as well as ones that are scheduled for future execution. .. code-block:: python { pending: 10, queued: 7, } .. py:method:: TxPool.content() \* Delegates to \`\`txpool\_content\`\` RPC Method Returns the exact details of all transactions that are pending or queued. .. code-block:: python >>> web3.geth.txpool.content() { 'pending': { '0x0216D5032f356960Cd3749C31Ab34eEFF21B3395': { 806: \[{ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000", 'blockNumber': None, 'from': "0x0216D5032f356960Cd3749C31Ab34eEFF21B3395", 'gas': "0x5208", 'gasPrice': None, 'hash': "0xaf953a2d01f55cfe080c0c94150a60105e8ac3d51153058a1f03dd239dd08586", 'input': "0x", 'maxFeePerGas': '0x77359400', 'maxPriorityFeePerGas': '0x3b9aca00', 'nonce': "0x326", 'to': "0x7f69a91A3CF4bE60020fB58B893b7cbb65376db8", 'transactionIndex': None, 'value': "0x19a99f0cf456000" }\] }, '0x24d407e5A0B506E1Cb2fae163100B5DE01F5193C': { 34: \[{ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000", 'blockNumber': None, 'from': "0x24d407e5A0B506E1Cb2fae163100B5DE01F5193C", 'gas': "0x44c72", 'gasPrice': None, 'hash': "0xb5b8b853af32226755a65ba0602f7ed0e8be2211516153b75e9ed640a7d359fe", 'input': "0xb61d27f600000000000000000000000024d407e5a0b506e1cb2fae163100b5de01f5193c00000000000000000000000000000000000000000000000053444835ec580000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 'maxFeePerGas': '0x77359400', 'maxPriorityFeePerGas': '0x3b9aca00', 'nonce': "0x22", 'to': "0x7320785200f74861B69C49e4ab32399a71b34f1a", 'transactionIndex': None, 'value': "0x0" }\] } }, 'queued': { '0x976A3Fc5d6f7d259EBfb4cc2Ae75115475E9867C': { 3: \[{ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000", 'blockNumber': None, 'from': "0x976A3Fc5d6f7d259EBfb4cc2Ae75115475E9867C", 'gas': "0x15f90", 'gasPrice': None, 'hash': "0x57b30c59fc39a50e1cba90e3099286dfa5aaf60294a629240b5bbec6e2e66576", 'input': "0x", 'maxFeePerGas': '0x77359400', 'maxPriorityFeePerGas': '0x3b9aca00', 'nonce': "0x3", 'to': "0x346FB27dE7E7370008f5da379f74dd49F5f2F80F", 'transactionIndex': None, 'value': "0x1f161421c8e0000" }\] }, '0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A': { 2: \[{ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000", 'blockNumber': None, 'from': "0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A", 'gas': "0x15f90", 'gasPrice': None, 'hash': "0x3a3c0698552eec2455ed3190eac3996feccc806970a4a056106deaf6ceb1e5e3", 'input': "0x", 'maxFeePerGas': '0x77359400', 'maxPriorityFeePerGas': '0x3b9aca00', 'nonce': "0x2", 'to': "0x24a461f25eE6a318BDef7F33De634A67bb67Ac9D", 'transactionIndex': None, 'value': "0xebec21ee1da40000" }\], 6: \[{ 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000", 'blockNumber': None, 'from': "0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A", 'gas': "0x15f90", 'gasPrice': None, 'hash': "0xbbcd1e45eae3b859203a04be7d6e1d7b03b222ec1d66dfcc8011dd39794b147e", 'input': "0x", 'maxFeePerGas': '0x77359400', 'maxPriorityFeePerGas': '0x3b9aca00', 'nonce': "0x6", 'to': "0x6368f3f8c2B42435D6C136757382E4A59436a681", 'transactionIndex': None, 'value': "0xf9a951af55470000" }, { 'blockHash': "0x0000000000000000000000000000000000000000000000000000000000000000", 'blockNumber': None, 'from': "0x9B11bF0459b0c4b2f87f8CEBca4cfc26f294B63A", 'gas': "0x15f90", 'gasPrice': None, 'hash': "0x60803251d43f072904dc3a2d6a084701cd35b4985790baaf8a8f76696041b272", 'input': "0x", 'maxFeePerGas': '0x77359400', 'maxPriorityFeePerGas': '0x3b9aca00', 'nonce': "0x6", 'to': "0x8DB7b4e0ECB095FBD01Dffa62010801296a9ac78", 'transactionIndex': None, 'value': "0xebe866f5f0a06000" }\], } } } .. py:module:: web3.geth.debug GethDebug API ~~~~~~~~~~~~~~ The \`\`web3.geth.debug\`\` object exposes methods to interact with the RPC APIs under the \`\`debug\_\`\` namespace. These methods are only exposed under the \`\`geth\`\` namespace. Full documentation around options can be found in the \`Geth docs \`\_. .. py:method:: Debug.trace\_transaction(transaction\_hash) \* Delegates to \`\`debug\_traceTransaction\`\` RPC Method Returns the trace of the transaction with the given \`\`transaction\_hash\`\` and \`\`trace\_config\`\`. .. code-block:: python >>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3') AttributeDict({ 'gas': 21000, 'failed': False, 'returnValue': '', 'structLogs': \[\] }) >>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3', { "tracer": "prestateTracer", }) AttributeDict({ '0x0000000000000000000000000000000000000000': AttributeDict({'balance': 0}), '0x7fE3e4C21bDE162214B715AabcE05391301e9F5B': AttributeDict({'balance': 115792089237316195423570985008687907853269984665640564039457584007913129639927}), '0x91fe3039271d43d3f8479f60Cc5293Bc8A461b75': AttributeDict({'balance': 0}) }) >>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3', { "tracer": "prestateTracer", "traceConfig": {"diffMode": True} }) AttributeDict({ 'post': AttributeDict({ '0x0000000000000000000000000000000000000000': AttributeDict({'balance': 63000}), '0xcF888Cc4FAe8a3D774e574Ef8C6a261958287d04': AttributeDict({ 'balance': 115792089237316195423570985008687907853269984665640564039457583959368602105927, 'nonce': 3 }), '0xD2593D3445a9F0f4c776715f5206FBf4CA6A0475': AttributeDict({'balance': 100000})}), 'pre': AttributeDict({ '0x0000000000000000000000000000000000000000': AttributeDict({'balance': 42000}), '0xcF888Cc4FAe8a3D774e574Ef8C6a261958287d04': AttributeDict({ 'balance': 115792089237316195423570985008687907853269984665640564039457583973451623990927, 'nonce': 2 }), '0xD2593D3445a9F0f4c776715f5206FBf4CA6A0475': AttributeDict({'balance': 0}) }) }) >>> web3.geth.debug.trace\_transaction('0x96014f00980a25dc7275a5eb5ed25ce0dd79c9233628c421ae373601236949b3', { "tracer": "callTracer", "tracerConfig": {"withLog": False}, }) AttributeDict({'calls': \[AttributeDict({'from': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11', 'gas': 154003, 'gasUsed': 275, 'input': HexBytes('0xad5c4648'), 'output': HexBytes('0x000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'), 'to': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'type': 'STATICCALL'}), AttributeDict({'from': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11', 'gas': 150633, 'gasUsed': 24678, 'input': HexBytes('0x095ea7b30000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d000000000000000000000000000000000000007e37be2022c0914b2680000000'), 'output': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001'), 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B', 'type': 'CALL', 'value': 0}), AttributeDict({'calls': \[AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'gas': 121167, 'gasUsed': 27504, 'input': HexBytes('0x23b872dd000000000000000000000000a0457775a08b175cbb444ed923556dc67ec5dc1100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d000000000000000000000000000000000000007e37be2022c0914b2680000000'), 'output': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001'), 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B', 'type': 'CALL', 'value': 0}), AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'gas': 89911, 'gasUsed': 2504, 'input': HexBytes('0x0902f1ac'), 'output': HexBytes('0x00000000000000000000000000000000000000000000000053f54ccde429ceb70000000000000000000000000000000000000000001635eb93ecdb339a7dc022000000000000000000000000000000000000000000000000000000006641f6cf'), 'to': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d', 'type': 'STATICCALL'}), AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'gas': 86926, 'gasUsed': 621, 'input': HexBytes('0x70a0823100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d'), 'output': HexBytes('0x000000000000000000000000000000000000007e37d4560e547e265a1a7dc022'), 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B', 'type': 'STATICCALL'}), AttributeDict({'calls': \[AttributeDict({'from': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d', 'gas': 70279, 'gasUsed': 29962, 'input': HexBytes('0xa9059cbb0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d00000000000000000000000000000000000000000000000053f53dfc545d56a6'), 'output': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001'), 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'type': 'CALL', 'value': 0}), AttributeDict({'from': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d', 'gas': 40164, 'gasUsed': 534, 'input': HexBytes('0x70a0823100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d'), 'output': HexBytes('0x00000000000000000000000000000000000000000000000000000ed18fcc7811'), 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'type': 'STATICCALL'}), AttributeDict({'from': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d', 'gas': 39233, 'gasUsed': 621, 'input': HexBytes('0x70a0823100000000000000000000000036f0548a77bfb1d5935483d25cc40633b46e2f4d'), 'output': HexBytes('0x000000000000000000000000000000000000007e37d4560e547e265a1a7dc022'), 'to': '0xec4cF8dCB526080792bC98E1Ef41fB4775777b6B', 'type': 'STATICCALL'})\], 'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'gas': 84769, 'gasUsed': 64940, 'input': HexBytes('0x022c0d9f00000000000000000000000000000000000000000000000053f53dfc545d56a600000000000000000000000000000000000000000000000000000000000000000000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d00000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000'), 'to': '0x36f0548a77BFb1d5935483D25cc40633b46e2f4d', 'type': 'CALL', 'value': 0}), AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'gas': 20382, 'gasUsed': 534, 'input': HexBytes('0x70a082310000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d'), 'output': HexBytes('0x00000000000000000000000000000000000000000000000053f53dfc545d56a6'), 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'type': 'STATICCALL'}), AttributeDict({'calls': \[AttributeDict({'from': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'gas': 2300, 'gasUsed': 83, 'input': HexBytes('0x'), 'to': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'type': 'CALL', 'value': 6049809828398585510})\], 'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'gas': 19432, 'gasUsed': 9223, 'input': HexBytes('0x2e1a7d4d00000000000000000000000000000000000000000000000053f53dfc545d56a6'), 'to': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'type': 'CALL', 'value': 0}), AttributeDict({'from': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'gas': 3353, 'gasUsed': 0, 'input': HexBytes('0x'), 'to': '0xE11418f9961248da36b1008b1090235f680AE8f5', 'type': 'CALL', 'value': 6049809828398585510})\], 'from': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11', 'gas': 125270, 'gasUsed': 122013, 'input': HexBytes('0x791ac947000000000000000000000000000000000000007e37be2022c0914b2680000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000e11418f9961248da36b1008b1090235f680ae8f5000000000000000000000000000000000000000000000000000000006641fe7f0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000ec4cf8dcb526080792bc98e1ef41fb4775777b6b000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'), 'to': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', 'type': 'CALL', 'value': 0})\], 'from': '0xE11418f9961248da36b1008b1090235f680AE8f5', 'gas': 185574, 'gasUsed': 144300, 'input': HexBytes('0x56feb11b000000000000000000000000ec4cf8dcb526080792bc98e1ef41fb4775777b6b000000000000000000000000000000000000007e37be2022c0914b2680000000'), 'to': '0xa0457775a08b175Cbb444eD923556Dc67Ec5Dc11', 'type': 'CALL', 'value': 0}) >>> w3.geth.debug.trace\_transaction(tx\_hash, {'tracer': '4byteTracer'}) --- # Unknown Utils ===== .. py:module:: web3.utils The \`\`utils\`\` module houses public utility functions and classes. ABI --- .. automodule:: web3.utils.abi :members: :undoc-members: :show-inheritance: Address ------- .. py:method:: utils.get\_create\_address(sender, nonce) Return the checksummed contract address generated by using the \`\`CREATE\`\` opcode by a sender address with a given nonce. .. py:method:: utils.get\_create2\_address(sender, salt, init\_code) Return the checksummed contract address generated by using the \`\`CREATE2\`\` opcode by a sender address with a given salt and contract bytecode. See \`EIP-1014 \`\_. Caching ------- .. py:class:: utils.SimpleCache The main cache class being used internally by web3.py. In some cases, it may prove useful to set your own cache size and pass in your own instance of this class where supported. Exception Handling ------------------ .. py:method:: utils.handle\_offchain\_lookup(offchain\_lookup\_payload, transaction) Handle \`\`OffchainLookup\`\` reverts on contract function calls manually. For an example, see :ref:\`ccip-read-example\` within the examples section. .. py:method:: utils.async\_handle\_offchain\_lookup(offchain\_lookup\_payload, transaction) The async version of the \`\`handle\_offchain\_lookup()\`\` utility method described above. --- # Unknown .. \_resources: Resources and Learning Material =============================== web3.py and the Ethereum Python ecosystem have an active community of developers and educators. Here you'll find libraries, tutorials, examples, courses and other learning material. .. warning :: Links on this page are community submissions and are not vetted by the team that maintains web3.py. As always, DYOR (Do Your Own Research). First Steps ----------- Resources for those brand new to Ethereum: - \`A Developer's Guide to Ethereum, Pt. 1 \`\_\_ - \`Ethereum Python Ecosystem Tour \`\_\_ Courses ------- - \`freeCodeCamp Solidity and Python Course (2022) \`\_\_ - \`Blockchain Python Programming Tutorial (2019) \`\_\_ Tutorials --------- - Intro to \`Ape development framework \`\_\_ - Intro to \`websockets \`\_\_ and web3.py - Intro to \`asynchronous web3.py \`\_\_ - Intro to \`threaded web3.py \`\_\_ - Sign \`typed data messages \`\_\_ (EIP 712) - Look up offchain data via \`CCIP Read \`\_\_ - Configure and \`customize web3.py \`\_\_ - \`Decode a signed transaction \`\_\_ - Find a historical contract \`revert reason \`\_\_ - Generate a \`vanity address \`\_\_ - Similate transactions with \`call state overrides \`\_\_ - Configure web3 for \`JSON-RPC fallback and MEV blocker providers \`\_\_ Conference Presentations and Videos ----------------------------------- - \`Web3.Py - Now And Near Future by Marc Garreau (2022, 15 mins) \`\_\_ - \`Python and DeFi by Curve Finance (2022, 15 mins) \`\_\_ - \`Working with MetaMask in Python by Rishab Kattimani (2022, 15 mins) \`\_\_ Smart Contract Programming Languages ------------------------------------ - \`Vyper \`\_\_ - Contract-oriented, pythonic programming language that targets EVM Frameworks and Tooling ---------------------- - \`Ape \`\_\_ - The Ethereum development framework for Python Developers, Data Scientists, and Security Professionals - \`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 Libraries --------- - \`Web3 Ethereum DeFi \`\_\_ - Library for DeFi trading and protocols (Uniswap, PancakeSwap, Sushi, Aave, Chainlink) - \`lighter-v1-python \`\_\_ - Lighter.xyz DEX client for Python - \`uniswap-python \`\_\_ - Library lets you easily retrieve prices and make trades on all Uniswap versions. - \`pyWalletConnect \`\_\_ - WalletConnect implementation for wallets in Python - \`dydx-v3-python \`\_\_ - Python client for dYdX v3 - \`Lido Python SDK \`\_\_ - Library with which you can get all Lido validator's signatures and check their validity Applications ------------ - \`Curve Finance \`\_\_ - \`Yearn Finance \`\_\_ - \`StakeWise Oracle \`\_\_ Hackathon Helpers ----------------- - \`ape-hackathon-kit \`\_\_ - Ape project template with a web front-end (Next.js, Tailwind, RainbowKit, wagmi) - \`eth-flogger \`\_\_ - Sample web app utilizing async web3.py, Flask, SQLite, Sourcify - \`Temo \`\_\_ - Sample terminal app utilizing async web3py, Textual, Anvil - \`web3py-discord-bot \`\_\_ - Sample Discord bot utilizing websockets, \`\`eth\_subscribe\`\`, and discord.py - \`py-signer \`\_\_ - Demo of typed data message signing (EIP-712) with eth-account and Ape --- # Unknown Beacon API ========== .. warning:: This API Is experimental. Client support is incomplete and the API itself is still evolving. To use this API, you'll need a beacon node running locally or remotely. To set that up, refer to the documentation of your specific client. Once you have a running beacon node, import and configure your beacon instance: .. code-block:: python >>> from web3.beacon import Beacon >>> beacon = Beacon("http://localhost:5051") Methods ------- .. py:method:: Beacon.get\_genesis() .. code-block:: python >>> beacon.get\_genesis() { 'data': { 'genesis\_time': '1605700807', 'genesis\_validators\_root': '0x9436e8a630e3162b7ed4f449b12b8a5a368a4b95bc46b941ae65c11613bfa4c1', 'genesis\_fork\_version': '0x00002009' } } .. py:method:: Beacon.get\_hash\_root(state\_id="head") .. code-block:: python >>> beacon.get\_hash\_root() { "data": { "root":"0xbb399fda70617a6f198b3d9f1c1cdbd70077677231b84f34e58568c9dc903558" } } .. py:method:: Beacon.get\_fork\_data(state\_id="head") .. code-block:: python >>> beacon.get\_fork\_data() { 'data': { 'previous\_version': '0x00002009', 'current\_version': '0x00002009', 'epoch': '0' } } .. py:method:: Beacon.get\_finality\_checkpoint(state\_id="head") .. code-block:: python >>> beacon.get\_finality\_checkpoint() { 'data': { 'previous\_justified': { 'epoch': '5024', 'root': '0x499ba555e8e8be639dd84be1be6d54409738facefc662f37d97065aa91a1a8d4' }, 'current\_justified': { 'epoch': '5025', 'root': '0x34e8a230f11536ab2ec56a0956e1f3b3fd703861f96d4695877eaa48fbacc241' }, 'finalized': { 'epoch': '5024', 'root': '0x499ba555e8e8be639dd84be1be6d54409738facefc662f37d97065aa91a1a8d4' } } } .. py:method:: Beacon.get\_validators(state\_id="head") .. code-block:: python >>> beacon.get\_validators() { 'data': \[ { 'index': '110280', 'balance': '32000000000', 'status': 'pending\_queued', 'validator': { 'pubkey': '0x99d37d1f7dd15859995330f75c158346f86d298e2ffeedfbf1b38dcf3df89a7dbd1b34815f3bcd1b2a5588592a35b783', 'withdrawal\_credentials': '0x00f338cfdb0c22bb85beed9042bd19fff58ad6421c8a833f8bc902b7cca06f5f', 'effective\_balance': '32000000000', 'slashed': False, 'activation\_eligibility\_epoch': '5029', 'activation\_epoch': '18446744073709551615', 'exit\_epoch': '18446744073709551615', 'withdrawable\_epoch': '18446744073709551615' } }, ... \] } .. py:method:: Beacon.get\_validator(validator\_id, state\_id="head") .. code-block:: python >>> beacon.get\_validator(110280) { 'data': { 'index': '110280', 'balance': '32000000000', 'status': 'pending\_queued', 'validator': { 'pubkey': '0x99d37d1f7dd15859995330f75c158346f86d298e2ffeedfbf1b38dcf3df89a7dbd1b34815f3bcd1b2a5588592a35b783', 'withdrawal\_credentials': '0x00f338cfdb0c22bb85beed9042bd19fff58ad6421c8a833f8bc902b7cca06f5f', 'effective\_balance': '32000000000', 'slashed': False, 'activation\_eligibility\_epoch': '5029', 'activation\_epoch': '18446744073709551615', 'exit\_epoch': '18446744073709551615', 'withdrawable\_epoch': '18446744073709551615' } } } .. py:method:: Beacon.get\_validator\_balances(state\_id="head") .. code-block:: python >>> beacon.get\_validator\_balances() { 'data': \[ { 'index': '110278', 'balance': '32000000000' }, ... \] } .. py:method:: Beacon.get\_epoch\_committees(state\_id="head") .. code-block:: python >>> beacon.get\_epoch\_committees() { 'data': \[ { 'slot': '162367', 'index': '25', 'validators': \['50233', '36829', '84635', ...\], }, ... \] } .. py:method:: Beacon.get\_block\_headers() .. code-block:: python >>> beacon.get\_block\_headers() { 'data': \[ { 'root': '0xa3873e7b1e0bcc7c59013340cfea59dff16e42e79825e7b8ab6c243dbafd4fe0', 'canonical': True, 'header': { 'message': { 'slot': '163587', 'proposer\_index': '69198', 'parent\_root': '0xc32558881dbb791ef045c48e3709a0978dc445abee4ae34d30df600eb5fbbb3d', 'state\_root': '0x4dc0a72959803a84ee0231160b05dda76a91b8f8b77220b4cfc7db160840b8a8', 'body\_root': '0xa3873e7b1e0bcc7c59013340cfea59dff16e42e79825e7b8ab6c243dbafd4fe0' }, 'signature': '0x87b549448d36e5e8b1783944b5511a05f34bb78ad3fcbf71a1adb346eed363d46e50d51ac53cd23bd03d0107d064e05913a6ef10f465f9171aba3b2b8a7a4d621c9e18d5f148813295a2d5aa5053029ccbd88cec72130833de2b4b7addf7faca' } } \] } .. py:method:: Beacon.get\_block\_header(block\_id) .. code-block:: 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' } } } .. py:method:: Beacon.get\_block(block\_id) .. code-block:: python >>> beacon.get\_block(1) { 'data': { 'message': { 'slot': '1', 'proposer\_index': '61090', 'parent\_root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87', 'state\_root': '0x7773ed5a7e944c6238cd0a5c32170663ef2be9efc594fb43ad0f07ecf4c09d2b', 'body': { 'randao\_reveal': '0x8e245a52a0a680fcfe789013e123880c321f237de10cad108dc55dd47290d7cfe50cdaa003c6f783405efdac48cef44e152493abba40d9f9815a060dd6151cb0635906c9e3c1ad4859cada73ccd2d6b8747e4aeeada7d75d454bcc8672afa813', 'eth1\_data': { 'deposit\_root': '0x4e910ac762815c13e316e72506141f5b6b441d58af8e0a049cd3341c25728752', 'deposit\_count': '100596', 'block\_hash': '0x89cb78044843805fb4dab8abd743fc96c2b8e955c58f9b7224d468d85ef57130' }, 'graffiti': '0x74656b752f76302e31322e31342b34342d673863656562663600000000000000', 'proposer\_slashings': \[\], 'attester\_slashings': \[\], 'attestations': \[ { 'aggregation\_bits': '0x0080020004000000008208000102000905', 'data': { 'slot': '0', 'index': '7', 'beacon\_block\_root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87', 'source': { 'epoch': '0', 'root': '0x0000000000000000000000000000000000000000000000000000000000000000' }, 'target': { 'epoch': '0', 'root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87' } }, 'signature': '0x967dd2946358db7e426ed19d4576bc75123520ef6a489ca50002222070ee4611f9cef394e5e3071236a93b825f18a4ad07f1d5a1405e6c984f1d71e03f535d13a2156d6ba22cb0c2b148df23a7b8a7293315d6e74b9a26b64283e8393f2ad4c5' } \], 'deposits': \[\], 'voluntary\_exits': \[\] } }, 'signature': '0xa30d70b3e62ff776fe97f7f8b3472194af66849238a958880510e698ec3b8a470916680b1a82f9d4753c023153fbe6db10c464ac532c1c9c8919adb242b05ef7152ba3e6cd08b730eac2154b9802203ead6079c8dfb87f1e900595e6c00b4a9a' } } .. py:method:: Beacon.get\_block\_root(block\_id) .. code-block:: python >>> beacon.get\_block\_root(1) { 'data': { 'root': '0x30c04689dd4f6cd4d56eb78f72727d2d16d8b6346724e4a88f546875f11b750d' } } .. py:method:: Beacon.get\_block\_attestations(block\_id) .. code-block:: python >>> beacon.get\_block\_attestations(1) { 'data': \[ { 'aggregation\_bits': '0x0080020004000000008208000102000905', 'data': { 'slot': '0', 'index': '7', 'beacon\_block\_root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87', 'source': { 'epoch': '0', 'root': '0x0000000000000000000000000000000000000000000000000000000000000000' }, 'target': { 'epoch': '0', 'root': '0x6a89af5df908893eedbed10ba4c13fc13d5653ce57db637e3bfded73a987bb87' } }, 'signature': '0x967dd2946358db7e426ed19d4576bc75123520ef6a489ca50002222070ee4611f9cef394e5e3071236a93b825f18a4ad07f1d5a1405e6c984f1d71e03f535d13a2156d6ba22cb0c2b148df23a7b8a7293315d6e74b9a26b64283e8393f2ad4c5' }, ... \] } .. py:method:: Beacon.get\_attestations() .. code-block:: python >>> beacon.get\_attestations() {'data': \[\]} .. py:method:: Beacon.get\_attester\_slashings() .. code-block:: python >>> beacon.get\_attester\_slashings() {'data': \[\]} .. py:method:: Beacon.get\_proposer\_slashings() .. code-block:: python >>> beacon.get\_proposer\_slashings() {'data': \[\]} .. py:method:: Beacon.get\_voluntary\_exits() .. code-block:: python >>> beacon.get\_voluntary\_exits() {'data': \[\]} .. py:method:: Beacon.get\_fork\_schedule() .. code-block:: python >>> beacon.get\_fork\_schedule() { 'data': \[ { 'previous\_version': '0x00002009', 'current\_version': '0x00002009', 'epoch': '0' } \] } .. py:method:: Beacon.get\_spec() .. code-block:: python >>> beacon.get\_spec() { 'data': { 'DEPOSIT\_CONTRACT\_ADDRESS': '0x8c5fecdC472E27Bc447696F431E425D02dd46a8c', 'MIN\_ATTESTATION\_INCLUSION\_DELAY': '1', 'SLOTS\_PER\_EPOCH': '32', 'SHUFFLE\_ROUND\_COUNT': '90', 'MAX\_EFFECTIVE\_BALANCE': '32000000000', 'DOMAIN\_BEACON\_PROPOSER': '0x00000000', 'MAX\_ATTESTER\_SLASHINGS': '2', 'DOMAIN\_SELECTION\_PROOF': '0x05000000', ... } } .. py:method:: Beacon.get\_deposit\_contract() .. code-block:: python >>> beacon.get\_deposit\_contract() { 'data': { 'chain\_id': '5', 'address': '0x8c5fecdC472E27Bc447696F431E425D02dd46a8c' } } .. py:method:: Beacon.get\_beacon\_state(state\_id="head") .. code-block:: python >>> beacon.get\_beacon\_state() { 'data': { 'genesis\_time': '1', 'genesis\_validators\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'slot': '1', 'fork': { 'previous\_version': '0x00000000', 'current\_version': '0x00000000', 'epoch': '1' }, 'latest\_block\_header': { 'slot': '1', 'proposer\_index': '1', 'parent\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'state\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'body\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2' }, 'block\_roots': \['0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2'\], 'state\_roots': \['0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2'\], 'historical\_roots': \['0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2'\], 'eth1\_data': { 'deposit\_root': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2', 'deposit\_count': '1', 'block\_hash': '0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2' }, 'eth1\_data\_votes': \[...\], 'eth1\_deposit\_index': '1', 'validators': \[...\], 'balances': \[...\], 'randao\_mixes': \[...\], 'slashings': \[...\], 'previous\_epoch\_attestations': \[...\], 'current\_epoch\_attestations': \[...\], 'justification\_bits': '0x0f', 'previous\_justified\_checkpoint': { 'epoch': '5736', 'root': '0xec7ef54f1fd81bada8170dd0cb6be8216f8ee2f445e6936f95f5c6894a4a3b38' }, 'current\_justified\_checkpoint': { 'epoch': '5737', 'root': '0x781f0166e34c361ce2c88070c1389145abba2836edcb446338a2ca2b0054826e' }, 'finalized\_checkpoint': { 'epoch': '5736', 'root': '0xec7ef54f1fd81bada8170dd0cb6be8216f8ee2f445e6936f95f5c6894a4a3b38' } } } .. py:method:: Beacon.get\_beacon\_heads() .. code-block:: python >>> beacon.get\_beacon\_heads() { 'data': \[ { 'slot': '221600', 'root': '0x9987754077fe6100a60c75d81a51b1ef457d019404d1546a66f4f5d6c23fae45' } \] } .. py:method:: Beacon.get\_blob\_sidecars(block\_id, indices=\[\]) .. code-block:: python >>> beacon.get\_blob\_sidecars(1, indices=\[1\]) { "data": \[ { "index": "1", "blob": ..., # ommitted "kzg\_commitment": "0x93247f2209abcacf57b75a51dafae777f9dd38bc7053d1af526f220a7489a6d3a2753e5f3e8b1cfe39b56f43611df74a", "kzg\_proof": "0x7FB0A12D11Ffe8A48c2fF80dCA17adbCC1da5F6aADaAEF2b338717dcDEECf6DaB9FD7C4e4265CfBc097cD31dCB19E836", "signed\_block\_header": { "message": { "slot": "1", "proposer\_index": "1", "parent\_root": "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "state\_root": "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "body\_root": "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2" }, "signature": "0x1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505cc411d61252fb6cb3fa0017b679f8bb2305b26a285fa2737f175668d0dff91cc1b66ac1fb663c9bc59509846d6ec05345bd908eda73e670af888da41af171505" }, "kzg\_commitment\_inclusion\_proof": \[ "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2" \] } \] } .. py:method:: Beacon.get\_node\_identity() .. code-block:: python >>> beacon.get\_node\_identity() { 'data': { 'peer\_id': '16Uiu2HAmLZ1CYVFKpa3wwn4cnknZqosum8HX3GHDhUpEULQc9ixE', 'enr': 'enr:-KG4QCIp6eCZ6hG\_fd93qsw12qmbfsl2rUTfQvwVP4FOTlWeNXYo0Gg9y3WVYIdF6FQC6R0E8CbK0Ywq\_6TKMx1BpGlAhGV0aDKQOwiHlQAAIAn\_\_\_\_\_\_\_\_\_\_4JpZIJ2NIJpcIR\_AAABiXNlY3AyNTZrMaEDdVT4g1gw86BfbrtLCq2fRBlG0AnMxsXtAQgA327S5FeDdGNwgiMog3VkcIIjKA', 'p2p\_addresses': \['/ip4/127.0.0.1/tcp/9000/p2p/16Uiu2HAmLZ1CYVFKpa3wwn4cnknZqosum8HX3GHDhUpEULQc9ixE'\], 'discovery\_addresses': \['/ip4/127.0.0.1/udp/9000/p2p/16Uiu2HAmLZ1CYVFKpa3wwn4cnknZqosum8HX3GHDhUpEULQc9ixE'\], 'metadata': {'seq\_number': '0', 'attnets': '0x0000000000000000'} } } .. py:method:: Beacon.get\_peers() .. code-block:: python >>> beacon.get\_peers() { 'data': \[ { 'peer\_id': '16Uiu2HAkw1yVqF3RtMCBHMbkLZbNhfGcTUdD6Uo4X3wfzPhGVnqv', 'address': '/ip4/3.127.23.51/tcp/9000', 'state': 'connected', 'direction': 'outbound' }, { 'peer\_id': '16Uiu2HAmEJHiCzgS8GwiEYLyM3d148mzvZ9iZzsz8yqayWVPANMG', 'address': '/ip4/3.88.7.240/tcp/9000', 'state': 'connected', 'direction': 'outbound' } \] } .. py:method:: Beacon.get\_peer(peer\_id) .. code-block:: python >>> beacon.get\_peer('16Uiu2HAkw1yVqF3RtMCBHMbkLZbNhfGcTUdD6Uo4X3wfzPhGVnqv') { 'data': { 'peer\_id': '16Uiu2HAkw1yVqF3RtMCBHMbkLZbNhfGcTUdD6Uo4X3wfzPhGVnqv', 'address': '/ip4/3.127.23.51/tcp/9000', 'state': 'connected', 'direction': 'outbound' } } .. py:method:: Beacon.get\_health() .. code-block:: python >>> beacon.get\_health() 200 .. py:method:: Beacon.get\_version() .. code-block:: python >>> beacon.get\_version() { 'data': { 'version': 'teku/v20.12.0+9-g9392008/osx-x86\_64/adoptopenjdk-java-15' } } .. py:method:: Beacon.get\_syncing() .. code-block:: python >>> beacon.get\_syncing() { 'data': { 'head\_slot': '222270', 'sync\_distance': '190861' } } --- # Unknown .. py:module:: ens ENS API =========== :doc:\`ens\_overview\` has a friendly overview. Continue below for the detailed specs on each method and class in the ens module. ens\\.ens module ---------------- .. automodule:: ens.ens :members: ens\\.async\_ens module --------------------- .. automodule:: ens.async\_ens :members: ens\\.exceptions module ---------------------- .. automodule:: ens.exceptions :members: :show-inheritance: --- # Unknown .. \_contributing: Contributing ------------ Thanks for your interest in contributing to web3.py! Read on to learn what would be helpful and how to go about it. If you get stuck along the way, reach for help in the \`Python Discord server\`\_. How to Help ~~~~~~~~~~~ Without code: \* Answer user questions within GitHub issues, Stack Overflow, or the \`Python Discord server\`\_. \* Write or record tutorial content. \* Improve our documentation (including typo fixes). \* \`Open an issue \`\_ on GitHub to document a bug. Include as much detail as possible, e.g., how to reproduce the issue and any exception messages. With code: \* Fix a bug that has been reported in an issue. \* Add a feature that has been documented in an issue. \* Add a missing test case. .. warning:: \*\*Before you start:\*\* always ask if a change would be desirable or let us know that you plan to work on something! We don't want to waste your time on changes we can't accept or duplicated effort. Your Development Environment ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. note:: Use of a virtual environment is strongly advised for minimizing dependency issues. See \`this article \`\_ for usage patterns. All pull requests are made from a fork of the repository; use the GitHub UI to create a fork. web3.py depends on \`submodules \`\_, so when you clone your fork to your local machine, include the \`\`--recursive\`\` flag: .. code:: sh $ git clone --recursive https://github.com//web3.py.git $ cd web3.py Finally, install all development dependencies: .. code:: sh $ pip install -e ".\[dev\]" Using Docker ^^^^^^^^^^^^ Developing within Docker is not required, but if you prefer that workflow, use the \*sandbox\* container provided in the \*\*docker-compose.yml\*\* file. To start up the test environment, run: .. code:: sh $ docker compose up -d This will build a Docker container set up with an environment to run the Python test code. .. note:: This container does not have \`go-ethereum\` installed, so you cannot run the go-ethereum test suite. To run the Python tests from your local machine: .. code:: sh $ docker compose exec sandbox bash -c 'pytest -n 4 -f -k "not goethereum"' You can run arbitrary commands inside the Docker container by using the \`bash -c\` prefix. .. code:: sh $ docker compose exec sandbox bash -c '' Or, if you would like to open a session to the container, run: .. code:: sh $ docker compose exec sandbox bash Code Style ~~~~~~~~~~ We value code consistency. To ensure your contribution conforms to the style being used in this project, we encourage you to read our \`style guide\`\_. We use Black for linting. To ignore the commits that introduced Black in git history, you can configure your git environment like so: .. code:: sh git config blame.ignoreRevsFile .git-blame-ignore-revs Type Hints ~~~~~~~~~~ This code base makes use of \`type hints\`\_. Type hints make it easy to prevent certain types of bugs, enable richer tooling, and enhance the documentation, making the code easier to follow. All new code is required to include type hints, with the exception of tests. All parameters, as well as the return type of functions, are expected to be typed, with the exception of \`\`self\`\` and \`\`cls\`\` as seen in the following example. .. code:: python def \_\_init\_\_(self, wrapped\_db: DatabaseAPI) -> None: self.wrapped\_db = wrapped\_db self.reset() Running The Tests ~~~~~~~~~~~~~~~~~ A great way to explore the code base is to run the tests. First, install the test dependencies: .. code:: sh $ pip install -e ".\[test\]" You can run all tests with: .. code:: sh $ pytest However, running the entire test suite takes a very long time and is generally impractical. Typically, you'll just want to run a subset instead, like: .. code:: sh $ pytest tests/core/eth-module/test\_accounts.py You can use \`\`tox\`\` to run all the tests for a given version of Python: .. code:: sh $ tox -e py38-core Linting is also performed by the CI. You can save yourself some time by checking for linting errors locally: .. code:: sh $ make lint It is important to understand that each pull request must pass the full test suite as part of the CI check. This test suite will run in the CI anytime a pull request is opened or updated. Writing Tests ~~~~~~~~~~~~~ We strongly encourage contributors to write good tests for their code as part of the code review process. This helps ensure that your code is doing what it should be doing. We strongly encourage you to use our existing tests for both guidance and homogeneity / consistency across our tests. We use \`\`pytest\`\` for our tests. For more specific pytest guidance, please refer to the \`pytest documentation\`\_. Within the \`\`pytest\`\` scope, :file:\`conftest.py\` files are used for common code shared between modules that exist within the same directory as that particular :file:\`conftest.py\` file. Unit Testing and eth-tester Tests ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Our unit tests are grouped together with tests against the \`\`eth-tester\`\` library, using the \`\`py-evm\`\` library as a backend, via the \`\`EthereumTesterProvider\`\`. These tests live under appropriately named child directories within the \`\`/tests\`\` directory. The core of these tests live under \`\`/tests/core\`\`. Do your best to follow the existing structure when adding a test and make sure that its location makes sense. Integration Testing ^^^^^^^^^^^^^^^^^^^ Our integration test suite setup lives under the \`\`/tests/integration\`\` directory. The integration test suite is dependent on what we call "fixtures" (not to be confused with pytest fixtures). These zip file fixtures, which also live in the \`\`/tests/integration\`\` directory, are configured to run the specific client we are testing against along with a genesis configuration that gives our tests some pre-determined useful objects (like unlocked, pre-loaded accounts) to be able to interact with the client when we run our tests. The parent \`\`/integration\`\` directory houses some common configuration shared across all client tests, whereas the \`\`/go\_ethereum\`\` directory houses common code to be shared across geth-specific provider tests. Though the setup and run configurations exist across the different files within \`\`/tests/integration\`\`, our integration module tests are written across different files within \`\`/web3/\_utils/module\_testing\`\`. \* :file:\`common.py\` files within the client directories contain code that is shared across all provider tests (http, ipc, and ws). This is mostly used to override tests that span across all providers. \* :file:\`conftest.py\` files within each of these directories contain mostly code that can be \*used\* by all test files that exist within the same directory or subdirectories of the :file:\`conftest.py\` file. This is mostly used to house pytest fixtures to be shared among our tests. Refer to the \`pytest documentation on fixtures\`\_ for more information. \* \`\`test\_{client}\_{provider}.py\`\` files (e.g. :file:\`test\_goethereum\_http.py\`) are where client-and-provider-specific test configurations exist. This is mostly used to override tests specific to the provider type for the respective client. Working With Test Contracts ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Contracts used for testing exist under \`\`web3/\_utils/contract\_sources\`\`. These contracts get compiled via the \`\`compile\_contracts.py\`\` script in the same directory. To use this script, simply pass the Solidity version to be used to compile the contracts as an argument at the command line. Arguments for the script are: -v or --version Solidity version to be used to compile the contracts. If blank, the script uses the latest available version from solcx. -f or --filename If left blank, all .sol files will be compiled and the respective contract data will be generated. Pass in a specific \`\`.sol\`\` filename here to compile just one file. To run the script, you will need the \`\`py-solc-x\`\` library for compiling the files as well as \`\`black\`\` for code formatting. You can install those independently or install the full \`\`\[dev\]\`\` package extra as shown below. .. code:: sh $ pip install "web3\[dev\]" The following example compiles all the contracts and generates their respective contract data that is used across our test files for the test suites. This data gets generated within the \`\`contract\_data\`\` subdirectory within the \`\`contract\_sources\`\` folder. .. code-block:: bash $ cd ../web3.py/web3/\_utils/contract\_sources $ python compile\_contracts.py -v 0.8.17 Compiling OffchainLookup ... ... reformatted ... To compile and generate contract data for only one \`\`.sol\`\` file, specify using the filename with the \`\`-f\`\` (or \`\`--filename\`\`) argument flag. .. code-block:: bash $ cd ../web3.py/web3/\_utils/contract\_sources $ python compile\_contracts.py -v 0.8.17 -f OffchainLookup.sol Compiling OffchainLookup.sol reformatted ... If there is any contract data that is not generated via the script but is important to pass on to the integration tests, the \`\`\_custom\_contract\_data.py\`\` file within the \`\`contract\_data\`\` subdirectory can be used to store that information when appropriate. Be sure to re-generate the integration test fixture after running the script to update the contract bytecodes for the integration test suite - see the :ref:\`generating\_fixtures\` section below. Manual Testing ~~~~~~~~~~~~~~ To import and test an unreleased version of web3.py in another context, you can install it from your development directory: .. code:: sh $ pip install -e ../path/to/web3py Documentation ~~~~~~~~~~~~~ Good documentation will lead to quicker adoption and happier users. Please check out our guide on \`how to create documentation\`\_ for the Python Ethereum ecosystem. Pull requests generate their own preview of the latest documentation at \`\`https://web3py--.org.readthedocs.build/en//\`\`. Pull Requests ~~~~~~~~~~~~~ It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission. See GitHub's documentation for \`working on pull requests\`\_. Once you've made a pull request take a look at the Circle CI build status in the GitHub interface and make sure all tests are passing. In general, pull requests that do not pass the CI build yet won't get reviewed unless explicitly requested. If the pull request introduces changes that should be reflected in the release notes, please add a \*\*newsfragment\*\* file as explained \`here \`\_. If possible, the change to the release notes file should be included in the commit that introduces the feature or bugfix. .. \_generating\_fixtures: Generating New Fixtures ~~~~~~~~~~~~~~~~~~~~~~~ Our integration tests make use of Geth private networks. When new versions of the client software are introduced, new fixtures should be generated. Before generating new fixtures, make sure you have the test dependencies installed: .. code:: sh $ pip install -e ".\[test\]" .. note:: A "fixture" is a pre-synced network. It's the result of configuring and running a client, deploying the test contracts, and saving the resulting state for testing web3.py functionality against. Geth Fixtures ^^^^^^^^^^^^^ 1. Install the desired Geth version on your machine locally. We recommend \`py-geth\`\_ for this purpose, because it enables you to easily manage multiple versions of Geth. Note that \`\`py-geth\`\` will need updating to support each new Geth version as well. Adding newer Geth versions to py-geth is straightforward; see past commits for a template. If py-geth has the Geth version you need, install that version locally. For example: .. code:: sh $ python -m geth.install v1.14.12 2. Specify the Geth binary and run the fixture creation script (from within the web3.py directory): .. code:: sh $ GETH\_BINARY=~/.py-geth/geth-v1.14.12/bin/geth python ./tests/integration/generate\_fixtures/go\_ethereum.py 3. The output of this script is your fixture, a zip file, which is now stored in \`\`/tests/integration/\`\`. The \`\`/tests/integration/go\_ethereum/conftest.py\`\` and \`\`/web3/tools/benchmark/node.py\`\` files should be updated automatically to point to this new fixture. Delete the old fixture. 4. Run the tests. To ensure that the tests run with the correct Geth version locally, you may again include the \`\`GETH\_BINARY\`\` environment variable. 5. The \`\`geth\_version\`\` and \`\`pygeth\_version\`\` parameter defaults in \`\`/.circleci/config.yml\`\` should be automatically updated to match the \`\`go-ethereum\`\` version used to generate the test fixture and the \`\`py-geth\`\` version that supports installing it. CI Testing With a Nightly Geth Build ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Occasionally you'll want to have CI run the test suite against an unreleased version of Geth - e.g. to test upcoming hard fork changes. The workflow described below is for testing only, as updates will only be merged into main once the Geth release is published and the test runs are updated to use the new stable version. 1. Configure \`\`tests/integration/generate\_fixtures/go\_ethereum/common.py\`\` as needed. 2. Geth automagically compiles new builds for every commit that gets merged into the codebase. Download the desired build from the \`develop builds \`\_. 3. Build your test fixture, passing in the binary you just downloaded via \`\`GETH\_BINARY\`\`. Don't forget to update the \`\`/tests/integration/go\_ethereum/conftest.py\`\` file to point to your new fixture. 4. Our CI runs on Ubuntu, so download the corresponding 64-bit Linux \`develop build \`\_, then add it to the root of your web3.py directory. Rename the binary \`\`custom\_geth\`\`. 5. In \`\`.circleci/config.yml\`\`, update the \`\`geth\_version\`\` pipeline parameter to "custom". This will trigger the custom Geth build to be used in the CI test suite. 6. Create a PR and let CI do its thing. Releasing ~~~~~~~~~ Final Test Before Each Release ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before releasing a new version, build and test the package that will be released. There's a script to build and install the wheel locally, then generate a temporary virtualenv for smoke testing: .. code:: sh $ git checkout main && git pull $ make package # in another shell, navigate to the virtualenv mentioned in output of ^ # load the virtualenv with the packaged web3.py release $ source package-smoke-test/bin/activate # smoke test the release $ pip install ipython $ ipython >>> from web3 import Web3, IPCProvider >>> w3 = Web3(IPCProvider(provider\_url)) >>> w3.is\_connected() >>> ... Verify The Latest Documentation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To preview the documentation that will get published: .. code:: sh $ make docs Preview The Release Notes ^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: sh $ towncrier build --draft Compile The Release Notes ^^^^^^^^^^^^^^^^^^^^^^^^^ After confirming that the release package looks okay, compile the release notes: .. code:: sh $ make notes bump=$$VERSION\_PART\_TO\_BUMP$$ You may need to fix up any broken release note fragments before committing. Keep running \`\`make build-docs\`\` until it passes, then commit and carry on. Push The Release to GitHub & PyPI ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After committing the compiled release notes and pushing them to the main branch, release a new version: .. code:: sh $ make release bump=$$VERSION\_PART\_TO\_BUMP$$ Which Version Part to Bump ^^^^^^^^^^^^^^^^^^^^^^^^^^ The version format for this repo is \`\`{major}.{minor}.{patch}\`\` for stable, and \`\`{major}.{minor}.{patch}-{stage}.{devnum}\`\` for unstable (\`\`stage\`\` can be alpha or beta). During a release, specify which part to bump, like \`\`make release bump=minor\`\` or \`\`make release bump=devnum\`\`. If you are in an alpha version, \`\`make release bump=stage\`\` will bump to beta. If you are in a beta version, \`\`make release bump=stage\`\` will bump to a stable version. To issue an unstable version when the current version is stable, specify the new version explicitly, like \`\`make release bump="--new-version 4.0.0-alpha.1 devnum"\`\`. .. \_Python Discord server: https://discord.gg/GHryRvPB84 .. \_style guide: https://github.com/ethereum/snake-charmers-tactical-manual/blob/main/style-guide.md .. \_type hints: https://www.python.org/dev/peps/pep-0484/ .. \_how to create documentation: https://github.com/ethereum/snake-charmers-tactical-manual/blob/main/documentation.md .. \_working on pull requests: https://help.github.com/articles/about-pull-requests/ .. \_py-geth: https://github.com/ethereum/py-geth .. \_pytest documentation: https://docs.pytest.org/en/latest .. \_pytest documentation on fixtures: https://docs.pytest.org/en/latest/how-to/fixtures.html --- # Unknown Code of Conduct --------------- Our Pledge ~~~~~~~~~~ In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards ~~~~~~~~~~~~~ Examples of behavior that contributes to creating a positive environment include: \* Using welcoming and inclusive language \* Being respectful of differing viewpoints and experiences \* Gracefully accepting constructive criticism \* Focusing on what is best for the community \* Showing empathy towards other community members Examples of unacceptable behavior by participants include: \* The use of sexualized language or imagery and unwelcome sexual attention or advances \* Trolling, insulting/derogatory comments, and personal or political attacks \* Public or private harassment \* Publishing others' private information, such as a physical or electronic address, without explicit permission \* Other conduct which could reasonably be considered inappropriate in a professional setting Our Responsibilities ~~~~~~~~~~~~~~~~~~~~ Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope ~~~~~ This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement ~~~~~~~~~~~ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at snakecharmers@ethereum.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution ~~~~~~~~~~~ This Code of Conduct is adapted from the \`Contributor Covenant \`\_, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html --- # Unknown .. \_web3-eth: web3.eth API ============ .. py:module:: web3.eth .. py:class:: Eth The \`\`web3.eth\`\` object exposes the following properties and methods to interact with the RPC APIs under the \`\`eth\_\`\` namespace. By default, when a property or method returns a mapping of keys to values, it will return an \`\`AttributeDict\`\` which acts like a \`\`dict\`\` but you can access the keys as attributes and cannot modify its fields. For example, you can find the latest block number in these two ways: .. code-block:: python >>> block = web3.eth.get\_block('latest') AttributeDict({ 'hash': '0xe8ad537a261e6fff80d551d8d087ee0f2202da9b09b64d172a5f45e818eb472a', 'number': 4022281, # ... etc ... }) >>> block\['number'\] 4022281 >>> block.number 4022281 >>> block.number = 4022282 Traceback # ... etc ... TypeError: This data is immutable -- create a copy instead of modifying This feature is available via the \`\`AttributeDictMiddleware\`\` which is a default middleware. .. note:: Accessing an \`\`AttributeDict\`\` property via attribute will break type hinting. If typing is crucial for your application, accessing via key / value, as well as removing the \`\`AttributeDictMiddleware\`\` altogether, may be desired. Properties ---------- The following properties are available on the \`\`web3.eth\`\` namespace. .. py:attribute:: Eth.default\_account The ethereum address that will be used as the default \`\`from\`\` address for all transactions. Defaults to empty. .. py:attribute:: Eth.default\_block The default block number that will be used for any RPC methods that accept a block identifier. Defaults to \`\`'latest'\`\`. .. py:attribute:: Eth.syncing \* Delegates to \`\`eth\_syncing\`\` RPC Method Returns either \`\`False\`\` if the node is not syncing or a dictionary showing sync status. .. code-block:: python >>> web3.eth.syncing AttributeDict({ 'currentBlock': 2177557, 'highestBlock': 2211611, 'knownStates': 0, 'pulledStates': 0, 'startingBlock': 2177365, }) .. py:attribute:: Eth.max\_priority\_fee \* Delegates to \`\`eth\_maxPriorityFeePerGas\`\` RPC Method Returns a suggestion for a max priority fee for dynamic fee transactions in Wei. .. code-block:: python >>> web3.eth.max\_priority\_fee 2000000000 .. py:attribute:: Eth.gas\_price \* Delegates to \`\`eth\_gasPrice\`\` RPC Method Returns the current gas price in Wei. .. code-block:: python >>> web3.eth.gas\_price 20000000000 .. py:attribute:: Eth.accounts \* Delegates to \`\`eth\_accounts\`\` RPC Method Returns the list of known accounts. .. code-block:: python >>> web3.eth.accounts \['0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD'\] .. py:attribute:: Eth.block\_number \* Delegates to \`\`eth\_blockNumber\`\` RPC Method Returns the number of the most recent block Alias for :meth:\`~web3.eth.Eth.get\_block\_number\` .. code-block:: python >>> web3.eth.block\_number 2206939 .. py:attribute:: Eth.chain\_id \* Delegates to \`\`eth\_chainId\`\` RPC Method Returns an integer value for the currently configured "Chain Id" value introduced in \`EIP-155 \`\_. Returns \`\`None\`\` if no Chain Id is available. .. code-block:: python >>> web3.eth.chain\_id 61 .. note:: This property gets called frequently in validation middleware, but \`eth\_chainId\` is an allowed method for caching by default. Simply turn on request caching to avoid repeated calls to this method. .. code-block:: python >>> w3.provider.cache\_allowed\_requests = True .. \_web3-eth-methods: Methods ------- The following methods are available on the \`\`web3.eth\`\` namespace. .. py:method:: Eth.get\_balance(account, block\_identifier=eth.default\_block) \* Delegates to \`\`eth\_getBalance\`\` RPC Method Returns the balance of the given \`\`account\`\` at the block specified by \`\`block\_identifier\`\`. \`\`account\`\` may be a checksum address or an ENS name .. code-block:: python >>> web3.eth.get\_balance('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') 77320681768999138915 .. py:method:: Eth.get\_block\_number() \* Delegates to \`\`eth\_blockNumber\`\` RPC Method Returns the number of the most recent block. .. code-block:: python >>> web3.eth.get\_block\_number() 2206939 .. py:method:: Eth.get\_storage\_at(account, position, block\_identifier=eth.default\_block) \* Delegates to \`\`eth\_getStorageAt\`\` RPC Method Returns the value from a storage position for the given \`\`account\`\` at the block specified by \`\`block\_identifier\`\`. \`\`account\`\` may be a checksum address or an ENS name .. code-block:: python >>> web3.eth.get\_storage\_at('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B', 0) '0x00000000000000000000000000000000000000000000000000120a0b063499d4' .. py:method:: Eth.blob\_base\_fee Fetches the expected base fee for blobs in the next block. \* Delegates to \`\`eth\_blobBaseFee\`\` RPC Method Returns the expected base fee in Wei. .. code-block:: python >>> web3.eth.blob\_base\_fee() 537070730 .. py:method:: Eth.get\_proof(account, positions, block\_identifier=eth.default\_block) \* Delegates to \`\`eth\_getProof\`\` RPC Method Returns the values from an array of storage positions for the given \`\`account\`\` at the block specified by \`\`block\_identifier\`\`. \`\`account\`\` may be a checksum address or an ENS name .. code-block:: python >>> web3.eth.get\_proof('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B', \[0\], 3391) AttributeDict({ 'address': '0x4CB06C43fcdABeA22541fcF1F856A6a296448B6c', 'accountProof': \['0xf90211a03841a7ddd65c70c94b8efa79190d00f0ab134b26f18dcad508f60a7e74559d0ba0464b07429a05039e22931492d6c6251a860c018ea390045d596b1ac11b5c7aa7a011f4b89823a03c9c4b5a8ab079ee1bc0e2a83a508bb7a5dc7d7fb4f2e95d3186a0b5f7c51c3b2d51d97f171d2b38a4df1a7c0acc5eb0de46beeff4d07f5ed20e19a0b591a2ce02367eda31cf2d16eca7c27fd44dbf0864b64ea8259ad36696eb2a04a02b646a7552b8392ae94263757f699a27d6e9176b4c06b9fc0a722f893b964795a02df05d68bceb88eebf68aafde61d10ab942097afc1c58b8435ffd3895358a742a0c2f16143c4d1db03276c433696dddb3e9f3b113bcd854b127962262e98f43147a0828820316cc02bfefd899aba41340659fd06df1e0a0796287ec2a4110239f6d2a050496598670b04df7bbff3718887fa36437d6d8c7afb4eff86f76c5c7097dcc4a0c14e9060c6b3784e35b9e6ae2ad2984142a75910ccc89eb89dc1e2f44b6c58c2a009804db571d0ce07913e1cbacc4f1dc4fb8265c936f5c612e3a47e91c64d8e9fa063d96f38b3cb51b1665c6641e25ffe24803f2941e5df79942f6a53b7169647e4a0899f71abb18c6c956118bf567fac629b75f7e9526873e429d3d8abb6dbb58021a00fd717235298742623c0b3cafb3e4bd86c0b5ab1f71097b4dd19f3d6925d758da0096437146c16097f2ccc1d3e910d65a4132803baee2249e72c8bf0bcaaeb37e580', '0xf90151a097b17a89fd2c03ee98cb6459c08f51b269da5cee46650e84470f62bf83b43efe80a03b269d284a4c3cf8f8deacafb637c6d77f607eec8d75e8548d778e629612310480a01403217a7f1416830c870087c524dabade3985271f6f369a12b010883c71927aa0f592ac54c879817389663be677166f5022943e2fe1b52617a1d15c2f353f27dda0ac8d015a9e668f5877fcc391fae33981c00577096f0455b42df4f8e8089ece24a003ba34a13e2f2fb4bf7096540b42d4955c5269875b9cf0f7b87632585d44c9a580a0b179e3230b07db294473ae57f0170262798f8c551c755b5665ace1215cee10ca80a0552d24252639a6ae775aa1df700ffb92c2411daea7286f158d44081c8172d072a0772a87d08cf38c4c68bfde770968571abd16fd3835cb902486bd2e515d53c12d80a0413774f3d900d2d2be7a3ad999ffa859a471dc03a74fb9a6d8275455f5496a548080', '0xf869a020d13b52a61d3c1325ce3626a51418adebd6323d4840f1bdd93906359d11c933b846f8440180a01ab7c0b0a2a4bbb5a1495da8c142150891fc64e0c321e1feb70bd5f881951f7ea0551332d96d085185ab4019ad8bcf89c45321e136c261eb6271e574a2edf1461f' \], 'balance': 0, 'codeHash': '0x551332d96d085185ab4019ad8bcf89c45321e136c261eb6271e574a2edf1461f', 'nonce': 1, 'storageHash': '0x1ab7c0b0a2a4bbb5a1495da8c142150891fc64e0c321e1feb70bd5f881951f7e', 'storageProof': \[ AttributeDict({ 'key': '0x00', 'value': '0x48656c6c6f00000000000000000000000000000000000000000000000000000a', 'proof': \['0xf9019180a01ace80e7bed79fbadbe390876bd1a7d9770edf9462049ef8f4b555d05715d53ea049347a3c2eac6525a3fd7e3454dab19d73b4adeb9aa27d29493b9843f3f88814a085079b4abcd07fd4a5d6c52d35f4c4574aecc85830e90c478ca8c18fcbe590de80a02e3f8ad7ea29e784007f51852b9c3e470aef06b11bac32586a8b691134e4c27da064d2157a14bc31f195f73296ea4dcdbe7698edbf3ca81c44bf7730179d98d94ca09e7dc2597c9b7f72ddf84d7eebb0fe2a2fa2ab54fe668cd14fee44d9b40b1a53a0aa5d4acc7ac636d16bc9655556770bc325e1901fb62dc53770ef9110009e080380a0d5fde962bd2fb5326ddc7a9ca7fe0ee47c5bb3227f838b6d73d3299c22457596a08691410eff46b88f929ef649ea25025f62a5362ca8dc8876e5e1f4fc8e79256d80a0673e88d3a8a4616f676793096b5ae87cff931bd20fb8dd466f97809a1126aad8a08b774a45c2273553e2daf4bbc3a8d44fb542ea29b6f125098f79a4d211b3309ca02fed3139c1791269acb9365eddece93e743900eba6b42a6a8614747752ba268f80', '0xf891808080a0c7d094301e0c54da37b696d85f72de5520b224ab2cf4f045d8db1a3374caf0488080a0fc5581783bfe27fab9423602e1914d719fd71433e9d7dd63c95fe7e58d10c9c38080a0c64f346fc7a21f6679cba8abdf37ca2de8c4fcd8f8bcaedb261b5f77627c93908080808080a0ddef2936a67a3ac7d3d4ff15a935a45f2cc4976c8f0310aed85daf763780e2b480', '0xf843a0200decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563a1a048656c6c6f00000000000000000000000000000000000000000000000000000a' \] }) \] }) \* Merkle proof verification using py-trie. The following example verifies that the values returned in the \`\`AttributeDict\`\` are included in the state of given trie \`\`root\`\`. .. code-block:: python from eth\_utils import ( keccak, ) import rlp from rlp.sedes import ( Binary, big\_endian\_int, ) from trie import ( HexaryTrie, ) from web3.\_utils.encoding import ( pad\_bytes, ) def format\_proof\_nodes(proof): trie\_proof = \[\] for rlp\_node in proof: trie\_proof.append(rlp.decode(bytes(rlp\_node))) return trie\_proof def verify\_eth\_get\_proof(proof, root): trie\_root = Binary.fixed\_length(32, allow\_empty=True) hash32 = Binary.fixed\_length(32) class \_Account(rlp.Serializable): fields = \[ ('nonce', big\_endian\_int), ('balance', big\_endian\_int), ('storage', trie\_root), ('code\_hash', hash32) \] acc = \_Account( proof.nonce, proof.balance, proof.storageHash, proof.codeHash ) rlp\_account = rlp.encode(acc) trie\_key = keccak(bytes.fromhex(proof.address\[2:\])) assert rlp\_account == HexaryTrie.get\_from\_proof( root, trie\_key, format\_proof\_nodes(proof.accountProof) ), f"Failed to verify account proof {proof.address}" for storage\_proof in proof.storageProof: trie\_key = keccak(pad\_bytes(b'\\x00', 32, storage\_proof.key)) root = proof.storageHash if storage\_proof.value == b'\\x00': rlp\_value = b'' else: rlp\_value = rlp.encode(storage\_proof.value) assert rlp\_value == HexaryTrie.get\_from\_proof( root, trie\_key, format\_proof\_nodes(storage\_proof.proof) ), f"Failed to verify storage proof {storage\_proof.key}" return True block = w3.eth.get\_block(3391) proof = w3.eth.get\_proof('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B', \[0, 1\], 3391) assert verify\_eth\_get\_proof(proof, block.stateRoot) .. py:method:: Eth.get\_code(account, block\_identifier=eth.default\_block) \* Delegates to \`\`eth\_getCode\`\` RPC Method Returns the bytecode for the given \`\`account\`\` at the block specified by \`\`block\_identifier\`\`. \`\`account\`\` may be a checksum address or an ENS name .. code-block:: python # For a contract address. >>> web3.eth.get\_code('0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B') '0x6060604052361561027c5760e060020a60003504630199.....' # For a private key address. >>> web3.eth.get\_code('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') '0x' .. py:method:: Eth.get\_block(block\_identifier=eth.default\_block, full\_transactions=False) \* Delegates to \`\`eth\_getBlockByNumber\`\` or \`\`eth\_getBlockByHash\`\` RPC Methods Returns the block specified by \`\`block\_identifier\`\`. Delegates to \`\`eth\_getBlockByNumber\`\` if \`\`block\_identifier\`\` is an integer or one of the predefined block parameters \`\`'latest', 'earliest', 'pending', 'safe', 'finalized'\`\` - otherwise delegates to \`\`eth\_getBlockByHash\`\`. Throws \`\`BlockNotFound\`\` error if the block is not found. If \`\`full\_transactions\`\` is \`\`True\`\` then the \`\`'transactions'\`\` key will contain full transactions objects. Otherwise it will be an array of transaction hashes. .. code-block:: python >>> web3.eth.get\_block(2000000) AttributeDict({ 'difficulty': 49824742724615, 'extraData': '0xe4b883e5bda9e7a59ee4bb99e9b1bc', 'gasLimit': 4712388, 'gasUsed': 21000, 'hash': '0xc0f4906fea23cf6f3cce98cb44e8e1449e455b28d684dfa9ff65426495584de6', 'logsBloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', 'miner': '0x61c808d82a3ac53231750dadc13c777b59310bd9', 'nonce': '0x3b05c6d5524209f1', 'number': 2000000, 'parentHash': '0x57ebf07eb9ed1137d41447020a25e51d30a0c272b5896571499c82c33ecb7288', 'receiptsRoot': '0x84aea4a7aad5c5899bd5cfc7f309cc379009d30179316a2a7baa4a2ea4a438ac', 'sha3Uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 'size': 650, 'stateRoot': '0x96dbad955b166f5119793815c36f11ffa909859bbfeb64b735cca37cbf10bef1', 'timestamp': 1470173578, 'totalDifficulty': 44010101827705409388, 'transactions': \['0xc55e2b90168af6972193c1f86fa4d7d7b31a29c156665d15b9cd48618b5177ef'\], 'transactionsRoot': '0xb31f174d27b99cdae8e746bd138a01ce60d8dd7b224f7c60845914def05ecc58', 'uncles': \[\], }) .. py:method:: Eth.get\_block\_transaction\_count(block\_identifier) \* Delegates to \`\`eth\_getBlockTransactionCountByNumber\`\` or \`\`eth\_getBlockTransactionCountByHash\`\` RPC Methods Returns the number of transactions in the block specified by \`\`block\_identifier\`\`. Delegates to \`\`eth\_getBlockTransactionCountByNumber\`\` if \`\`block\_identifier\`\` is an integer or one of the predefined block parameters \`\`'latest', 'earliest', 'pending', 'safe', 'finalized'\`\`, otherwise delegates to \`\`eth\_getBlockTransactionCountByHash\`\`. Throws \`\`BlockNotFoundError\`\` if transactions are not found. .. code-block:: python >>> web3.eth.get\_block\_transaction\_count(46147) 1 >>> web3.eth.get\_block\_transaction\_count('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd') # block 46147 1 .. py:method:: Eth.get\_uncle\_by\_block(block\_identifier, uncle\_index) \* Delegates to \`\`eth\_getUncleByBlockHashAndIndex\`\` or \`\`eth\_getUncleByBlockNumberAndIndex\`\` RPC methods Returns the uncle at the index specified by \`\`uncle\_index\`\` from the block specified by \`\`block\_identifier\`\`. Delegates to \`\`eth\_getUncleByBlockNumberAndIndex\`\` if \`\`block\_identifier\`\` is an integer or one of the predefined block parameters \`\`'latest', 'earliest', 'pending'\`\`, otherwise delegates to \`\`eth\_getUncleByBlockHashAndIndex\`\`. Throws \`\`BlockNotFound\`\` if the block is not found. .. code-block:: python >>> web3.eth.get\_uncle\_by\_block(56160, 0) AttributeDict({ 'author': '0xbe4532e1b1db5c913cf553be76180c1777055403', 'difficulty': '0x17dd9ca0afe', 'extraData': '0x476574682f686261722f76312e302e312f6c696e75782f676f312e342e32', 'gasLimit': '0x2fefd8', 'gasUsed': '0x0', 'hash': '0xc78c35720d930f9ef34b4e6fb9d02ffec936f9b02a8f0fa858456e4afd4d5614', 'logsBloom':'0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', 'miner': '0xbe4532e1b1db5c913cf553be76180c1777055403', 'mixHash': '0x041e14603f35a82f6023802fec96ef760433292434a39787514f140950597e5e', 'nonce': '0x5d2b7e3f1af09995', 'number': '0xdb5e', 'parentHash': '0xcc30e8a9b15c548d5bf113c834143a8f0e1909fbfea96b2a208dc154293a78cf', 'receiptsRoot': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', 'sealFields': \['0xa0041e14603f35a82f6023802fec96ef760433292434a39787514f140950597e5e', '0x885d2b7e3f1af09995'\], 'sha3Uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 'size': None, 'stateRoot': '0x8ce2b1bf8e25a06a8ca34c647ff5fd0fa48ac725cc07f657ae1645ab8ef68c91', 'timestamp': '0x55c6a972', 'totalDifficulty': '0xce4c4f0a0b810b', 'transactions': \[\], 'transactionsRoot': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', 'uncles': \[\] }) # You can also refer to the block by hash: >>> web3.eth.get\_uncle\_by\_block('0x685b2226cbf6e1f890211010aa192bf16f0a0cba9534264a033b023d7367b845', 0) AttributeDict({ ... }) .. py:method:: Eth.get\_uncle\_count(block\_identifier) \* Delegates to \`\`eth\_getUncleCountByBlockHash\`\` or \`\`eth\_getUncleCountByBlockNumber\`\` RPC methods Returns the (integer) number of uncles associated with the block specified by \`\`block\_identifier\`\`. Delegates to \`\`eth\_getUncleCountByBlockNumber\`\` if \`\`block\_identifier\`\` is an integer or one of the predefined block parameters \`\`'latest', 'earliest', 'pending'\`\`, otherwise delegates to \`\`eth\_getUncleCountByBlockHash\`\`. Throws \`\`BlockNotFound\`\` if the block is not found. .. code-block:: python >>> web3.eth.get\_uncle\_count(56160) 1 # You can also refer to the block by hash: >>> web3.eth.get\_uncle\_count('0x685b2226cbf6e1f890211010aa192bf16f0a0cba9534264a033b023d7367b845') 1 .. py:method:: Eth.get\_transaction(transaction\_hash) \* Delegates to \`\`eth\_getTransactionByHash\`\` RPC Method Returns the transaction specified by \`\`transaction\_hash\`\`. If the transaction cannot be found throws :class:\`web3.exceptions.TransactionNotFound\`. .. code-block:: python >>> web3.eth.get\_transaction('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') AttributeDict({'blockHash': HexBytes('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd'), 'blockNumber': 46147, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gas': 21000, 'gasPrice': 50000000000000, 'hash': HexBytes('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060'), 'input': HexBytes('0x'), 'nonce': 0, 'r': HexBytes('0x88ff6cf0fefd94db46111149ae4bfc179e9b94721fffd821d38d16464b3f71d0'), 's': HexBytes('0x45e0aff800961cfce805daef7016b9b675c137a6a41a548f7b60a3484c06a33a'), 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionIndex': 0, 'type': 0, 'v': 28, 'value': 31337 }) .. py:method:: Eth.get\_raw\_transaction(transaction\_hash) \* Delegates to \`\`eth\_getRawTransactionByHash\`\` RPC Method Returns the raw form of transaction specified by \`\`transaction\_hash\`\`. If no transaction is found, \`\`TransactionNotFound\`\` is raised. .. code-block:: python >>> web3.eth.get\_raw\_transaction('0x86fbfe56cce542ff0a2a2716c31675a0c9c43701725c4a751d20ee2ddf8a733d') HexBytes('0xf86907843b9aca0082520894dc544d1aa88ff8bbd2f2aec754b1f1e99e1812fd018086eecac466e115a0f9db4e25484b28f486b247a372708d4cd0643fc63e604133afac577f4cc1eab8a044841d84e799d4dc18ba146816a937e8a0be8bc296bd8bb8aea126de5e627e06') .. py:method:: Eth.get\_transaction\_by\_block(block\_identifier, transaction\_index) \* Delegates to \`\`eth\_getTransactionByBlockNumberAndIndex\`\` or \`\`eth\_getTransactionByBlockHashAndIndex\`\` RPC Methods Returns the transaction at the index specified by \`\`transaction\_index\`\` from the block specified by \`\`block\_identifier\`\`. Delegates to \`\`eth\_getTransactionByBlockNumberAndIndex\`\` if \`\`block\_identifier\`\` is an integer or one of the predefined block parameters \`\`'latest', 'earliest', 'pending', 'safe', 'finalized'\`\`, otherwise delegates to \`\`eth\_getTransactionByBlockHashAndIndex\`\`. If a transaction is not found at specified arguments, throws :class:\`web3.exceptions.TransactionNotFound\`. .. code-block:: python >>> web3.eth.get\_transaction\_by\_block(46147, 0) AttributeDict({ 'blockHash': '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 'blockNumber': 46147, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gas': 21000, 'gasPrice': None, 'hash': '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060', 'input': '0x', 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'nonce': 0, 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionIndex': 0, 'value': 31337, }) >>> web3.eth.get\_transaction\_by\_block('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 0) AttributeDict({ 'blockHash': '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 'blockNumber': 46147, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gas': 21000, 'gasPrice': None, 'hash': '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060', 'input': '0x', 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'nonce': 0, 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionIndex': 0, 'value': 31337, }) .. py:method:: Eth.get\_raw\_transaction\_by\_block(block\_identifier, transaction\_index) \* Delegates to \`\`eth\_getRawTransactionByBlockNumberAndIndex\`\` or \`\`eth\_getRawTransactionByBlockHashAndIndex\`\` RPC Methods Returns the raw transaction at the index specified by \`\`transaction\_index\`\` from the block specified by \`\`block\_identifier\`\`. Delegates to \`\`eth\_getRawTransactionByBlockNumberAndIndex\`\` if \`\`block\_identifier\`\` is an integer or one of the predefined block parameters \`\`'latest', 'earliest', 'pending', 'safe', 'finalized'\`\`, otherwise delegates to \`\`eth\_getRawTransactionByBlockHashAndIndex\`\`. If a transaction is not found at specified arguments, throws :class:\`web3.exceptions.TransactionNotFound\`. .. code-block:: python >>> web3.eth.get\_raw\_transaction\_by\_block('latest', 0) HexBytes('0x02f87582053901843b9aca00843b9aca008301d8a894e2dfcfa89a45abdc3de91f7a2844b276b8451d2e888ac7230489e8000080c001a028dcd2e11682288c00237f377280bc6a478a6b27e9c2d745262152add1b1dfcba04e7a33b7ce2a37fc3cd3af7bdc7d7beff721664d56508defa188df35afd77c2c') >>> web3.eth.get\_raw\_transaction\_by\_block(2, 0) HexBytes('0x02f87582053901843b9aca00843b9aca008301d8a894e2dfcfa89a45abdc3de91f7a2844b276b8451d2e888ac7230489e8000080c001a028dcd2e11682288c00237f377280bc6a478a6b27e9c2d745262152add1b1dfcba04e7a33b7ce2a37fc3cd3af7bdc7d7beff721664d56508defa188df35afd77c2c') >>> web3.eth.get\_raw\_transaction\_by\_block('0xca609fb606a04ce6aaec76415cd0b9d8c2bc83ad2a4d17db7fd403ee7d97bf40', 0) HexBytes('0x02f87582053901843b9aca00843b9aca008301d8a894e2dfcfa89a45abdc3de91f7a2844b276b8451d2e888ac7230489e8000080c001a028dcd2e11682288c00237f377280bc6a478a6b27e9c2d745262152add1b1dfcba04e7a33b7ce2a37fc3cd3af7bdc7d7beff721664d56508defa188df35afd77c2c') .. py:method:: Eth.wait\_for\_transaction\_receipt(transaction\_hash, timeout=120, poll\_latency=0.1) Waits for the transaction specified by \`\`transaction\_hash\`\` to be included in a block, then returns its transaction receipt. Optionally, specify a \`\`timeout\`\` in seconds. If timeout elapses before the transaction is added to a block, then :meth:\`~Eth.wait\_for\_transaction\_receipt\` raises a :class:\`web3.exceptions.TimeExhausted\` exception. .. code-block:: python >>> web3.eth.wait\_for\_transaction\_receipt('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') # If transaction is not yet in a block, time passes, while the thread sleeps... # ... # Then when the transaction is added to a block, its receipt is returned: AttributeDict({ 'blockHash': HexBytes('0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd'), 'blockNumber': 46147, 'contractAddress': None, 'cumulativeGasUsed': 21000, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gasUsed': 21000, 'logs': \[\], 'logsBloom': HexBytes('0x000000000000000000000000000000000000000000000000...0000'), 'status': 1, 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionHash': HexBytes('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060'), 'transactionIndex': 0, }) .. py:method:: Eth.get\_transaction\_receipt(transaction\_hash) \* Delegates to \`\`eth\_getTransactionReceipt\`\` RPC Method Returns the transaction receipt specified by \`\`transaction\_hash\`\`. If the transaction cannot be found throws :class:\`web3.exceptions.TransactionNotFound\`. If \`\`status\`\` in response equals 1 the transaction was successful. If it is equals 0 the transaction was reverted by EVM. .. code-block:: python >>> web3.eth.get\_transaction\_receipt('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') # not yet mined Traceback # ... etc ... TransactionNotFound: Transaction with hash: 0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060 not found. # wait for it to be mined.... >>> web3.eth.get\_transaction\_receipt('0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060') AttributeDict({ 'blockHash': '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd', 'blockNumber': 46147, 'contractAddress': None, 'cumulativeGasUsed': 21000, 'from': '0xA1E4380A3B1f749673E270229993eE55F35663b4', 'gasUsed': 21000, 'logs': \[\], 'logsBloom': '0x000000000000000000000000000000000000000000000000...0000', 'status': 1, # 0 or 1 'to': '0x5DF9B87991262F6BA471F09758CDE1c0FC1De734', 'transactionHash': '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060', 'transactionIndex': 0, }) .. py:method:: Eth.get\_transaction\_count(account, block\_identifier=web3.eth.default\_block) \* Delegates to \`\`eth\_getTransactionCount\`\` RPC Method Returns the number of transactions that have been sent from \`\`account\`\` as of the block specified by \`\`block\_identifier\`\`. \`\`account\`\` may be a checksum address or an ENS name .. code-block:: python >>> web3.eth.get\_transaction\_count('0xd3CdA913deB6f67967B99D67aCDFa1712C293601') 340 .. py:method:: Eth.send\_transaction(transaction) \* Delegates to \`\`eth\_sendTransaction\`\` RPC Method Signs and sends the given \`\`transaction\`\` The \`\`transaction\`\` parameter should be a dictionary with the following fields. \* \`\`from\`\`: \`\`bytes or text\`\`, checksum address or ENS name - (optional, default: \`\`web3.eth.defaultAccount\`\`) The address the transaction is sent from. \* \`\`to\`\`: \`\`bytes or text\`\`, checksum address or ENS name - (optional when creating new contract) The address the transaction is directed to. \* \`\`gas\`\`: \`\`integer\`\` - (optional) Integer of the gas provided for the transaction execution. It will return unused gas. \* \`\`maxFeePerGas\`\`: \`\`integer or hex\`\` - (optional) maximum amount you're willing to pay, inclusive of \`\`baseFeePerGas\`\` and \`\`maxPriorityFeePerGas\`\`. The difference between \`\`maxFeePerGas\`\` and \`\`baseFeePerGas + maxPriorityFeePerGas\`\` is refunded to the user. \* \`\`maxPriorityFeePerGas\`\`: \`\`integer or hex\`\` - (optional) the part of the fee that goes to the miner \* \`\`gasPrice\`\`: \`\`integer\`\` - Integer of the gasPrice used for each paid gas \*\*LEGACY\*\* - unless you have a good reason to use \`\`gasPrice\`\`, use \`\`maxFeePerGas\`\` and \`\`maxPriorityFeePerGas\`\` instead. \* \`\`value\`\`: \`\`integer\`\` - (optional) Integer of the value send with this transaction \* \`\`data\`\`: \`\`bytes or text\`\` - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see \`Ethereum Contract ABI \`\_. \* \`\`nonce\`\`: \`\`integer\`\` - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce. If the \`\`transaction\`\` specifies a \`\`data\`\` value but does not specify \`\`gas\`\` then the \`\`gas\`\` value will be populated using the :meth:\`~web3.eth.Eth.estimate\_gas()\` function with an additional buffer of \`\`100000\`\` gas up to the \`\`gasLimit\`\` of the latest block. In the event that the value returned by :meth:\`~web3.eth.Eth.estimate\_gas()\` method is greater than the \`\`gasLimit\`\` a \`\`ValueError\`\` will be raised. .. code-block:: python # simple example (web3.py and / or client determines gas and fees, typically defaults to a dynamic fee transaction post London fork) >>> web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 12345 }) # Dynamic fee transaction, introduced by EIP-1559: HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') >>> web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 12345, 'gas': 21000, 'maxFeePerGas': web3.to\_wei(250, 'gwei'), 'maxPriorityFeePerGas': web3.to\_wei(2, 'gwei'), }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') # Legacy transaction (less efficient) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') >>> web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 12345, 'gas': 21000, 'gasPrice': web3.to\_wei(50, 'gwei'), }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') .. py:method:: Eth.sign\_transaction(transaction) \* Delegates to \`\`eth\_signTransaction\`\` RPC Method. Returns a transaction that's been signed by the node's private key, but not yet submitted. The signed tx can be submitted with \`\`Eth.send\_raw\_transaction\`\` .. code-block:: python >>> signed\_txn = w3.eth.sign\_transaction(dict( nonce=w3.eth.get\_transaction\_count(w3.eth.accounts\[0\]), maxFeePerGas=2000000000, maxPriorityFeePerGas=1000000000, gas=100000, to='0xd3CdA913deB6f67967B99D67aCDFa1712C293601', value=1, data=b'', ) ) b"\\xf8d\\x80\\x85\\x040\\xe24\\x00\\x82R\\x08\\x94\\xdcTM\\x1a\\xa8\\x8f\\xf8\\xbb\\xd2\\xf2\\xae\\xc7T\\xb1\\xf1\\xe9\\x9e\\x18\\x12\\xfd\\x01\\x80\\x1b\\xa0\\x11\\r\\x8f\\xee\\x1d\\xe5=\\xf0\\x87\\x0en\\xb5\\x99\\xed;\\xf6\\x8f\\xb3\\xf1\\xe6,\\x82\\xdf\\xe5\\x97lF|\\x97%;\\x15\\xa04P\\xb7=\*\\xef \\t\\xf0&\\xbc\\xbf\\tz%z\\xe7\\xa3~\\xb5\\xd3\\xb7=\\xc0v\\n\\xef\\xad+\\x98\\xe3'" # noqa: E501 .. py:method:: Eth.send\_raw\_transaction(raw\_transaction) \* Delegates to \`\`eth\_sendRawTransaction\`\` RPC Method Sends a signed and serialized transaction. Returns the transaction hash as a HexBytes object. .. code-block:: python >>> signed\_txn = w3.eth.account.sign\_transaction(dict( nonce=w3.eth.get\_transaction\_count(public\_address\_of\_senders\_account), maxFeePerGas=3000000000, maxPriorityFeePerGas=2000000000, gas=100000, to='0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', value=12345, data=b'', type=2, # (optional) the type is now implicitly set based on appropriate transaction params chainId=1, ), private\_key\_for\_senders\_account, ) >>> w3.eth.send\_raw\_transaction(signed\_txn.raw\_transaction) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') .. py:method:: Eth.replace\_transaction(transaction\_hash, new\_transaction) \* Delegates to \`\`eth\_sendTransaction\`\` RPC Method Sends a transaction that replaces the transaction with \`\`transaction\_hash\`\`. The \`\`transaction\_hash\`\` must be the hash of a pending transaction. The \`\`new\_transaction\`\` parameter should be a dictionary with transaction fields as required by :meth:\`~web3.eth.Eth.send\_transaction\`. It will be used to entirely replace the transaction of \`\`transaction\_hash\`\` without using any of the pending transaction's values. If the \`\`new\_transaction\`\` specifies a \`\`nonce\`\` value, it must match the pending transaction's nonce. If the \`\`new\_transaction\`\` specifies \`\`maxFeePerGas\`\` and \`\`maxPriorityFeePerGas\`\` values, they must be greater than the pending transaction's values for each field, respectively. \* Legacy Transaction Support (Less Efficient - Not Recommended) If the pending transaction specified a \`\`gasPrice\`\` value (legacy transaction), the \`\`gasPrice\`\` value for the \`\`new\_transaction\`\` must be greater than the pending transaction's \`\`gasPrice\`\`. If the \`\`new\_transaction\`\` does not specify any of \`\`gasPrice\`\`, \`\`maxFeePerGas\`\`, or \`\`maxPriorityFeePerGas\`\` values, one of the following will happen: \* If the pending transaction has a \`\`gasPrice\`\` value, this value will be used with a multiplier of 1.125 - This is typically the minimum \`\`gasPrice\`\` increase a node requires before it accepts a replacement transaction. \* If a gas price strategy is set, the \`\`gasPrice\`\` value from the gas price strategy(See :ref:\`Gas\_Price\`) will be used. \* If none of the above, the client will ultimately decide appropriate values for \`\`maxFeePerGas\`\` and \`\`maxPriorityFeePerGas\`\`. These will likely be default values and may result in an unsuccessful replacement of the pending transaction. This method returns the transaction hash of the replacement transaction as a HexBytes object. .. code-block:: python >>> tx = web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 1000 }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') >>> web3.eth.replace\_transaction('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331', { 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 2000 }) HexBytes('0x4177e670ec6431606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1528989') .. py:method:: Eth.modify\_transaction(transaction\_hash, \*\*transaction\_params) \* Delegates to \`\`eth\_sendTransaction\`\` RPC Method Sends a transaction that modifies the transaction with \`\`transaction\_hash\`\`. \`\`transaction\_params\`\` are keyword arguments that correspond to valid transaction parameters as required by :meth:\`~web3.eth.Eth.send\_transaction\`. The parameter values will override the pending transaction's values to create the replacement transaction to send. The same validation and defaulting rules of :meth:\`~web3.eth.Eth.replace\_transaction\` apply. This method returns the transaction hash of the newly modified transaction as a HexBytes object. .. code-block:: python >>> tx = web3.eth.send\_transaction({ 'to': '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', 'from': web3.eth.accounts\[0\], 'value': 1000 }) HexBytes('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331') >>> web3.eth.modify\_transaction('0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331', value=2000) HexBytes('0xec6434e6701771606e55d6b4ca35a1a6b75ee3d73315145a921026d15299d05') .. py:method:: Eth.sign(account, data=None, hexstr=None, text=None) \* Delegates to \`\`eth\_sign\`\` RPC Method Caller must specify exactly one of: \`\`data\`\`, \`\`hexstr\`\`, or \`\`text\`\`. Signs the given data with the private key of the given \`\`account\`\`. The account must be unlocked. \`\`account\`\` may be a checksum address or an ENS name .. code-block:: python >>> web3.eth.sign( '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', text='some-text-tö-sign') '0x1a8bbe6eab8c72a219385681efefe565afd3accee35f516f8edf5ae82208fbd45a58f9f9116d8d88ba40fcd29076d6eada7027a3b412a9db55a0164547810cc401' >>> web3.eth.sign( '0x582AC4D8929f58c217d4a52aDD361AE470a8a4cD', data=b'some-text-t\\xc3\\xb6-sign') '0x1a8bbe6eab8c72a219385681efefe565afd3accee35f516f8edf5ae82208fbd45a58f9f9116d8d88ba40fcd29076d6eada7027a3b412a9db55a0164547810cc401' >>> web3.eth.sign( '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', hexstr='0x736f6d652d746578742d74c3b62d7369676e') '0x1a8bbe6eab8c72a219385681efefe565afd3accee35f516f8edf5ae82208fbd45a58f9f9116d8d88ba40fcd29076d6eada7027a3b412a9db55a0164547810cc401' .. py:method:: Eth.sign\_typed\_data(account, jsonMessage) \* Delegates to \`\`eth\_signTypedData\`\` RPC Method .. note:: \`\`eth\_signTypedData\`\` is not currently supported by any major client (Besu, Erigon, Geth, or Nethermind) Please note that the \`\`jsonMessage\`\` argument is the loaded JSON Object and \*\*NOT\*\* the JSON String itself. Signs the \`\`Structured Data\`\` (or \`\`Typed Data\`\`) with the private key of the given \`\`account\`\`. The account must be unlocked. \`\`account\`\` may be a checksum address or an ENS name .. py:method:: Eth.call(transaction, block\_identifier=web3.eth.default\_block, state\_override=None, ccip\_read\_enabled=True) \* Delegates to \`\`eth\_call\`\` RPC Method Executes the given transaction locally without creating a new transaction on the blockchain. Returns the return value of the executed contract. The \`\`transaction\`\` parameter is handled in the same manner as the :meth:\`~web3.eth.Eth.send\_transaction()\` method. .. code-block:: python >>> myContract.functions.setVar(1).transact() HexBytes('0x79af0c7688afba7588c32a61565fd488c422da7b5773f95b242ea66d3d20afda') >>> myContract.functions.getVar().call() 1 # The above call equivalent to the raw call: >>> web3.eth.call({'value': 0, 'gas': 21736, 'maxFeePerGas': 2000000000, 'maxPriorityFeePerGas': 1000000000, 'to': '0xc305c901078781C232A2a521C2aF7980f8385ee9', 'data': '0x477a5c98'}) HexBytes('0x0000000000000000000000000000000000000000000000000000000000000001') In most cases it is better to make contract function call through the :py:class:\`web3.contract.Contract\` interface. Overriding state is a debugging feature available in Geth clients. View their \`usage documentation \`\_ for a list of possible parameters. \`EIP-3668 \`\_ introduced support for the \`\`OffchainLookup\`\` revert / CCIP Read support. In order to properly handle a call to a contract function that reverts with an \`\`OffchainLookup\`\` error for offchain data retrieval, the \`\`ccip\_read\_enabled\`\` flag has been added to the \`\`eth\_call\`\` method. \`\`ccip\_read\_enabled\`\` is optional, yielding the default value for CCIP Read on calls to a global \`\`global\_ccip\_read\_enabled\`\` flag on the provider which is set to \`\`True\`\` by default. This means CCIP Read is enabled by default for calls, as is recommended in EIP-3668. Therefore, calls to contract functions that revert with an \`\`OffchainLookup\`\` will be handled appropriately by default. The \`\`ccip\_read\_enabled\`\` flag on the call will always override the value of the global flag on the provider for explicit control over specific calls. If the flag on the call is set to \`\`False\`\`, the call will raise the \`\`OffchainLookup\`\` instead of properly handling the exception according to EIP-3668. This may be useful for "preflighting" a transaction with a call (see :ref:\`ccip-read-example\` within the examples section). If the function called results in a \`\`revert\`\` error, a \`\`ContractLogicError\`\` will be raised. If there is an error message with the error, web3.py attempts to parse the message that comes back and return it to the user as the error string. As of v6.3.0, the raw data is also returned and can be accessed via the \`\`data\`\` attribute on \`\`ContractLogicError\`\`. .. py:method:: Eth.create\_access\_list(transaction, block\_identifier=web3.eth.default\_block) \* Delegates to \`\`eth\_createAccessList\`\` RPC Method This method creates an \`EIP-2930 \`\_ type \`\`accessList\`\` based on a given \`\`transaction\`\`. The \`\`accessList\`\` contains all storage slots and addresses read and written by the transaction, except for the sender account and the precompiles. This method uses the same \`\`transaction\`\` call object and \`\`block\_identifier\`\` object as :meth:\`~web3.eth.Eth.call()\`. An \`\`accessList\`\` can be used to access contracts that became inaccessible due to gas cost increases. The \`\`transaction\`\` parameter is handled in the same manner as the :meth:\`~web3.eth.Eth.send\_transaction()\` method. The optional \`\`block\_identifier\`\` parameter is a block\_number or \`\`latest\`\` or \`\`pending\`\`. Default is \`\`latest\`\`. .. code-block:: python >>> w3.eth.create\_access\_list( ... { ... "to": to\_checksum\_address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"), ... "gasPrice": 10\*\*11, ... "value": 0, ... "data": "0x608060806080608155", ... }, ... "pending", ... ) AttributeDict({ "accessList": \[ AttributeDict({ "address": "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe", "storageKeys": \[ "0x0000000000000000000000000000000000000000000000000000000000000003", "0x0000000000000000000000000000000000000000000000000000000000000007", \] }), AttributeDict({ "address": "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413", "storageKeys": \[\] }), \], "gasUsed": 21000 }) The method \`\`eth\_createAccessList\`\` returns a list of addresses and storage keys used by the transaction, plus the gas consumed when the \`\`accessList\`\` is included. Like \`\`eth\_estimateGas\`\`, this is an estimation; the list could change when the transaction is actually finalized. Adding an \`\`accessList\`\` to your transaction does not necessarily result in lower gas usage compared to a transaction without an \`\`accessList\`\`. .. py:method:: Eth.fee\_history(block\_count, newest\_block, reward\_percentiles=None) \* Delegates to \`\`eth\_feeHistory\`\` RPC Method Returns transaction fee data for up to 1,024 blocks. :param block\_count: The number of blocks in the requested range. Depending on the client, this value should be either a :py:class:\`int\` between 1 and 1024 or a hexstring. Less than requested may be returned if not all blocks are available. :type block\_count: int or hexstring :param newest\_block: The newest, highest-numbered, block in the requested range. This value may be an :py:class:\`int\` or one of the predefined block parameters \`\`'latest'\`\`, \`\`'earliest'\`\`, or \`\`'pending'\`\`. :type newest\_block: int or BlockParams :param reward\_percentiles: \*(optional)\* A monotonically increasing list of percentile :py:class:\`float\` values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used. :type reward\_percentiles: List\[float\] or None :return: An \`\`AttributeDict\`\` containing the following keys: \* \*\*oldestBlock\*\* \*(int)\* -- The oldest, lowest-numbered, block in the range requested as a \`\`BlockNumber\`\` type with :py:class:\`int\` value. \* \*\*baseFeePerGas\*\* \*(List\[Wei\])\* -- An array of block base fees per gas. This includes the next block after the newest of the returned range, because this value can be derived from the newest block. Zeroes are returned for pre-EIP-1559 blocks. \* \*\*gasUsedRatio\*\* \*(List\[float\])\* -- An array of \`\`gasUsed\`\`/\`\`gasLimit\`\` float values for the requested blocks. \* \*\*reward\*\* \*(List\[List\[Wei\]\])\* -- \*(optional)\* A two-dimensional array of effective priority fees per gas at the requested block percentiles. .. code-block:: python >>> w3.eth.fee\_history(4, 'latest', \[10, 90\]) AttributeDict({ 'oldestBlock': 3, 'reward': \[\[220, 7145389\], \[1000000, 6000213\], \[550, 550\], \[125, 12345678\]\], 'baseFeePerGas': \[202583058, 177634473, 155594425, 136217133, 119442408\], 'gasUsedRatio': \[0.007390479689642084, 0.0036988514889990873, 0.0018512333048507866, 0.00741217041320997\] }) .. py:method:: Eth.estimate\_gas(transaction, block\_identifier=None, state\_override=None) \* Delegates to \`\`eth\_estimateGas\`\` RPC Method Executes the given transaction locally without creating a new transaction on the blockchain. Returns amount of gas consumed by execution which can be used as a gas estimate. The \`\`transaction\`\` and \`\`block\_identifier\`\` parameters are handled in the same manner as the :meth:\`~web3.eth.Eth.send\_transaction()\` method. The \`\`state\_override\`\` is useful when there is a chain of transaction calls. It overrides state so that the gas estimate of a transaction is accurate in cases where prior calls produce side effects. .. code-block:: python >>> web3.eth.estimate\_gas({'to': '0xd3CdA913deB6f67967B99D67aCDFa1712C293601', 'from':web3.eth.accounts\[0\], 'value': 12345}) 21000 .. py:method:: Eth.generate\_gas\_price(transaction\_params=None) Uses the selected gas price strategy to calculate a gas price. This method returns the gas price denominated in wei. The \`\`transaction\_params\`\` argument is optional however some gas price strategies may require it to be able to produce a gas price. .. code-block:: python >>> web3.eth.generate\_gas\_price() 20000000000 .. note:: For information about how gas price can be customized in web3 see :ref:\`Gas\_Price\`. .. py:method:: Eth.set\_gas\_price\_strategy(gas\_price\_strategy) Set the selected gas price strategy. It must be a method of the signature \`\`(web3, transaction\_params)\`\` and return a gas price denominated in wei. .. py:method:: Eth.subscribe(subscription\_identifier, subscription\_params) \* Delegates to \`\`eth\_subscribe\`\` RPC Method Only available on persistent connection providers: :class:\`~web3.providers.persistent.WebSocketProvider\` and :class:\`~web3.providers.persistent.AsyncIPCProvider\`. Returns a subscription ID that can be used to track a particular subscription to, or unsubscribe from, an event. For usage examples see the docs on :ref:\`subscription-examples\`. .. code-block:: python >>> subscription\_id = await web3.eth.subscribe('newHeaders') >>> subscription\_id '0xbd63bb89e7475591a0a6fc9014307bc4' .. py:method:: Eth.unsubscribe(subscription\_id) \* Delegates to \`\`eth\_unsubscribe\`\` RPC Method Only available on persistent connection providers: :class:\`~web3.providers.persistent.WebSocketProvider\` and :class:\`~web3.providers.persistent.AsyncIPCProvider\`. Returns \`\`True\`\` if successfully unsubscribed. For usage examples see the docs on :ref:\`subscription-examples\`. .. code-block:: python >>> result = await web3.eth.unsubscribe(subscription\_id) >>> result True Filters ------- The following methods are available on the \`\`web3.eth\`\` object for interacting with the filtering API. .. py:method:: Eth.filter(filter\_params) \* Delegates to \`\`eth\_newFilter\`\`, \`\`eth\_newBlockFilter\`\`, and \`\`eth\_newPendingTransactionFilter\`\` RPC Methods. This method delegates to one of three RPC methods depending on the value of \`\`filter\_params\`\`. \* If \`\`filter\_params\`\` is the string \`\`'pending'\`\` then a new filter is registered using the \`\`eth\_newPendingTransactionFilter\`\` RPC method. This will create a new filter that will be called for each new unmined transaction that the node receives. \* If \`\`filter\_params\`\` is the string \`\`'latest'\`\` then a new filter is registered using the \`\`eth\_newBlockFilter\`\` RPC method. This will create a new filter that will be called each time the node receives a new block. \* If \`\`filter\_params\`\` is a dictionary then a new filter is registered using the \`\`eth\_newFilter\`\` RPC method. This will create a new filter that will be called for all log entries that match the provided \`\`filter\_params\`\`. This method returns a \`\`web3.utils.filters.Filter\`\` object which can then be used to either directly fetch the results of the filter or to register callbacks which will be called with each result of the filter. When creating a new log filter, the \`\`filter\_params\`\` should be a dictionary with the following keys. Note that the keys are camel-cased strings, as is expected in a JSON-RPC request. \* \`\`fromBlock\`\`: \`\`integer/tag\`\` - (optional, default: "latest") Integer block number, or one of predefined block identifiers "latest", "pending", "earliest", "safe", or "finalized". \* \`\`toBlock\`\`: \`\`integer/tag\`\` - (optional, default: "latest") Integer block number, or one of predefined block identifiers "latest", "pending", "earliest", "safe", or "finalized". \* \`\`address\`\`: \`\`string\`\` or list of \`\`strings\`\`, each 20 Bytes - (optional) Contract address or a list of addresses from which logs should originate. \* \`\`topics\`\`: list of 32 byte \`\`strings\`\` or \`\`null\`\` - (optional) Array of topics that should be used for filtering. Topics are order-dependent. This parameter can also be a list of topic lists in which case filtering will match any of the provided topic arrays. .. note:: Though \`\`"latest"\`\` and \`\`"safe"\`\` block identifiers are not yet part of the specifications for \`\`eth\_newFilter\`\`, they are supported by web3.py and may or may not yield expected results depending on the node being accessed. See :doc:\`./filters\` for more information about filtering. .. code-block:: python >>> web3.eth.filter('latest') \>>> web3.eth.filter('pending') \>>> web3.eth.filter({'fromBlock': 1000000, 'toBlock': 1000100, 'address': '0x6C8f2A135f6ed072DE4503Bd7C4999a1a17F824B'}) .. py:method:: Eth.get\_filter\_changes(self, filter\_id) \* Delegates to \`\`eth\_getFilterChanges\`\` RPC Method. Returns all new entries which occurred since the last call to this method for the given \`\`filter\_id\`\` .. code-block:: python >>> filter = web3.eth.filter() >>> web3.eth.get\_filter\_changes(filter.filter\_id) \[ { 'address': '0xDc3A9Db694BCdd55EBaE4A89B22aC6D12b3F0c24', 'blockHash': '0xb72256286ca528e09022ffd408856a73ef90e7216ac560187c6e43b4c4efd2f0', 'blockNumber': 2217196, 'data': '0x0000000000000000000000000000000000000000000000000000000000000001', 'logIndex': 0, 'topics': \['0xe65b00b698ba37c614af350761c735c5f4a82b4ab365a1f1022d49d9dfc8e930', '0x000000000000000000000000754c50465885f1ed1fa1a55b95ee8ecf3f1f4324', '0x296c7fb6ccafa3e689950b947c2895b07357c95b066d5cdccd58c301f41359a3'\], 'transactionHash': '0xfe1289fd3915794b99702202f65eea2e424b2f083a12749d29b4dd51f6dce40d', 'transactionIndex': 1, }, ... \] .. py:method:: Eth.get\_filter\_logs(self, filter\_id) \* Delegates to \`\`eth\_getFilterLogs\`\` RPC Method. Returns all entries for the given \`\`filter\_id\`\` .. code-block:: python >>> filter = web3.eth.filter() >>> web3.eth.get\_filter\_logs(filter.filter\_id) \[ { 'address': '0xDc3A9Db694BCdd55EBaE4A89B22aC6D12b3F0c24', 'blockHash': '0xb72256286ca528e09022ffd408856a73ef90e7216ac560187c6e43b4c4efd2f0', 'blockNumber': 2217196, 'data': '0x0000000000000000000000000000000000000000000000000000000000000001', 'logIndex': 0, 'topics': \['0xe65b00b698ba37c614af350761c735c5f4a82b4ab365a1f1022d49d9dfc8e930', '0x000000000000000000000000754c50465885f1ed1fa1a55b95ee8ecf3f1f4324', '0x296c7fb6ccafa3e689950b947c2895b07357c95b066d5cdccd58c301f41359a3'\], 'transactionHash': '0xfe1289fd3915794b99702202f65eea2e424b2f083a12749d29b4dd51f6dce40d', 'transactionIndex': 1, }, ... \] .. py:method:: Eth.uninstall\_filter(self, filter\_id) \* Delegates to \`\`eth\_uninstallFilter\`\` RPC Method. Uninstalls the filter specified by the given \`\`filter\_id\`\`. Returns boolean as to whether the filter was successfully uninstalled. .. code-block:: python >>> filter = web3.eth.filter() >>> web3.eth.uninstall\_filter(filter.filter\_id) True >>> web3.eth.uninstall\_filter(filter.filter\_id) False # already uninstalled. .. py:method:: Eth.get\_logs(filter\_params) This is the equivalent of: creating a new filter, running :meth:\`~Eth.get\_filter\_logs\`, and then uninstalling the filter. See :meth:\`~Eth.filter\` for details on allowed filter parameters. Contracts --------- .. py:method:: Eth.contract(address=None, contract\_name=None, ContractFactoryClass=Contract, \*\*contract\_factory\_kwargs) If \`\`address\`\` is provided, then this method will return an instance of the contract defined by \`\`abi\`\`. The address may be a checksum string, or an ENS name like \`\`'mycontract.eth'\`\`. .. code-block:: python from web3 import Web3 w3 = Web3(...) contract = w3.eth.contract(address='0x000000000000000000000000000000000000dEaD', abi=...) # alternatively: contract = w3.eth.contract(address='mycontract.eth', abi=...) .. note:: If you use an ENS name to initialize a contract, the contract will be looked up by name on each use. If the name could ever change maliciously, first :ref:\`ens\_get\_address\`, and then create the contract with the checksum address. If \`\`address\`\` is \*not\* provided, the newly created contract class will be returned. That class will then be initialized by supplying the address. .. code-block:: python from web3 import Web3 w3 = Web3(...) Contract = w3.eth.contract(abi=...) # later, initialize contracts with the same metadata at different addresses: contract1 = Contract(address='0x000000000000000000000000000000000000dEaD') contract2 = Contract(address='mycontract.eth') \`\`contract\_name\`\` will be used as the name of the contract class. If it is \`\`None\`\` then the name of the \`\`ContractFactoryClass\`\` will be used. \`\`ContractFactoryClass\`\` will be used as the base Contract class. The following arguments are accepted for contract class creation. :param abi: Application Binary Interface. Usually provided since an \`\`abi\`\` is required to interact with any contract. :type abi: ABI :param asm: Assembly code generated by the compiler :param ast: Abstract Syntax Tree of the contract generated by the compiler :param bytecode: Bytecode of the contract generated by the compiler :param bytecode\_runtime: Bytecode stored at the contract address, excludes the constructor and initialization code :param clone\_bin: :param dev\_doc: :param decode\_tuples: Optionally convert tuples/structs to named tuples :param interface: :param metadata: Contract Metadata generated by the compiler :param opcodes: Opcodes for the contract generated by the compiler :param src\_map: :param src\_map\_runtime: :param user\_doc: :return: Instance of the contract :rtype: Contract :raises TypeError: If the address is not provided :raises AttributeError: If the contract class is not initialized See the :doc:\`web3.contract\` documentation for more information about Contracts. .. py:method:: Eth.set\_contract\_factory(contractFactoryClass) Modify the default contract factory from \`\`Contract\`\` to \`\`contractFactoryClass\`\`. Future calls to \`\`Eth.contract()\`\` will then default to \`\`contractFactoryClass\`\`. --- # Unknown Release Notes ============= v7 Breaking Changes Summary See the :ref:\`v7 Migration Guide\` .. towncrier release notes start web3.py v7.6.1 (2024-12-18) --------------------------- Bugfixes ~~~~~~~~ - Include an end-of-line delimiter when sending messages via IPC with the \`\`IPCProvider\`\` and \`\`AsyncIPCProvider\`\`. (\`#3537 \`\_\_) - Contract functions and events no longer initialize for each call. Retrieval of overloaded functions and events is now deterministic. Any ambiguity will result in an exception being raised. (\`#3540 \`\_\_) - Bump the eth-tester version to one that works in the tester dependency extras (\`#3555 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update ENS-related links (\`#3563 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Upgrade Geth Fixture to 1.14.12 (\`#3533 \`\_\_) - Delete \`\`ARCHITECTURE.md\`\` as unused (\`#3547 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3525 \`\_\_ web3.py v7.6.0 (2024-11-22) --------------------------- Bugfixes ~~~~~~~~ - Update the \`ContractEvents\` class to raise a \`NoABIFound\` exception if the \`Contract\` is initialized without an \`ABI\` and an attempt to access an event is made. This exception makes \`ContractEvents\` consistent with \`ContractFunctions\`. (\`#3491 \`\_\_) Features ~~~~~~~~ - Contracts with overloaded functions or events are now supported. The Contract initializes functions and events using an identifier to distinguish between them. The identifier is the function or event signature, which consists of the name and the parameter types. (\`#3491 \`\_\_) - - Support for \`\`w3.eth.blob\_base\_fee\`\` - Async support for \`\`w3.eth.blob\_base\_fee\`\` (\`#3527 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Pin \`\`websockets<14\`\` due to breaking changes (\`#3529 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3491 \`\_\_ web3.py v7.5.0 (2024-11-06) --------------------------- Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Polish docs index page (\`#3522 \`\_\_) Features ~~~~~~~~ - Add support for Geth Debug traceTransaction. (\`#3334 \`\_\_) - New contract methods to obtain event elements from a contract ABI using a name, signature, selector, or topic. (\`#3472 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Add python 3.13 support (\`#3493 \`\_\_) - Compile test contracts with newly released Solidity \`\`v0.8.28\`\` to ensure compatibility. (\`#3515 \`\_\_) web3.py v7.4.0 (2024-10-16) --------------------------- Bugfixes ~~~~~~~~ - Fix a bug where CCIP-Read expected a \`\`{sender}\`\` in the url for a POST request. If \`\`{data}\`\` is missing from the url, assume a POST request is being made regardless of whether \`\`{sender}\`\` is present. (\`#3291 \`\_\_) - Fix a bug where non-mainnet chains could not cache requests based on missing \`\`finalized\`\` block number. (\`#3508 \`\_\_) - Send \`\`json\`\`, not \`\`data\`\` with CCIP-Read POST requests. (\`#3512 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update the request caching documentation to clarify on when to reach for request caching and how to configure the request validation threshold for certain endpoints. (\`#3508 \`\_\_) Features ~~~~~~~~ - Allow a time interval, in seconds, to be used as the \`\`request\_cache\_validation\_threshold\`\` for request caching. Keep a list of internal default values based on the chain id for some of the bigger chains. (\`#3508 \`\_\_) web3.py v7.3.1 (2024-10-14) --------------------------- Bugfixes ~~~~~~~~ - Properly wrap \`\`AsyncBeacon.request\_timeout\`\` float in a \`\`aiohttp.ClientTimeout\`\` when making requests. (\`#3503 \`\_\_) - Changes related to an \`eth-typing\` bugfix, input types for \`\`ABIEvent\`\`: \`\`ABIComponent\`\` -> \`\`ABIComponentIndexed\`\`. (\`#3510 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix \`\`EthereumTesterProvider\`\` signature in docs, added an \`\`eth\_tester\`\` example. (\`#3500 \`\_\_) - Fix \`pip install -e ".\[dev\]"\` command in linux README. (\`#3505 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Update the ENSIP-15 to the latest spec and update the test suite. (\`#3501 \`\_\_) web3.py v7.3.0 (2024-09-25) --------------------------- Bugfixes ~~~~~~~~ - Base default \`\`maxFeePerGas\`\` calculation off of existing \`\`maxPriorityFeePerGas\`\` key instead of separate RPC call (\`#3052 \`\_\_) - Add back dependency extra for 'tester'. (\`#3480 \`\_\_) - Fix a bug where sensitive requests that make use of block data should not be cached until some validation threshold deems it is safe to do so, when request caching is turned on. (\`#3483 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update \`\`contract.encode\_abi\`\` signature in docs and migration guide (\`#3473 \`\_\_) - Update documentation around \`\`SignAndSendRawMiddlewareBuilder\`\` injection into the middleware onion. It should be injected lower in the stack than any middleware that modifies the transaction, in order to ensure those modified fields are signed. (\`#3488 \`\_\_) - Docs cleanups related to \`\`test\`\` vs \`\`tester\`\` install extras. (\`#3496 \`\_\_) Features ~~~~~~~~ - Add a configuration for request caching that sets a threshold for validating cached requests that make use of block data. This can be turned off altogether by setting the threshold to \`\`None\`\`. (\`#3483 \`\_\_) - Add a configuration option for the \`\`read\_buffer\_limit\`\` for \`\`AsyncIPCProvider\`\` in order to control the expected message size limit (defaults to 20MB). Add \`\`ReadBufferLimitReached\`\` for when the read limit is reached, extend from \`\`PersistentConnectionError\`\`. (\`#3492 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Test warning cleanup (\`#3468 \`\_\_) - Re-compile test contracts with recently released Solidity \`\`v0.8.27\`\`. (\`#3475 \`\_\_) - Re-organize the install extras. Re-define the \`\`test\`\` extra to always include the \`\`tester\`\` extra since it's needed for testing. (\`#3495 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3490 \`\_\_ Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Improve logic for reading from the async IPC socket in order to properly handle and adjust the handling of large messages. This improves reading speeds in general. (\`#3492 \`\_\_) web3.py v7.2.0 (2024-08-29) --------------------------- Bugfixes ~~~~~~~~ - Fix a bug with newer \`\`hexbytes\`\` versions that yield non-0x-prefixed hex for \`\`HexBytes\`\`: \`\`raw\_transaction.hex()\`\` -> \`\`raw\_transaction.to\_0x\_hex()\`\`. (\`#3471 \`\_\_) Features ~~~~~~~~ - HTTPProvider and AsyncHTTPProvider's get\_request\_headers is now available on both the class and the instance (\`#3467 \`\_\_) web3.py v7.1.0 (2024-08-28) --------------------------- Bugfixes ~~~~~~~~ - Specify a unique \`\`\_\_hash\_\_()\`\` for unhashable \`\`Web3Middleware\`\` types and use this hash as the middleware onion key when a name is not provided for the middleware. This fixes a bug where different middleware were given the same name and therefore raised errors. (\`#3463 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix bug in filters example code (\`#3455 \`\_\_) - Update \`\`v6\`\` -> \`\`v7\`\` migration guide with examples for importing and adding middleware, as well as examples on how to use the \`\`MiddlewareBuilder\`\` classes. (\`#3462 \`\_\_) Features ~~~~~~~~ - Add sync and async support for beacon \`\`/eth/v1/beacon/blob\_sidecars\`\` endpoint. (\`#3407 \`\_\_) - Allow user to call ContractFunctions without parentheses (\`#3444 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Refactor and DRY up CI run setup and reduce surface area for errors. Include pre-releases in CI runs for internally maintained libraries to try and catch any conflicts. (\`#3452 \`\_\_) - Bump \`py-geth\` to \`\`>=5.0.0\`\` from \`\`>=5.0.0b1\`\` now that stable has been released. This only matters for the \`\`test\`\` install extra (CI and dev purposes). (\`#3458 \`\_\_) web3.py v7.0.0 (2024-08-21) --------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Update \`eth-utils\` and \`eth-typing\` to latest major versions \`eth-utils\` v5 and \`eth-typing\` v5 (\`#3450 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Improve batch request documentation. (\`#3448 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Fix Release Notes formatting (\`#3454 \`\_\_) web3.py v7.0.0-beta.9 (2024-08-01) ---------------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ \* Upgrades to use latest \`\`ABI\`\` utilities and typings from \`\`eth-utils\`\` and \`\`eth-typing\`\`. \* Typings for \`\`ABI\`\` components are now available in the \`\`eth-typing\`\` package. \`\`ABI\`\` types previously in \`\`web3.types\`\` have been removed. \* New versions of existing ABI functions were added to \`\`eth-utils\`\` and are now exposed in \`web3.py\` via \`\`web3.utils.abi\`\`. \* ABI exceptions have been renamed in \`\`web3.exceptions\`\`. The \`\`ABIEventFunctionNotFound\`\` and \`\`FallbackNotFound\`\` exceptions have been removed. Use \`\`ABIEventNotFound\`\` and \`\`ABIFallbackNotFound\`\` instead. \* \`\`MismatchedABI\`\` exceptions are raised instead of a \`\`Web3ValidationError\`\` for ABI related errors. \* \`\`encode\_abi\`\` arguments have been updated to use \`\`abi\_element\_name\`\` instead of \`\`fn\_name\`\`. (\`#3408 \`\_\_) - Remove \`\`Web3ValidationError\`\` dependence / inheritance from \`eth-utils\` \`\`ValidationError\`\`. (\`#3443 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Use autodoc and update ABI functions with docstrings and doctests. (\`#3408 \`\_\_) Features ~~~~~~~~ \* Utilities to extract function and event \`\`ABI\`\` attributes from a contract. Utilities in the \`\`web3.utils.abi\`\` module parse ABI elements and check encodability of provided arguments. ABI functions in \`\`eth-utils\`\` are exposed by the \`\`web3.utils.abi\`\` module. \* \`\`get\_abi\_element\_info\`\` returns an \`\`ABIElementInfo\`\` TypedDict with the \`\`abi\`\`, \`\`selector\`\`, and \`\`arguments\`\`. \* \`\`get\_abi\_element\`\` returns the \`\`ABI\`\` of a function, event, or error given the name and arguments. \* \`\`check\_if\_arguments\_can\_be\_encoded\`\` returns true if the arguments can be encoded with the given ABI. \* \`\`get\_event\_abi\`\` returns the \`\`ABI\`\` of an event given the name. \* \`\`get\_event\_log\_topics\`\` returns the log topics of an event given the name. \* \`\`log\_topics\_to\_bytes\`\` returns the log topics as bytes. (\`#3408 \`\_\_) - Add explicit stream kwarg to HTTPProvider so that timeout can be more finely tuned. (\`#3428 \`\_\_) - Implement a \`\`RequestTimedOut\`\` exception, extending from \`\`Web3RPCError\`\`, for when requests to the node time out. (\`#3440 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Run \`\`mypy\`\` locally using \`\`pre-commit\`\` hook, instead of within \`\`pre-commit\`\` container (\`#3414 \`\_\_) - Mitigate inconsistently failing tests for CI runs with appropriate \`\`flaky\`\` or \`\`pytest.mark.xfail()\`\` decorators. (\`#3440 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3408 \`\_\_, \`#3445 \`\_\_ web3.py v7.0.0-beta.8 (2024-07-24) ---------------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Refactor the public \`\`socket\`\` api for persistent connection providers to properly define \`\`send()\`\`, \`\`recv()\`\`, and \`\`make\_request()\`\` (send and wait for response) methods for interacting with the open socket. (\`#3433 \`\_\_) - Format entries in \`\`accessList\`\` \`\`storageKeys\`\` to be \`\`HexStr\`\` instead of \`\`HexBytes\`\` (\`#3434 \`\_\_) Bugfixes ~~~~~~~~ - Handle \`\`ConnectionClosedOK\`\` case for \`\`WebSocketProvider\`\`. If a persistent connection is closed gracefully, log and raise a silent \`\`PersistentConnectionClosedOK\`\` exception, triggering an end to the message listener task and breaking out of the \`\`process\_subscriptions()\`\` iterator. (\`#3432 \`\_\_) Features ~~~~~~~~ - Add \`\`popitem()\`\` functionality to the \`\`SimpleCache\`\` class as well as an async utility method to wait for the next item, \`\`async\_await\_and\_popitem()\`\`. (\`#3433 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Refactor some common logic for persistent connection providers back into the base \`\`PersistentConnectionProvider\`\` class to reduce code duplication and improve maintainability. (\`#3433 \`\_\_) web3.py v7.0.0-beta.7 (2024-06-26) ---------------------------------- Bugfixes ~~~~~~~~ - Change the \`\`exception\_retry\_configuration\`\` typing on http providers to be an \`\`Optional\`\`, as setting this property to \`\`None\`\` effectively turns off retries on exceptions for requests. (\`#3412 \`\_\_) - A bugfix, pre-release, to update the \`\`Beacon\`\` APIs (sync and async) to properly use the new \`\`HTTPSessionManager\`\`. (\`#3421 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add an \`\`eth\_subscribe\`\` example to the events guide (\`#3403 \`\_\_) Features ~~~~~~~~ - Properly handle \`\`InsufficientDataBytes\`\` errors when processing receipts (\`#3388 \`\_\_) - Provide explicit \`\`\_\_all\_\_\`\` exports for providers in \`web3/providers/\_\_init\_\_.py\`; update \`web3/\_\_init\_\_.py\` to include all provider classes including base classes. (\`#3409 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Re-compile test contracts with Solidity v0.8.25 to ensure compatibility. (\`#3307 \`\_\_) - Increase allowable range of eth-tester: 0.11.x and 0.12.x (\`#3400 \`\_\_) - Remove uses of signHash in tests, require eth-account >=0.13.0 in doctests (\`#3404 \`\_\_) - Use a \`\`HTTPSessionManager\`\` to manage sessions for http providers, rather than have them share a single session manager / cache. (\`#3412 \`\_\_) web3.py v7.0.0-beta.6 (2024-05-15) ---------------------------------- Bugfixes ~~~~~~~~ - Properly propagate exceptions from the message listener task to the main loop for persistent connection providers. (\`#3378 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Prunes the node onboarding text (\`#3371 \`\_\_) - Stale example cleanup (\`#3374 \`\_\_) - Merge migration guides into one page (\`#3379 \`\_\_) - Simplify titles of docs guides (\`#3381 \`\_\_) - Move ABI Types guide into the Troubleshooting page (\`#3382 \`\_\_) - Distribute examples into relevant guides and delete Example page (\`#3383 \`\_\_) - Add subscribe/unsubscribe API (\`#3386 \`\_\_) - Introduces batch request API (\`#3393 \`\_\_) Features ~~~~~~~~ - Add support for request batching via \`\`w3.batch\_requests()\`\` context manager (sync and async). (\`#3370 \`\_\_) - Allow request cache configuration on provider \`\`\_\_init\_\_()\`\` for all provider classes. (\`#3395 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Merge the python project template, notably adding python 3.12 support (\`#3363 \`\_\_) - Increase python-asyncio dependency to be >=0.21.2,<0.23 (\`#3369 \`\_\_) - Bump to \`\`mypy==1.10.0\`\` for \`\`pre-commit\`\` (\`#3377 \`\_\_) - Move signed.rawTransaction -> signed.raw\_transaction in eth module tests (\`#3380 \`\_\_) web3.py v7.0.0-beta.5 (2024-04-26) ---------------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Snake-case remaining arguments \`\`fromBlock\`\`, \`\`toBlock\`\`, and \`\`blockHash\`\` in contract and filter methods where they are passed in as kwargs. (\`#3353 \`\_\_) - Employ an exponential backoff strategy using the \`\`backoff\_factor\`\` in \`\`ExceptionRetryConfiguration\`\` for \`\`HTTPProvider\`\` and \`\`AsyncHTTPProvider\`\`. Reduce the default initial delay to \`\`0.125\`\` seconds. (\`#3358 \`\_\_) - Validate JSON-RPC responses more strictly against the JSON-RPC 2.0 specifications. \`\`BlockNumberOutofRange\`\` -> \`\`BlockNumberOutOfRange\`\`. (\`#3359 \`\_\_) Deprecations ~~~~~~~~~~~~ - \`\`messageHash\`\` and \`\`rawTransaction\`\` from \`\`eth-account\`\` have been deprecated for snake\_case versions (\`#3348 \`\_\_) Features ~~~~~~~~ - Raise \`\`Web3RPCError\`\` on JSON-RPC errors rather than \`\`Web3ValueError\`\`. Raise \`\`MethodNotSupported\`\` exception when a method is not supported within \*web3.py\*; keep \`\`MethodUnavailable\`\` for when a method is not available on the current provider (JSON-RPC error). (\`#3359 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Bump \`\`eth-account\`\` dependency to \`\`>=0.12.2\`\` (\`#3348 \`\_\_) Removals ~~~~~~~~ - Remove the deprecated \`\`personal\`\` namespace and all references to it. (\`#3350 \`\_\_) web3.py v7.0.0-beta.4 (2024-04-11) ---------------------------------- Bugfixes ~~~~~~~~ - Fix misused call to \`endpoint\_uri\` for all cases of \`\`PersistentConnectionProvider\`\` by being able to retrieve either the \`\`ipc\_path\`\` or the \`\`endpoint\_uri\`\` from the base class with \`\`endpoint\_uri\_or\_ipc\_path\`\` property. (\`#3319 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix \`\`eth\_createAccessList\`\` docs to reflect the correct behavior. (\`#3327 \`\_\_) Features ~~~~~~~~ - Use in-house exception wrappers for common Python exceptions, such as \`\`ValueError\`\`, \`\`TypeError\`\`, \`\`AttributeError\`\`, and \`\`AssertionError\`\`, for better control over exception handling. (\`#3300 \`\_\_) - Add request formatter for \`\`maxFeePerBlobGas\`\` when sending blob transactions. Add formatters for \`\`blobGasPrice\`\` and \`\`blobGasUsed\`\` for \*eth\_getTransactionReceipt\*. (\`#3322 \`\_\_) - Add formatters to ensure that the result of a \`\`eth\_createAccessList\`\` response can be plugged directly into an \`\`accessList\`\` in a transaction. (\`#3327 \`\_\_) - Add Cancun support to \`\`EthereumTesterProvider\`\`; update Cancun-related fields in some internal types. (\`#3332 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Use \`\`pre-commit\`\` for linting, run updated lint tools and fix errors (\`#3297 \`\_\_) - Dependency updates: \`\`eth-abi>=5.0.1\`\`, \`\`eth-account>=0.12.0\`\` \`\`eth-typing>=4.0.0\`\` and \`\`hexbytes>=1.2.0\`\` with relevant changes to support these. (\`#3298 \`\_\_) - Remove code conditionally necessary for \`\`python<=3.7\`\` (\`#3317 \`\_\_) web3.py v7.0.0-beta.3 (2024-03-28) ---------------------------------- Bugfixes ~~~~~~~~ - Fix \`\`process\_log()\`\` when parsing logs for events with indexed and non-indexed inputs. \`\`get\_event\_data()\`\` now compares log topics and event ABIs as hex values. (\`#3289 \`\_\_) - Fix \`\`process\_log\`\` for \`\`HexStr\`\` inputs. Explicit type coercion of entry \`\`topics\`\` and \`\`data\`\` values. (\`#3293 \`\_\_) - Fix typing for json data argument to \`\`eth\_signTypedData\`\`. (\`#3308 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add note about middlewares change to v7 migration guide. (\`#3277 \`\_\_) - Rearrange v7 migration guide and include upgrade path from WebsocketProviderV2 (\`#3310 \`\_\_) Features ~~~~~~~~ - Add support for \`\`eth\_getRawTransactionByHash\`\` RPC method (\`#3247 \`\_\_) - Add \`\`user\_message\`\` kwarg for human readable \`\`Web3Exception\`\` messages. (\`#3263 \`\_\_) - Add formatters for type 3 transaction fields \`\`maxFeePerBlobGas\`\` and \`\`blobVersionedHashes\`\`. (\`#3314 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Add a daily CI run (\`#3272 \`\_\_) - Add linting for non-inclusive language with \`\`blocklint\`\`. (\`#3275 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3304 \`\_\_ Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Importing \`\`ens.\_normalization\`\` is deferred until the first call of \`\`ens.utils.normalize\_name\`\` in order to speed up \`\`import web3\`\`. (\`#3285 \`\_\_) - Utilize \`\`async\`\` functionality when popping responses from request manager cache for persistent connection providers. (\`#3306 \`\_\_) Removals ~~~~~~~~ - Remove \`\`Contract.encodeABI()\`\` in favor of \`\`Contract.encode\_abi()\`\` to follow standard conventions. (\`#3281 \`\_\_) web3.py v7.0.0-beta.2 (2024-03-11) ---------------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Move \`\`middlewares\`\` -> \`\`middleware\`\` (\`#3276 \`\_\_) Bugfixes ~~~~~~~~ - Fix/update methods and decorators in \`\`web3/\_utils/abi.py\`\` to address issues raised by \`\`mypy\`\` (\`#3269 \`\_\_) - Catch all types of \`\`eth-abi\`\` \`\`DecodingError\`\` in \`\`EthereumTesterProvider->\_make\_request()\`\` (\`#3271 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Remove annual user survey prompt from docs (\`#3218 \`\_\_) - Introduce feedback form banner prompt on docs (\`#3253 \`\_\_) - Refresh of the middleware docs (\`#3266 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3259 \`\_\_, \`#3262 \`\_\_ Removals ~~~~~~~~ - Remove the \`\`ethpm\`\` module and related docs, tests, and dependencies (\`#3261 \`\_\_) web3.py v7.0.0-beta.1 (2024-02-28) ---------------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Refactor the middleware setup so that request processors and response processors are separated. This will allow for more flexibility in the future and aid in the implementation of features such as batched requests. This PR also closes out a few outstanding issues and will be the start of the breaking changes for \`web3.py\` \`\`v7\`\`. Review PR for a full list of changes. (\`#3169 \`\_\_) - Use a message listener background task for \`\`WebsocketProviderV2\`\` rather than relying on \`\`ws.recv()\`\` blocking. Some breaking changes to API, notably \`\`listen\_to\_websocket\`\` -> \`\`process\_subscriptions\`\`. (\`#3179 \`\_\_) - Drop dependency on \`\`lru-dict\`\` library. (\`#3196 \`\_\_) - Drop support for python 3.7 (\`#3198 \`\_\_) - Return iterable of \`\`ABIFunction\`\`s from the \`\`BaseContractFunctions\`\` iterator. (\`#3200 \`\_\_) - Name changes internal to the library related to \`\`v7\`\`: \`\`WebsocketProvider\`\` -> \`\`LegacyWebSocketProvider\`\`, \`\`WebsocketProviderV2\`\` -> \`\`WebSocketProvider\`\` (\`#3225 \`\_\_) - \`\`CallOverride\`\` type change to \`\`StateOverride\`\` to reflect better the type name for the state override. \`\`eth\_call\`\` is also not the only method with this param, making the name more generic. (\`#3227 \`\_\_) - Rename \`beacon/main.py\` -> \`beacon/beacon.py\` (\`#3233 \`\_\_) - \`\`EthereumTesterProvider\`\` now returns \`\`input\`\` for \`eth\_getTransaction\*\` for better consistency with JSON-RPC spec. (\`#3235 \`\_\_) - Change the signature for the async version of \`\`wait\_for\_transaction\_receipt()\`\` to use \`\`Optional\[float\]\`\` instead of \`\`float\`\`. (\`#3237 \`\_\_) - \`\`get\_default\_ipc\_path()\`\` and \`\`get\_dev\_ipc\_path()\`\` now return the path value without checking if the \`\`geth.ipc\`\` file exists. (\`#3245 \`\_\_) Bugfixes ~~~~~~~~ - Fix return type of \`\`AsyncContract.constructor\`\` (\`#3192 \`\_\_) - Handle new geth errors related to waiting for a transaction receipt while transactions are still being indexed. (\`#3216 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Documentation was updated to reflect early changes to \`\`v7\`\` from \`\`v6\`\`. A \`\`v6\`\` -> \`\`v7\`\` migration guide was also started and will be added to as \`\`v7\`\` breaking changes are introduced. (\`#3211 \`\_\_) - Remove ENS v6 breaking change warning from v7 (\`#3254 \`\_\_) Features ~~~~~~~~ - Add AsyncIPCProvider (\`#2984 \`\_\_) - Implement \`\`state\_override\`\` parameter for \`\`eth\_estimateGas\`\` method. (\`#3164 \`\_\_) - Upgrade \`eth-tester\` to \`\`v0.10.0-b.1\`\` and turn on \`\`eth\_feeHistory\`\` support for \`\`EthereumTesterProvider\`\`. (\`#3172 \`\_\_) - Add formatters for new \`\`Cancun\`\` network upgrade block header fields: \`\`blobGasUsed\`\`, \`\`excessBlobGas\`\`, and \`\`parentBeaconBlockRoot\`\`. (\`#3223 \`\_\_) - Contract event \`\`get\_logs\`\` results sorted by each \`\`ContractEvent\`\` \`\`logIndex\`\`. (\`#3228 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Create test fixture for latest \`\`geth\`\` version. Run tests with \`\`geth\`\` in \`\`--dev\`\` mode. (\`#3191 \`\_\_) - Validate geth version used to generate the integration test fixture against the version in the binary that is used to run the tests. (\`#3193 \`\_\_) - Internal change to \`\`WebsocketProviderV2\`\` before release: raise exceptions in message listener task by default; opting to silence them via a flag. (\`#3202 \`\_\_) - Compile contracts with and test against new Solidity version \`\`v0.8.24\`\`. (\`#3204 \`\_\_) - Formatting updates for \`\`black==24.1.0\`\`. (\`#3207 \`\_\_) - Allow HTTP provider request retry configuration to be turned off appropriately. Internal change since \`\`v7\`\` has not yet been released. (\`#3211 \`\_\_) - Upgraded geth fixture version (\`#3231 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#2964 \`\_\_, \`#3248 \`\_\_ Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Remove call to \`\`parse\_block\_identifier\`\` when initializing \`\`ContractCaller\`\` functions. (\`#3257 \`\_\_) Removals ~~~~~~~~ - \`\`normalize\_request\_parameters\`\` middleware was in a stale state and not being used or tested. This middleware has been removed. (\`#3211 \`\_\_) - Remove deprecated \`\`geth.miner\`\` namespace and methods. (\`#3236 \`\_\_) web3.py v6.14.0 (2024-01-10) ---------------------------- Bugfixes ~~~~~~~~ - Change \`\`fee\_history\`\` default behavior. If \`\`reward\_percentiles\`\` arg not included, pass it to the provider as an empty list instead of \`\`None\`\`. (\`#3185 \`\_\_) - Use \`\`importlib.metadata\`\` for version info if python>=3.8 (\`#3187 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Remove docs reference for removed \`\`protocol\_version\`\` RPC method (\`#3183 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Re-define how async vs sync core test suites are ran. (\`#3180 \`\_\_) - Add basic import and version tests for the \`\`web3\`\` module (\`#3187 \`\_\_) web3.py v6.13.0 (2023-12-20) ---------------------------- Features ~~~~~~~~ - Implement async \`\`eth\_createAccessList\`\` RPC method to create an EIP-2930 access list. (\`#3167 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Add flaky async Geth integration tests to CI (\`#3170 \`\_\_) - Fix wrong test reference for \`\`EthereumTesterProvider\`\` integration test suite. (\`#3171 \`\_\_) - Small fix for integration tests for \`\`tox\`\` to recognize independent patterns for each test run. (\`#3173 \`\_\_) web3.py v6.12.0 (2023-12-11) ---------------------------- Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Make downloadable versions of docs available in \`\`pdf\`\`, \`\`htmlzip\`\`, and \`\`epub\`\` formats (\`#3153 \`\_\_) - Add 2023 user survey fine art banner in the docs (\`#3159 \`\_\_) - Polish the community resources docs page (\`#3162 \`\_\_) Features ~~~~~~~~ - Implement \`\`createAccessList\`\` RPC endpoint to create an EIP-2930 access list. (\`#2381 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Run flaky eth-tester tests on CI (\`#3157 \`\_\_) - Pin \`\`pytest-asyncio\`\` dependency to <0.23 (\`#3160 \`\_\_) web3.py v6.11.4 (2023-11-27) ---------------------------- Bugfixes ~~~~~~~~ - Fix collision of \`\`w3\`\` variable when initializing contract with function of the same name (\`#3147 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3148 \`\_\_ web3.py v6.11.3 (2023-11-08) ---------------------------- Bugfixes ~~~~~~~~ - When coming back through the middleware onion after a request is made, we have the response \`\`id\`\`. Use it to match to the cached request information and process the response accordingly. (\`#3140 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Adds Discord bot template repo to Resources page (\`#3143 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Additional contract \`\`abi\`\` documentation to make it a clear requirement for contract instances. (\`#2539 \`\_\_) - Fix type annotations for \`\`web3\`\` constants. (\`#3138 \`\_\_) - Add upper pin to deprecated dependency \`\`lru-dict\`\` whose new minor version release introduced a typing issue with CI lint builds. (\`#3144 \`\_\_) - Recompile test contracts with new Solidity version \`\`v0.8.23\`\` to ensure compatibility. (\`#3146 \`\_\_) web3.py v6.11.2 (2023-10-30) ---------------------------- Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix formatting in documentation for creating an account. (\`#3128 \`\_\_) - Fix broken links for Apeworx and Sepolia faucet (\`#3130 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Speed up the core test suite by splitting up sync and async tests. This reduces the CI build times to ~8min from ~12min. (\`#3111 \`\_\_) - Re-compile test contracts with Solidity \`\`v0.8.22\`\` to ensure compatibility with this latest Solidity version. (\`#3134 \`\_\_) - Improvements on yielding to the event loop while searching in response caches and calling \`\`recv()\`\` on the websocket connection for \`\`WebSocketProviderV2\`\`. (\`#3135 \`\_\_) web3.py v6.11.1 (2023-10-18) ---------------------------- Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update \`\`WebsocketProviderV2\`\` documentation. Document a general overview of the \`\`RequestProcessor\`\` class and its internal caches. (\`#3125 \`\_\_) Features ~~~~~~~~ - Properly define an \`\`\_\_await\_\_()\`\` method on the \`\`\_PersistentConnectionWeb3\`\` class so a persistent connection may be initialized using the \`\`await\`\` pattern. Integration tests added for initializing the persistent connection using the \`\`await\`\` pattern. (\`#3125 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Updates and refactoring for the \`\`WebsocketProviderV2\`\` class and its internal supporting classes and logic. Separation of one-to-one and one-to-many request responses. Storing of one-to-many responses in a \`\`deque\`\` and one-to-one responses in a \`\`SimpleCache\`\` class. Provide an async lock around the websocket \`\`recv()\`\`. (\`#3125 \`\_\_) - Add upper pin to \`\`hexbytes\`\` dependency to due incoming breaking change (\`#3127 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#3114 \`\_\_, \`#3129 \`\_\_ web3.py v6.11.0 (2023-10-11) ---------------------------- Breaking Changes (to Beta APIs) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Refactor the async iterator pattern for message streams from the websocket connection for \`\`WebsocketProviderV2\`\` to a proper async iterator. This allows for a more natural usage of the iterator pattern and mimics the behavior of the underlying \`\`websockets\`\` library. (\`#3116 \`\_\_) Bugfixes ~~~~~~~~ - Use hashes to compare equality of two \`\`AttributeDict\`\` classes (\`#3104 \`\_\_) - Fix issues with formatting middleware, such as \`\`async\_geth\_poa\_middleware\`\` and subscription responses for \`\`WebsocketProviderV2\`\`. (\`#3116 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Change \`\`docker-compose\`\` to \`\`docker compose\`\` in the Contributing docs examples. (\`#3107 \`\_\_) - Updates to the \`\`WebsocketProviderV2\`\` documentation async iterator example for iterating over a persistent stream of messages from the websocket connection via \`\`async for\`\`. (\`#3116 \`\_\_) - Update outdated node and private key management verbiage. (\`#3117 \`\_\_) Features ~~~~~~~~ - Allow passing in a \`\`float\`\` for a \`\`request\_timeout\`\` for requests for the \`\`Beacon\`\` class. Update some Beacon API endpoints (sync and async). (\`#3106 \`\_\_) - Add \`\`allow\_list\`\` kwarg for \`\`exception\_retry\_middleware\`\` to allow for a custom list of RPC endpoints. Add a sleep between retries and a customizable \`\`backoff\_factor\`\` to control the sleep time between retry attempts. (\`#3120 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Refactor logic for the \`\`input\_munger()\`\` method on the \`\`Method\`\` class. (\`#2987 \`\_\_) - Pin mypy to v1.4.1, the last to support py37 (\`#3122 \`\_\_) web3.py v6.10.0 (2023-09-21) ---------------------------- Breaking Changes (to Beta APIs) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Breaking change to the API for interacting with a persistent websocket connection via \`\`AsyncWeb3\`\` and \`\`WebsocketProviderV2\`\`. This change internalizes the \`\`provider.ws\`\` property and opts for a \`\`w3.ws\`\` API achieved via a new \`\`WebsocketConnection\`\` class. With these changes, \`\`eth\_subscription\`\` messages now return the subscription id as the \`\`subscription\`\` param and the formatted message as the \`\`result\`\` param. (\`#3096 \`\_\_) Bugfixes ~~~~~~~~ - Return \`w3.eth.gas\_price\` when calculating time based gas price strategy for an empty chain. (\`#1149 \`\_\_) - Update \`LogReceipt\` and \`TxReceipt\` declarations. Remove \`LogReceipt\`'s \`payload\` and \`topic\` attributes. Refactor \`LogEntry\` to \`LogReceipt\`. (\`#3043 \`\_\_) - Fixes \`\`AsyncEth.max\_priority\_fee\_per\_gas\`\`. It wasn't falling back to \`\`eth\_feeHistory\`\` since the \`\`MethodUnavailable\`\` error was introduced. (\`#3084 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update \`\`WebsocketProviderV2\`\` documentation to reflect the new public websocket API via the \`\`WebsocketConnection\`\` class. (\`#3096 \`\_\_) Features ~~~~~~~~ - Improved error messaging for exceptions from malformed JSON-RPC responses. (\`#3053 \`\_\_) - Enable filtering by non-indexed arguments for contract event \`\`get\_logs()\`\`. (\`#3078 \`\_\_) - Add \`\`eth\_maxPriorityFeePerGas\`\` to \`\`exception\_retry\_middleware\`\` whitelist (\`#3090 \`\_\_) - Sync responses for \`\`WebsocketProviderV2\`\` open connections with requests via matching RPC \`\`id\`\` values. (\`#3096 \`\_\_) - Properly JSON encode \`\`AttributeDict\`\`, \`\`bytes\`\`, and \`\`HexBytes\`\` when sending a JSON-RPC request by utilizing the in-house \`\`Web3JsonEncoder\`\` class. (\`#3101 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Fix an issue with an IPC test present only on MacOSX. (\`#929 \`\_\_) - Ignore flake8 rule F401 (unused import) in all \`\`\_\_init\_\_.py\`\` files (\`#3097 \`\_\_) web3.py v6.9.0 (2023-08-23) --------------------------- Bugfixes ~~~~~~~~ - Fix the type for \`\`input\`\` in \`\`TxData\`\` from \`\`HexStr\`\` -> \`\`HexBytes\`\`. (\`#3074 \`\_\_) - Fix an issue with \`\`WebsocketProviderV2\`\` when responses to a request aren't found in the cache (\`\`None\`\` values). (\`#3075 \`\_\_) - Re-expose some websockets constants found in \`\`web3.providers.websocket.websocket\`\` via \`\`web3.providers.websocket\`\`. (\`#3076 \`\_\_) - Return \`\`NotImplemented\`\` constant, rather than raising \`\`NotImplementedError\`\` for \`\`NamedElementOnion.\_\_add\_\_()\`\`, based on Python standards. (\`#3080 \`\_\_) - Only release \`\`async\_lock\`\` if it's locked to begin with. (\`#3083 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add MEV blocking tutorial to Resources docs page (\`#3072 \`\_\_) - Fix documentation around current state of \`\`get\_logs()\`\` usage and arguments. (\`#3073 \`\_\_) - Add an Ape hackathon kit to Resources documenation page (\`#3082 \`\_\_) web3.py v6.8.0 (2023-08-02) --------------------------- Bugfixes ~~~~~~~~ - Fix the type for the optional param asking for "full transactions" when subscribing to \`\`newPendingTransactions\`\` via \`\`eth\_subscribe\`\` to \`\`bool\`\`. (\`#3067 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Change docs to reflect AsyncHTTPProvider does accept ENS names now (\`#3070 \`\_\_) Features ~~~~~~~~ - Return structured JSON-RPC errors for missing or unimplemented eth-tester methods. (\`#3061 \`\_\_) - ENS name-to-address support for \`\`eth\_subscribe\`\`. (\`#3066 \`\_\_) - Asynchronous iterator support for \`\`AsyncWeb3\`\` with \`\`WebsocketProviderV2\`\` using \`\`async for\`\` syntax. (\`#3067 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Minor fixes to type hinting in the core tests setup fixtures. (\`#3069 \`\_\_) web3.py v6.7.0 (2023-07-26) --------------------------- Bugfixes ~~~~~~~~ - Test wheel build in separate directory and virtualenv (\`#3046 \`\_\_) - Handle case where data gets returned as \`\`None\`\` in a JSON-RPC error response (\`#3054 \`\_\_) - Fixed default windows IPC provider path to work with python 3.11 (\`#3058 \`\_\_) - Fix return type for \`\`rpc\_gas\_price\_strategy\`\` to \`\`int\`\` but also only convert the \`\`strategy\_based\_gas\_price\`\` to \`\`hex\`\` if it is an \`\`int\`\` in the \`\`gas\_price\_strategy\_middleware\`\`. (\`#3065 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add note to Release Notes about v5 end-of-life and v6.6.0 yank (\`#3045 \`\_\_) - Add documentation for \`\`WebsocketProviderV2\`\` (beta). (\`#3048 \`\_\_) Features ~~~~~~~~ - Add ENSIP-9 (Multichain Address Resolution) support for \`\`address()\`\` and \`\`setup\_address()\`\` for \`\`ENS\`\` and \`\`AsyncENS\`\` classes. (\`#3030 \`\_\_) - Support for \`\`eth\_subscribe\`\` and \`\`eth\_unsubscribe\`\` methods has been added with the introduction of a new websocket provider, \`\`WebsocketProviderV2\`\`. (\`#3048 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Added recursive typing to \`\`ABIFunctionComponents\`\` type (\`#3063 \`\_\_) - Upgrade eth-tester requirement to v0.9.0-b.1 (\`#3064 \`\_\_) web3.py v6.6.1 (2023-07-12) --------------------------- Bugfixes ~~~~~~~~ - Add \`\`ens/specs\`\` to MANIFEST.in (\`#3039 \`\_\_) web3.py v6.6.0 (2023-07-12) --------------------------- \*\*Note: This release was missing the required \`\`ens/specs\`\` directory, so it was yanked from Pypi in favor of v6.6.1\*\* Breaking Changes ~~~~~~~~~~~~~~~~ - ENS name normalization now uses ENSIP-15 by default. This is technically a breaking change introduced by ENS but, according to ENSIP-15, 99% of existing names should be unaffected. (\`#3024 \`\_\_) Bugfixes ~~~~~~~~ - Handle \`\`None\`\` in the formatting middleware (\`#2546 \`\_\_) - Fix for a possible bug in \`\`construct\_sign\_and\_send\_raw\_middleware\`\` where the signed transaction was sent as bytes and expected to be converted to hex by formatting later on. It is now explicitly sent as the hex string hash within the middleware. (\`#2936 \`\_\_) - Fixes \`\`max\_priority\_fee\_per\_gas\`\`. It wasn't falling back to \`\`eth\_feeHistory\`\` since the \`\`MethodUnavailable\`\` error was introduced. (\`#3002 \`\_\_) - Properly initialize logger in \`\`AsyncHTTPProvider\`\`. (\`#3026 \`\_\_) - Fix \`\`AsyncWeb3.solidity\_keccak\`\` to match \`\`Web3.solidity\_keccak\`\`. (\`#3034 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Replaced transaction examples with unused account addresses. (\`#2011 \`\_\_) - Removed obsolete docs for camelCase miner methods and \`\`deploy\`\` (\`#2039 \`\_\_) - Update documentation relating to ENS only being available on mainnet. ENS is available on all networks where the ENS contracts are deployed. (\`#3012 \`\_\_) - Add first steps section and tidy up learning resources (\`#3013 \`\_\_) - Replace references to \`\`jasoncarver.eth\`\` with \`\`ens.eth\`\`. (\`#3020 \`\_\_) - Adds "Hackathon Helpers" section to Resources page (\`#3035 \`\_\_) Features ~~~~~~~~ - Update ENS Resolver ABI (\`#1839 \`\_\_) - \`\`async\_http\_retry\_request\_middleware\`\`, an async http request retry middleware for \`\`AsyncHTTPProvider\`\`. (\`#3009 \`\_\_) - Add \`\`eth\_getStorageAt()\`\` support for \`\`EthereumTesterProvider\`\`. (\`#3011 \`\_\_) - Add async support for ENS name-to-address resolution via \`\`async\_name\_to\_address\_middleware\`\`. (\`#3012 \`\_\_) - Add async support for the sign-and-send raw transaction middleware via \`\`construct\_async\_sign\_and\_send\_raw\_middleware()\`\`. (\`#3025 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Remove some warnings from test output (\`#2991 \`\_\_) - Introduced the logic for ENSIP-15 ENS name normalization. Originally this was done via a flag in this PR but changed to the default behavior in #3024 before release. (\`#3000 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#2997 \`\_\_, \`#3011 \`\_\_, \`#3023 \`\_\_, \`#3037 \`\_\_ Removals ~~~~~~~~ - Removed references to deprecated middlewares with new tests to check default middlewares (\`#2972 \`\_\_) web3.py v6.5.0 (2023-06-15) --------------------------- Bugfixes ~~~~~~~~ - Properly create a fresh cache for each instance of \`\`simple\_cache\_middleware\`\` if no cache is provided. Fixes a bug when using this middleware with multiple instances of \`\`Web3\`\`. (\`#2979 \`\_\_) - Fix potential race condition when writing cache entries in \`\`simple\_cache\_middleware\`\` (\`#2981 \`\_\_) - Catch \`\`UnicodeDecodeError\`\` for contract revert messages that cannot be decoded and issue a warning instead, raising a \`\`ContractLogicError\`\` with the raw \`\`data\`\` from the response. (\`#2989 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Introduces resources page to documentation (\`#2957 \`\_\_) - Completed docstrings for \`\`ContractFunction\`\` and \`\`AsyncContractFunction\`\` classes (\`#2960 \`\_\_) - Added 'unsupported by any current clients' note to the \`\`Eth.sign\_typed\_data\`\` docs (\`#2961 \`\_\_) - Removed list of \`\`AsyncHTTPProvider\`\`-supported methods, it supports them all now (\`#2962 \`\_\_) - Modernize the filtering guide, emphasizing \`\`get\_logs\`\` (\`#2968 \`\_\_) - Removed references to defunct providers in \`\`IPCProvider\`\` docs (\`#2971 \`\_\_) - Update Matomo analytics script to move to cloud services (\`#2978 \`\_\_) Features ~~~~~~~~ - Add the \`\`sign\_typed\_data\`\` method to the \`\`AsyncEth\`\` class (\`#2920 \`\_\_) - Add support for Solidity \`\`Panic\`\` errors, available since Solidity 0.8.0. Raises \`\`ContractPanicError\`\` with appropriate messaging based on the known panic error codes. (\`#2986 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - \`\`lint-roll\`\` - dropped \`\`isort\`\` \`\`--recursive\`\` flag, not needed as of their \`\`v5\`\`, added black (\`#2930 \`\_\_) - Moved \`\`ethpm\`\` deprecation warning to only show when the module is explicitly enabled (\`#2983 \`\_\_) - Update make release to check remote upstream is pointing to ethereum/web3.py. (\`#2988 \`\_\_) - Removed \`pluggy\` from dev requirements (\`#2992 \`\_\_) Miscellaneous Changes ~~~~~~~~~~~~~~~~~~~~~ - \`#2960 \`\_\_, \`#2965 \`\_\_ web3.py v6.4.0 (2023-05-15) --------------------------- Bugfixes ~~~~~~~~ - fix AttributeDicts unhashable if they contain lists recursively tupleizing them (\`#2908 \`\_\_) Deprecations ~~~~~~~~~~~~ - add deprecation notice for the \`ethPM\` module (\`#2953 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - remove reference to the ability to specify a list of providers - you can't anymore (\`#2949 \`\_\_) - add deprecation notice for the \`ethPM\` module (\`#2953 \`\_\_) Features ~~~~~~~~ - Update \`\`eth-tester\`\` to pull in Shanghai changes and make additional changes to fully support Shanghai with \`\`eth-tester\`\`. (\`#2958 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - bump sphinx and readthedocs py versions (\`#2945 \`\_\_) - re-compile test contracts with Solidity \`\`v0.8.20\`\` (\`#2951 \`\_\_) - Set towncrier settings in \`pyproject.toml\` to match the python project template and change newfragment type "doc" to "docs" (\`#2959 \`\_\_) v6.3.0 (2023-05-03) ------------------- Features ~~~~~~~~ - Add support for custom revert errors (\`#2795 \`\_\_) - Add the \`\`modify\_transaction\`\` method to the \`\`AsyncEth\`\` class (\`#2825 \`\_\_) - add show\_traceback flag to is\_connected to allow user to see connection error reason (\`#2912 \`\_\_) - Add a \`\`data\`\` attribute on the \`\`ContractLogicError\`\` class that returns raw data returned by the node. (\`#2922 \`\_\_) - Add support via result formatters for \`\`reward\`\` type trace actions on tracing calls. (\`#2929 \`\_\_) Bugfixes ~~~~~~~~ - Typing was being ignored for the \`\`get\_ipc\_path\`\` and \`\`get\_dev\_ipc\_path\`\` functions because of a missing \`\`None\`\` return. Those two methods now explicitly return \`\`None\`\` and have an \`\`Optional\`\` in their type definition. (\`#2917 \`\_\_) - fix AsyncEventFilterBuilder looking for Web3 instead of AsyncWeb3 (\`#2931 \`\_\_) - Add check for null withdrawal field on get\_block response (\`#2941 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add a decision tree guide for sending transactions (\`#2919 \`\_\_) - Update references to master branch (\`#2933 \`\_\_) - Cleanup Quickstart guide and next steps (\`#2935 \`\_\_) - Cleanup Overview page links and context (\`#2938 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Added \`\`build\`\` to towncrier commands in Makefile (\`#2915 \`\_\_) - Update win wheel CI builds to use \`\`python -m tox -r\`\` instead of specifying the \`\`tox\`\` executable directly. (\`#2923 \`\_\_) - update pip and tox install on CI containers (\`#2927 \`\_\_) v6.2.0 (2023-04-12) ------------------- Features ~~~~~~~~ - Adds async version of \`eth\_getUncleCount\` methods (\`#2822 \`\_\_) - Add the \`\`sign\_transaction\`\` method to the \`\`AsyncEth\`\` class (\`#2827 \`\_\_) - Add the \`\`replace\_transaction\`\` method to the \`\`AsyncEth\`\` class (\`#2847 \`\_\_) Bugfixes ~~~~~~~~ - Use \`\`TraceFilterParams\`\` instead of \`\`FilterParams\`\` for \`\`trace\_filter\`\` typing (\`#2913 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add welcome banner for Ethereum newcomers (\`#2905 \`\_\_) - Added breaking changes from pr2448 to v6 migration guide (\`#2907 \`\_\_) v6.1.0 (2023-04-05) ------------------- Features ~~~~~~~~ - Add tracing functionality back in via the \`\`tracing\`\` module, add formatters for human-readable input and output, and attach this module to \`\`Web3\`\` on init / make it a default module. (\`#2851 \`\_\_) - Add result formatters for \`\`withdrawals\_root\`\` and \`\`withdrawals\`\` as part of \`\`Shanghai\`\` hard fork support. (\`#2868 \`\_\_) - add eth\_chainId to exception\_retry\_middleware whitelist (\`#2892 \`\_\_) Bugfixes ~~~~~~~~ - Mark \`test\_async\_eth\_sign\` with \`@pytest.mark.asyncio\` (\`#2858 \`\_\_) - fix readthedocs broken version selector (\`#2883 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - remove camelCased method deprecation notices from web3.eth docs (\`#2882 \`\_\_) - Add doc blurb about multiple HTTPProviders with the same URL (\`#2889 \`\_\_) - fix styling and external link formatting (\`#2897 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Bump pytest from 6.2.5 to 7+ because of CI \`\`DeprecationWarning\`\` (\`#2863 \`\_\_) - Require eth-abi v4 stable (\`#2886 \`\_\_) - remove unused docs dependencies and bump version of remaining (\`#2890 \`\_\_) - Update go-ethereum integration test fixture to use the latest version of geth - \`\`v1.11.5\`\`. (\`#2896 \`\_\_) - Update \`\`geth\_steps\`\` in CircleCI builds to pip install the proper version of \`\`py-geth\`\`. (\`#2898 \`\_\_) - Update CircleCI windows orb path since it now uses python 3.11. (\`#2899 \`\_\_) - Bump go version used in CI jobs that install and run go-ethereum and parameterize the version in circleci config file for ease of configuration. (\`#2900 \`\_\_) Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - \`#2887 \`\_\_ v6.0.0 (2023-03-14) ------------------- Bugfixes ~~~~~~~~ - fix dict\_to\_namedtuple unable to handle empty dict as input (\`#2867 \`\_\_) v6.0.0-beta.11 (2023-02-24) --------------------------- Features ~~~~~~~~ - Add the \`\`sign\`\` method to the \`\`AsyncEth\`\` class (\`#2833 \`\_\_) Bugfixes ~~~~~~~~ - More accurately define the \`\`eth\_call\`\` return type as \`\`HexBytes\`\` since the response is converted to \`\`HexBytes\`\` in the pythonic formatters and there are differences between \`\`HexBytes\`\` and \`\`bytes\`\` types. (\`#2842 \`\_\_) - Set default block\_identifier in ContractFunction.call() to None (\`#2846 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Remove unused module lines to instantiate the AsyncHTTPProvider (\`#2789 \`\_\_) - Typos fix in docs (\`#2817 \`\_\_) - Add/cleanup docs for the \`\`AsyncHTTPProvider\`\` in light of the new \`\`AsyncWeb3\`\` class (\`#2821 \`\_\_) - Remove user survey banner following close of survey (\`#2831 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Do not invoke \`\`setup.py\`\` directly; use \`\`python -m build\`\` where appropriate. (\`#2714 \`\_\_) - clean up ignored unused imports (\`#2838 \`\_\_) - Recompile test contracts with the new Solidity version \`\`0.8.19\`\`. (\`#2840 \`\_\_) - Update \`\`py-geth\`\` version and re-generate integration test fixture with geth \`\`v1.11.2\`\`. (\`#2841 \`\_\_) Breaking changes ~~~~~~~~~~~~~~~~ - Use \`\`AsyncWeb3\`\` class and preserve typing for the async api calls. (\`#2819 \`\_\_) - Fix typing for \`\`CallOverrideParams\`\` and add proper request formatters for call state overrides. (\`#2843 \`\_\_) - Remove python warning and doc notes related to unstable async providers. (\`#2845 \`\_\_) v6.0.0-beta.10 (2023-02-15) --------------------------- Features ~~~~~~~~ - add decode\_tuples option to contract instantiation (\`#2799 \`\_\_) Bugfixes ~~~~~~~~ - Fix \`\`ethpm\`\` import issues after making \`\`ipfshttpclient\`\` optional. (\`#2775 \`\_\_) - Fix for recently-broken \`\`eth-tester\`\` exception message parsing for some exception cases. (\`#2783 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Added a v6 Migraion Guide (\`#2778 \`\_\_) - Rebrand the library to lowercase "web3.py" (\`#2804 \`\_\_) - remove references to Rinkeby or replace with Goerli (\`#2815 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Organize the \`\`eth\`\` module into separate files for better readability. (\`#2753 \`\_\_) - Rename the newly-split \`\`eth\`\` module files to match convention. (\`#2772 \`\_\_) - Re-compile all test contracts with latest Solidity version. Refactor test fixtures. Adds a script that compiles all test contracts to the same directory with selected Solidity version. (\`#2797 \`\_\_) - Updates to \`\`isort\`\` and \`\`black\`\` required some formatting changes and isort config refactoring. (\`#2802 \`\_\_) - Compile test contracts using newly-released Solidity version \`\`0.8.18\`\`. (\`#2803 \`\_\_) Breaking changes ~~~~~~~~~~~~~~~~ - All exceptions inherit from a custom class. EthPM exceptions inherit from EthPMException, ENS exceptions inherit from ENSException, and all other web3.py exceptions inherit from Web3Exception (\`#1478 \`\_\_) - Reorganized contract to contract.py, async\_contract.py, base\_contract.py and utils.py. In this change there was a small breaking change where the constructor of BaseContractCaller contract\_function\_class was defaulting to a ContractFunction now there is no default. This was done to separate the base class from the implementation. (\`#2567 \`\_\_) - When calling a contract, use \`\`w3.eth.default\_block\`\` if no block\_identifier is specified instead of \`\`latest\`\`. (\`#2777 \`\_\_) - Strict bytes type checking is now default for \`\`web3.py\`\`. This change also adds a boolean flag on the \`\`Web3\`\` class for turning this feature on and off, as well as a flag on the \`\`ENS\`\` class for control over a standalone \`\`ENS\`\` instance. (\`#2788 \`\_\_) - When a method is not supported by a node provider, raise a MethodUnavailable error instead of the generic ValueError. (\`#2796 \`\_\_) - \`\`dict\`\` to \`\`AttributeDict\`\` conversion is no longer a default result formatter. This conversion is now done via a default middleware that may be removed. (\`#2805 \`\_\_) - Removed deprecated \`\`manager.request\_async\`\` and associated methods. (\`#2810 \`\_\_) - removed Rinkeby from list of allowed chains in EthPM (\`#2815 \`\_\_) v6.0.0-beta.9 (2023-01-03) -------------------------- Features ~~~~~~~~ - Add async \`\`w3.eth.get\_block\_transaction\_count\`\` (\`#2687 \`\_\_) - Support Python 3.11 (\`#2699 \`\_\_) - Load the \`\`AsyncHTTPProvider\`\` with default async middleware and default async modules, just as the \`\`HTTPProvider\`\`. (\`#2736 \`\_\_) - Add support for Nethermind/Gnosis revert reason formatting (\`#2739 \`\_\_) - Added async functionality to filter (\`#2744 \`\_\_) - Get contract address from \`\`CREATE\`\` and \`\`CREATE2\`\` opcodes (\`#2762 \`\_\_) Bugfixes ~~~~~~~~ - Fixing abi encoding for multidimensional arrays. (\`#2764 \`\_\_) Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Some minor performance improvements to the \`\`SimpleCache\`\` class and simple cache middlewares (sync and async). (\`#2719 \`\_\_) - Remove unnecessary \`\`await\`\` for \`\`generate\_gas\_price()\`\` method as it does not need to be awaited. Move this method to \`\`BaseEth\`\` to be used directly by both \`\`Eth\`\` and \`\`AsyncEth\`\` modules. (\`#2735 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add user survey to docs banner (\`#2720 \`\_\_) - Document improvements for private key info and account funding. (\`#2722 \`\_\_) - Include eth-tester install note in quickstart (\`#2755 \`\_\_) Deprecations and Removals ~~~~~~~~~~~~~~~~~~~~~~~~~ - Removal of Infura auto provider support. (\`#2706 \`\_\_) - Removal of \`\`version\`\` module. (\`#2729 \`\_\_) - Remove already-deprecated \`\`start\_rpc\`\` and \`\`stop\_rpc\`\` from the \`\`w3.geth.admin\`\` module. (\`#2731 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Use regex pattern for \`\`black\`\` command for \`\`tox\`\` / \`\`make lint\`\` linting commands. (\`#2727 \`\_\_) - Use regex pattern for \`\`mypy\`\` command for \`\`tox\`\` / \`\`make lint\`\` linting commands. (\`#2734 \`\_\_) - Remove internal method \`\`apply\_formatter\_to\_array\`\` and use the method with the same name from the \`\`eth-utils\`\` library. (\`#2737 \`\_\_) Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - \`#2751 \`\_\_ Breaking changes ~~~~~~~~~~~~~~~~ - Snakecase the processReceipt, processLog, createFilter, and getLogs methods (\`#2709 \`\_\_) - Remove Parity module and references. (\`#2718 \`\_\_) - Make the \`\`ipfshttpclient\`\` library opt-in via a web3 install extra. This only affects the \`\`ethpm\`\` \`\`ipfs\`\` backends, which rely on the library. (\`#2730 \`\_\_) v6.0.0-beta.8 (2022-11-14) -------------------------- Features ~~~~~~~~ - Async support for caching certain methods via \`\`async\_simple\_cache\_middleware\`\` as well as constructing custom async caching middleware via \`\`async\_construct\_simple\_cache\_middleware\`\`. \`\`SimpleCache\`\` class was also added to the public \`\`utils\`\` module. (\`#2579 \`\_\_) - Remove upper pins on dependencies (\`#2648 \`\_\_) - Async support for beacon api. (\`#2689 \`\_\_) - If the loop for a cached async session is closed, or the session itself was closed, create a new session at that cache key and properly close and evict the stale session. (\`#2713 \`\_\_) Bugfixes ~~~~~~~~ - bump \`sphinx\_rtd\_theme\` version to fix missing unordered list bullets (\`#2688 \`\_\_) - Fix bug to generate unique cache keys when multi-threading & with unique event loops for async. (\`#2690 \`\_\_) - Properly release \`\`async\_lock\`\` for session requests if an exception is raised during a task. (\`#2695 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - move definition of RTD install requirements file from their dashboard into \`.readthedocs.yml\`, and remove unused \`sphinx-better-theme\` from requirements (\`#2688 \`\_\_) Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - \`#2690 \`\_\_, \`#2694 \`\_\_ Breaking changes ~~~~~~~~~~~~~~~~ - Remove support for dictionary-based caches, for simple-cache-middleware, in favor of the internal \`\`SimpleCache\`\` class. (\`#2579 \`\_\_) - Snakecase the clientVersion method (\`#2686 \`\_\_) - change instances of \`createFilter\` to \`create\_filter\` (\`#2692 \`\_\_) - Remove \`\`SolidityError\`\` in favor of \`\`ContractLogicError\`\` (\`#2697 \`\_\_) - Snakecase the solidityKeccak method (\`#2702 \`\_\_) - Snakecase the fromWeb3 method (\`#2703 \`\_\_) - Snakecase the toBytes, toHex, toInt, toJSON, and toText methods (\`#2707 \`\_\_) - Snakecase the toAddress, isChecksumAddress, and toChecksumAddress methods (\`#2708 \`\_\_) v6.0.0-beta.7 (2022-10-19) -------------------------- Bugfixes ~~~~~~~~ - Protobuf dependency had a DoS-able bug. It was fixed in v4.21.6. See: https://nvd.nist.gov/vuln/detail/CVE-2022-1941 (\`#2666 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Added Chainstack link to quickstart docs. (\`#2677 \`\_\_) Deprecations and Removals ~~~~~~~~~~~~~~~~~~~~~~~~~ - Remove Ropsten auto provider and the relevant references to Ropsten across the repo (\`#2672 \`\_\_) Internal Changes - for web3.py Contributors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Clean up remaining uses of deprecated \`\`eth\_abi\`\` methods. (\`#2668 \`\_\_) Miscellaneous changes ~~~~~~~~~~~~~~~~~~~~~ - \`#2671 \`\_\_, \`#2682 \`\_\_ v6.0.0-beta.6 (2022-09-26) -------------------------- Bugfixes ~~~~~~~~ - Protobuf dependency breaks at version \`\`3.20.2\`\` and above; pin to \`\`3.20.1\`\` for now. (\`#2657 \`\_\_) Features ~~~~~~~~ - Add new predefined block identifiers \`\`safe\`\` and \`\`finalized\`\`. (\`#2652 \`\_\_) v6.0.0-beta.5 (2022-09-19) -------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Removed IBAN since it was an unused feature (\`#2537 \`\_\_) - Update eth-tester dependency to v0.7.0-beta.1; Update eth-account version to >=0.7.0,<0.8.0 (\`#2623 \`\_\_) - Remove \`\`WEB3\_INFURA\_API\_KEY\`\` environment variable in favor of \`\`WEB3\_INFURA\_PROJECT\_ID\`\`. Change \`\`InfuraKeyNotFound\`\` exception to \`\`InfuraProjectIdNotFound\`\` (\`#2634 \`\_\_) - Remove Kovan auto provider (\`#2635 \`\_\_) - Snakecase the \`isConnected\` method (\`#2643 \`\_\_) - Snakecase the \`\`toWei\`\` and \`\`fromWei\`\` methods (\`#2647 \`\_\_) Bugfixes ~~~~~~~~ - Fix \`\`eth-tester\`\` key remapping for \`\`logsBloom\`\` and \`\`receiptsRoot\`\` (\`#1630 \`\_\_) - Improve upon issues with session caching - better support for multithreading and make sure session eviction from cache does not happen prematurely. (\`#2409 \`\_\_) - Allow classes to inherit from the \`\`Web3\`\` class by attaching modules appropriately. (\`#2592 \`\_\_) - fixed bug in how async\_eth\_tester\_middleware fills default fields (\`#2600 \`\_\_) - Allow hex for \`\`value\`\` field when validating via \`\`validate\_payable()\`\` contracts method (\`#2602 \`\_\_) - Update Beacon API to v2.3.0 (\`#2616 \`\_\_) - Move \`\`flaky\`\` option to top-level conftest.py (\`#2642 \`\_\_) Documentation Updates ~~~~~~~~~~~~~~~~~~~~~ - Update Proof of Authority middleware (\`geth\_poa\_middleware\`) documentation for better clarity. (\`#2538 \`\_\_) - Add some missing supported async middlewares to docs. (\`#2574 \`\_\_) - Introduce AsyncENS and availability on w3 instance in ENS guide. (\`#2585 \`\_\_) - Fix typo in eth.call docs (\`#2613 \`\_\_) - remove section for deleted \`account.recoverHash\` method (\`#2615 \`\_\_) - examples docs gave incorrect return type for \`eth.get\_transaction\`, fixed (\`#2617 \`\_\_) - minor typo fix in contracts overview (\`#2628 \`\_\_) - fix bug in \`Deploying new contracts\` example (\`#2646 \`\_\_) Features ~~~~~~~~ - Support for \`\`Account\`\` class access in \`\`AsyncEth\`\` via \`\`async\_w3.eth.account\`\` (\`#2580 \`\_\_) - Expose public abi utility methods: \`\`get\_abi\_output\_names()\`\` and \`\`get\_abi\_input\_names()\`\` (\`#2596 \`\_\_) - update all references to deprecated \`eth\_abi.encode\_abi\` to \`eth\_abi.encode\` (\`#2621 \`\_\_) - update all references to deprecated \`eth\_abi.decode\_abi\` to \`eth\_abi.decode\` (\`#2636 \`\_\_) - Add Sepolia auto provider (\`#2639 \`\_\_) Misc ~~~~ - \`#2603 \`\_\_, \`#2622 \`\_\_, \`#2630 \`\_\_, \`#2638 \`\_\_ v6.0.0-beta.4 (2022-07-13) -------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - sha3 and soliditySha3 were previously deprecated and now removed (\`#2479 \`\_\_) - Remove deprecated methods from Geth, Parity and Net modules (\`#2480 \`\_\_) - Provide better messaging to wrong arguments for contract functions, especially for \`\`tuple\`\` argument types. (\`#2556 \`\_\_) Bugfixes ~~~~~~~~ - Properly format \`\`block\_number\`\` for \`\`eth\_getTransactionCount\`\` when using \`\`EthereumTesterProvider\`\` (\`#1801 \`\_\_) - removed \`Optional\` type hints for \`passphrase\` arguments that aren't actually optional (\`#2511 \`\_\_) - Fix \`is\_dynamic\_fee\_transaction\` and \`TRANSACTION\_DEFAULTS\` when \`gas\_price\_strategy\` returns zero (\`#2562 \`\_\_) Documentation Updates ~~~~~~~~~~~~~~~~~~~~~ - Remove deprecated methods from Geth, Parity, and Net modules (\`#2480 \`\_\_) - replace double- with single-quotes to make f-string valid (\`#2504 \`\_\_) - added geth personal\_sign and personal\_ec\_recover documentation (\`#2511 \`\_\_) Features ~~~~~~~~ - Add transaction result formatters for \`type\` and \`chainId\` to convert values to \`\`int\`\` if \`\`hexadecimal\`\` if the field is not null (\`#2491 \`\_\_) - Add a global flag on the provider for enabling / disabling CCIP Read for calls: \`\`global\_ccip\_read\_enabled\`\` (defaults to \`\`True\`\`). (\`#2499 \`\_\_) - Deprecate Geth Admin StartRPC and StopRPC for StartHTTP and StopHTTP (\`#2507 \`\_\_) - Added Async support for ENS (\`#2547 \`\_\_) - support multi-dimensional arrays for ABI tuples types (\`#2555 \`\_\_) Misc ~~~~ - \`#2345 \`\_\_, \`#2483 \`\_\_, \`#2505 \`\_\_, \`#2513 \`\_\_, \`#2514 \`\_\_, \`#2515 \`\_\_, \`#2516 \`\_\_, \`#2518 \`\_\_, \`#2520 \`\_\_, \`#2521 \`\_\_, \`#2522 \`\_\_, \`#2523 \`\_\_, \`#2524 \`\_\_, \`#2525 \`\_\_, \`#2527 \`\_\_, \`#2530 \`\_\_, \`#2531 \`\_\_, \`#2534 \`\_\_, \`#2542 \`\_\_, \`#2544 \`\_\_, \`#2550 \`\_\_, \`#2551 \`\_\_, \`#2559 \`\_\_ v6.0.0-beta.3 (2022-06-01) -------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Removed deprecated methods from eth and geth (\`#1416 \`\_\_) Bugfixes ~~~~~~~~ - Fix bug in \_is\_latest\_block\_number\_request in cache middleware (\`#2185 \`\_\_) - Increase cache size to allow for 20 entries. (\`#2477 \`\_\_) - format receipt.type to int and log.data to HexBytes (\`#2482 \`\_\_) - Only thread lock for methods attempting to access the cache for caching middleware. (\`#2496 \`\_\_) Documentation Updates ~~~~~~~~~~~~~~~~~~~~~ - Fix typo in simple\_cache\_middleware example (\`#2449 \`\_\_) - Fix dict type hints in EventScanner example (\`#2469 \`\_\_) - Add clarification around ValueError and Local Signing middleware (\`#2474 \`\_\_) Features ~~~~~~~~ - Add async version of contract functionality (\`#2270 \`\_\_) - ENSIP-10 / wildcard resolution support for ENS module (\`#2411 \`\_\_) - CCIP Read support and finalize implementation of and add tests for ENS offchain resolution support (\`#2457 \`\_\_) Misc ~~~~ - \`#2454 \`\_\_, \`#2450 \`\_\_, \`#2462 \`\_\_, \`#2471 \`\_\_, \`#2478 \`\_\_ v6.0.0-beta.2 (2022-04-27) -------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Audit \`\`.rst\`\` and \`\`.py\`\` files and convert all Web3 instance variable names to \`\`w3\`\` to avoid confusion with the \`\`web3\`\` module. (\`#1183 \`\_\_) - Update dependency requirements: - eth-utils - eth-abi - eth-tester - eth-account - eth-typing (\`#2342 \`\_\_) - Add \`\`attach\_methods()\`\` to \`\`Module\`\` class to facilitate attaching methods to modules. (\`#2383 \`\_\_) - Move IOError -> OSError (\`#2434 \`\_\_) Documentation Updates ~~~~~~~~~~~~~~~~~~~~~ - Clarify info about Infura filters over HTTP (\`#2322 \`\_\_) - Document reading private keys from environment variables (\`#2380 \`\_\_) - Add example for the \`\`construct\_sign\_and\_send\_raw\_middleware\`\` when connected to a hosted node (\`#2410 \`\_\_) - Doc fix: Pending transaction filter returns a \`\`TransactionFilter\`\` not a \`\`BlockFilter\`\` (\`#2444 \`\_\_) Features ~~~~~~~~ - Add 'get\_text' method to look up ENS text record values (\`#2286 \`\_\_) - For \`\`ENS.name()\`\`, validate that the forward resolution returns the same address as provided by the user as per the ENS documentation recommendation for Reverse Resolution. (\`#2420 \`\_\_) - Add sync chain\_id to \`\`simple\_middleware\_cache\`\` (\`#2425 \`\_\_) Misc ~~~~ - \`#2369 \`\_\_, \`#2372 \`\_\_, \`#2418 \`\_\_ v6.0.0-beta.1 (2022-02-28) -------------------------- Breaking Changes ~~~~~~~~~~~~~~~~ - Update \`\`websockets\`\` dependency to v10+ (\`#2324 \`\_\_) - Remove support for the unsupported Python 3.6 Also removes outdated Parity tests (\`#2343 \`\_\_) - Update Sphinx requirement to \`\`>=4.2.0,<5\`\` (\`#2362 \`\_\_) Bugfixes ~~~~~~~~ - Fix types for \`\`gas\`\`, and \`\`gasLimit\`\`: \`\`Wei -> int\`\`. Also fix types for \`\`effectiveGasPrice\`\`: (\`\`int -> Wei\`\`) (\`#2330 \`\_\_) Features ~~~~~~~~ - Added session caching to the AsyncHTTPProvider (\`#2016 \`\_\_) - Add support for Python 3.10 (\`#2175 \`\_\_) - Added 'Breaking Changes' and 'Deprecations' categories to our release notes (\`#2340 \`\_\_) - Add async \`eth.get\_storage\_at\` method (\`#2350 \`\_\_) - Upgrade \`\`jsonschema\`\` version to \`\`>=4.0.0<5\`\` (\`#2361 \`\_\_) Misc ~~~~ - \`#2353 \`\_\_, \`#2365 \`\_\_ v5.28.0 (2022-02-09) -------------------- Features ~~~~~~~~ - Added Async functions for Geth Personal and Admin modules (\`#1413 \`\_\_) - async support for formatting, validation, and geth poa middlewares (\`#2098 \`\_\_) - Calculate a default \`\`maxPriorityFeePerGas\`\` using \`\`eth\_feeHistory\`\` when \`\`eth\_maxPriorityFeePerGas\`\` is not available, since the latter is not a part of the Ethereum JSON-RPC specs and only supported by certain clients. (\`#2259 \`\_\_) - Allow NamedTuples in ABI inputs (\`#2312 \`\_\_) - Add async \`eth.syncing\` method (\`#2331 \`\_\_) Bugfixes ~~~~~~~~ - remove \`ens.utils.dict\_copy\` decorator (\`#1423 \`\_\_) - The exception retry middleware whitelist was missing a comma between \`\`txpool\`\` and \`\`testing\`\` (\`#2327 \`\_\_) - Properly initialize external modules that do not inherit from the \`\`web3.module.Module\`\` class (\`#2328 \`\_\_) v5.27.0 (2022-01-31) -------------------- Features ~~~~~~~~ - Added Async functions for Geth TxPool (\`#1413 \`\_\_) - external modules are no longer required to inherit from the \`\`web3.module.Module\`\` class (\`#2304 \`\_\_) - Add async \`eth.get\_logs\` method (\`#2310 \`\_\_) - add Async access to \`default\_account\` and \`default\_block\` (\`#2315 \`\_\_) - Update eth-tester and eth-account dependencies to pull in bugfix from eth-keys (\`#2320 \`\_\_) Bugfixes ~~~~~~~~ - Fixed issues with parsing tuples and nested tuples in event logs (\`#2211 \`\_\_) - In ENS the contract function to resolve an ENS address was being called twice in error. One of those calls was removed. (\`#2318 \`\_\_) - \`\`to\_hexbytes\`\` block formatters no longer throw when value is \`\`None\`\` (\`#2321 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - fix typo in \`eth.account\` docs (\`#2111 \`\_\_) - explicitly add \`output\_values\` to contracts example (\`#2293 \`\_\_) - update imports for \`AsyncHTTPProvider\` sample code (\`#2302 \`\_\_) - fixed broken link to filter schema (\`#2303 \`\_\_) - add github link to the main docs landing page (\`#2313 \`\_\_) - fix typos and update referenced \`geth\` version (\`#2326 \`\_\_) Misc ~~~~ - \`#2217 \`\_\_ v5.26.0 (2022-01-06) -------------------- Features ~~~~~~~~ - Add \`\`middlewares\`\` property to \`\`NamedElementOnion\`\` / \`\`web3.middleware\_onion\`\`. Returns current middlewares in proper order for importing into a new \`\`Web3\`\` instance (\`#2239 \`\_\_) - Add async \`\`eth.hashrate\`\` method (\`#2243 \`\_\_) - Add async \`\`eth.chain\_id\`\` method (\`#2251 \`\_\_) - Add async \`\`eth.mining\`\` method (\`#2252 \`\_\_) - Add async \`\`eth.get\_transaction\_receipt\`\` and \`\`eth.wait\_for\_transaction\_receipt\`\` methods (\`#2265 \`\_\_) - Add async \`eth.accounts\` method (\`#2284 \`\_\_) - Support for attaching external modules to the \`\`Web3\`\` instance when instantiating the \`\`Web3\`\` instance, via the \`\`external\_modules\`\` argument, or via the new \`\`attach\_modules()\`\` method (\`#2288 \`\_\_) Bugfixes ~~~~~~~~ - Fixed doctest that wasn't running in \`\`docs/contracts.rst\`\` (\`#2213 \`\_\_) - Key mapping fix to eth-tester middleware for access list storage keys (\`#2224 \`\_\_) - Inherit \`\`Web3\`\` instance middlewares when instantiating \`\`ENS\`\` with \`\`ENS.fromWeb3()\`\` method (\`#2239 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix example docs to show a TransactionNotFound error, instead of None (\`#2199 \`\_\_) - fix typo in ethpm.rst (\`#2277 \`\_\_) - Clarify provider usage in Quickstart docs (\`#2287 \`\_\_) - Address common BSC usage question (\`#2289 \`\_\_) Misc ~~~~ - \`#1729 \`\_\_, \`#2233 \`\_\_, \`#2242 \`\_\_, \`#2260 \`\_\_, \`#2261 \`\_\_, \`#2283 \`\_\_ v5.25.0 (2021-11-19) -------------------- Features ~~~~~~~~ - Support for \`\`w3.eth.get\_raw\_transaction\_by\_block\`\`, and async support for \`\`w3.eth.get\_raw\_transaction\_by\_block\`\` (\`#2209 \`\_\_) Bugfixes ~~~~~~~~ - BadResponseFormat error thrown instead of KeyError when a response gets sent back without a \`\`result\`\` key. (\`#2188 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Correct link to Websocket library documentation (\`#2173 \`\_\_) - Doc update to make it clearer that enable\_unstable\_package\_management() method is on the web3 instance (\`#2208 \`\_\_) Misc ~~~~ - \`#2102 \`\_\_, \`#2179 \`\_\_, \`#2191 \`\_\_, \`#2201 \`\_\_, \`#2205 \`\_\_, \`#2212 \`\_\_ v5.24.0 (2021-09-27) -------------------- Features ~~~~~~~~ - Add async \`\`eth.send\_raw\_transaction\`\` method (\`#2135 \`\_\_) - Updated eth-account version to v0.5.6 - adds support for signing typed transactions without needing to explicitly set the transaction type and now accepts correct JSON-RPC structure for accessList for typed transactions (\`#2157 \`\_\_) Bugfixes ~~~~~~~~ - Encode block\_count as hex before making eth\_feeHistory RPC call (\`#2117 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix typo in AsyncHTTPProvider docs (\`#2131 \`\_\_) - Update AsyncHTTPProvider doc Supported Methods to include \`\`web3.eth.send\_raw\_transaction()\`\`. (\`#2135 \`\_\_) - Improve messaging around usage and implementation questions, directing users to the appropriate channel (\`#2138 \`\_\_) - Clarify some contract \`\`ValueError\`\` error messages. (\`#2146 \`\_\_) - Updated docs for w3.eth.account.sign\_transaction to reflect that transaction type is no longer needed to successfully sign typed transactions and to illustrate how to structure an optional accessList parameter in a typed transaction (\`#2157 \`\_\_) Misc ~~~~ - \`#2105 \`\_\_ v5.23.1 (2021-08-27) -------------------- Features ~~~~~~~~ - Add constants for the zero address, zero hash, max int, and wei per ether. (\`#2109 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Renamed "1559 transaction" to "dynamic fee transaction" where appropriate to keep consistency among the general code base for 1559 transaction (type=2) naming (\`#2118 \`\_\_) - Update AsyncHTTPProvider doc example to include modules and middlewares keyword arguments (\`#2123 \`\_\_) Misc ~~~~ - \`#2110 \`\_\_, \`#2118 \`\_\_, \`#2122 \`\_\_ v5.23.0 (2021-08-12) -------------------- Features ~~~~~~~~ - Add support for eth\_feeHistory RPC method (\`#2038 \`\_\_) - Add support for eth\_maxPriorityFeePerGas RPC method (\`#2100 \`\_\_) Bugfixes ~~~~~~~~ - Hot fix for string interpolation issue with contract function call decoding exception to facilitate extracting a meaningful message from the eth\_call response (\`#2096 \`\_\_) - Bypass adding a \`\`gasPrice\`\` via the gas price strategy, if one is set, when EIP-1559 transaction params are used for \`\`send\_transaction\`\` (\`#2099 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update feeHistory docs (\`#2104 \`\_\_) v5.22.0 (2021-08-02) -------------------- Features ~~~~~~~~ - Add support for eth\_getRawTransactionByHash RPC method (\`#2039 \`\_\_) - Add AsyncNet module (\`#2044 \`\_\_) - Add async \`\`eth.get\_balance\`\`, \`\`eth.get\_code\`\`, \`\`eth.get\_transaction\_count\`\` methods. (\`#2056 \`\_\_) - eth\_signTransaction support for eip-1559 params 'maxFeePerGas' and 'maxPriorityFeePerGas' (\`#2082 \`\_\_) - Add support for async \`\`w3.eth.call\`\`. (\`#2083 \`\_\_) Bugfixes ~~~~~~~~ - If a transaction hash was passed as a string rather than a HexByte to \`\`w3.eth.wait\_for\_transaction\_receipt\`\`, and the time was exhausted before the transaction is in the chain, the error being raised was a TypeError instead of the correct TimeExhausted error. This is because the \`\`to\_hex\`\` method in the TimeExhausted error message expects a primitive as the first argument, and a string doesn't qualify as a primitive. Fixed by converting the transaction\_hash to HexBytes instead. (\`#2068 \`\_\_) - Hot fix for a string interpolation issue in message when BadFunctionCallOutput is raised for call\_contract\_function() (\`#2069 \`\_\_) - \`\`fill\_transaction\_defaults()\`\` no longer sets a default \`\`gasPrice\`\` if 1559 fees are present in the transaction parameters. This fixes sign-and-send middleware issues with 1559 fees. (\`#2092 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Clarify that \`\`send\_transaction\`\`, \`\`modify\_transaction\`\`, and \`\`replace\_transaction\`\` return HexByte objects instead of strings. (\`#2058 \`\_\_) - Added troubleshooting section for Microsoft Visual C++ error on Windows machines (\`#2077 \`\_\_) - Updated the sign-and-send middleware docs to include EIP-1559 as well as legacy transaction examples (\`#2092 \`\_\_) Misc ~~~~ - \`#2073 \`\_\_, \`#2080 \`\_\_, \`#2085 \`\_\_ v5.21.0 (2021-07-12) -------------------- Features ~~~~~~~~ - Adds support for EIP 1559 transaction keys: \`maxFeePerGas\` and \`maxPriorityFeePerGas\` (\`#2060 \`\_\_) Bugfixes ~~~~~~~~ - Bugfix where an error response got passed to a function expecting a block identifier. Split out null result formatters from the error formatters and added some tests. (\`#2022 \`\_\_) - Fix broken tests and use the new 1559 params for most of our test transactions. (\`#2053 \`\_\_) - Set a default maxFeePerGas value consistent with Geth (\`#2055 \`\_\_) - Fix bug in geth PoA middleware where a \`\`None\`\` response should throw a \`\`BlockNotFound\`\` error, but was instead throwing an \`\`AttributeError\`\` (\`#2064 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Added general documentation on unit and integration testing and how to contribute to our test suite. (\`#2053 \`\_\_) v5.20.1 (2021-07-01) -------------------- Bugfixes ~~~~~~~~ - Have the geth dev IPC auto connection check for the \`\`WEB3\_PROVIDER\_URI\`\` environment variable. (\`#2023 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Remove reference to allowing multiple providers in docs (\`#2018 \`\_\_) - Update "Contract Deployment Example" docs to use \`\`py-solc-x\`\` as \`\`solc\`\` is no longer maintained. (\`#2020 \`\_\_) - Detail using unreleased Geth builds in CI (\`#2037 \`\_\_) - Clarify that a missing trie node error could occur when using \`\`block\_identifier\`\` with \`\`.call()\`\` on a node that isn't running in archive mode (\`#2048 \`\_\_) Misc ~~~~ - \`#1938 \`\_\_, \`#2015 \`\_\_, \`#2021 \`\_\_, \`#2025 \`\_\_, \`#2028 \`\_\_, \`#2029 \`\_\_, \`#2035 \`\_\_ v5.20.0 (2021-06-09) -------------------- Features ~~~~~~~~ - Add new AsyncHTTPProvider. No middleware or session caching support yet. Also adds async \`\`w3.eth.gas\_price\`\`, and async \`\`w3.isConnected()\`\` methods. (\`#1978 \`\_\_) - Add ability for AsyncHTTPProvider to accept middleware Also adds async gas\_price\_strategy middleware, and moves gas estimate to middleware. AsyncEthereumTesterProvider now inherits from AsyncBase (\`#1999 \`\_\_) - Support state\_override in contract function call. (\`#2005 \`\_\_) Bugfixes ~~~~~~~~ - Test ethpm caching + bump Sphinx version. (\`#1977 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Clarify solidityKeccak documentation. (\`#1971 \`\_\_) - Improve contributor documentation context and ordering. (\`#2008 \`\_\_) - Add docs for unstable AsyncHTTPProvider (\`#2017 \`\_\_) Misc ~~~~ - \`#1979 \`\_\_, \`#1980 \`\_\_, \`#1993 \`\_\_, \`#2002 \`\_\_ v5.19.0 (2021-04-28) -------------------- Features ~~~~~~~~ - Handle optional \`\`eth\_call\`\` state override param. (\`#1921 \`\_\_) - Add list\_storage\_keys deprecate listStorageKeys (\`#1944 \`\_\_) - Add net\_peers deprecate netPeers (\`#1946 \`\_\_) - Add trace\_replay\_transaction deprecate traceReplayTransaction (\`#1949 \`\_\_) - Add add\_reserved\_peer deprecate addReservedPeer (\`#1951 \`\_\_) - Add \`\`parity.set\_mode\`\`, deprecate \`\`parity.setMode\`\` (\`#1954 \`\_\_) - Add \`\`parity.trace\_raw\_transaction\`\`, deprecate \`\`parity.traceRawTransaction\`\` (\`#1955 \`\_\_) - Add \`\`parity.trace\_call\`\`, deprecate \`\`parity.traceCall\`\` (\`#1957 \`\_\_) - Add trace\_filter deprecate traceFilter (\`#1960 \`\_\_) - Add trace\_block, deprecate traceBlock (\`#1961 \`\_\_) - Add trace\_replay\_block\_transactions, deprecate traceReplayBlockTransactions (\`#1962 \`\_\_) - Add \`\`parity.trace\_transaction\`\`, deprecate \`\`parity.traceTransaction\`\` (\`#1963 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Document \`\`eth\_call\`\` state overrides. (\`#1965 \`\_\_) Misc ~~~~ - \`#1774 \`\_\_, \`#1805 \`\_\_, \`#1945 \`\_\_, \`#1964 \`\_\_ v5.18.0 (2021-04-08) -------------------- Features ~~~~~~~~ - Add \`\`w3.eth.modify\_transaction\`\` deprecate \`\`w3.eth.modifyTransaction\`\` (\`#1886 \`\_\_) - Add \`\`w3.eth.get\_transaction\_receipt\`\`, deprecate \`\`w3.eth.getTransactionReceipt\`\` (\`#1893 \`\_\_) - Add \`\`w3.eth.wait\_for\_transaction\_receipt\`\` deprecate \`\`w3.eth.waitForTransactionReceipt\`\` (\`#1896 \`\_\_) - Add \`\`w3.eth.set\_contract\_factory\`\` deprecate \`\`w3.eth.setContractFactory\`\` (\`#1900 \`\_\_) - Add \`\`w3.eth.generate\_gas\_price\`\` deprecate \`\`w3.eth.generateGasPrice\`\` (\`#1905 \`\_\_) - Add \`\`w3.eth.set\_gas\_price\_strategy\`\` deprecate \`\`w3.eth.setGasPriceStrategy\`\` (\`#1906 \`\_\_) - Add \`\`w3.eth.estimate\_gas\`\` deprecate \`\`w3.eth.estimateGas\`\` (\`#1913 \`\_\_) - Add \`\`w3.eth.sign\_typed\_data\`\` deprecate \`\`w3.eth.signTypedData\`\` (\`#1915 \`\_\_) - Add \`\`w3.eth.get\_filter\_changes\`\` deprecate \`\`w3.eth.getFilterChanges\`\` (\`#1916 \`\_\_) - Add \`\`eth.get\_filter\_logs\`\`, deprecate \`\`eth.getFilterLogs\`\` (\`#1919 \`\_\_) - Add \`\`eth.uninstall\_filter\`\`, deprecate \`\`eth.uninstallFilter\`\` (\`#1920 \`\_\_) - Add \`\`w3.eth.get\_logs\`\` deprecate \`\`w3.eth.getLogs\`\` (\`#1925 \`\_\_) - Add \`\`w3.eth.submit\_hashrate\`\` deprecate \`\`w3.eth.submitHashrate\`\` (\`#1926 \`\_\_) - Add \`\`w3.eth.submit\_work\`\` deprecate \`\`w3.eth.submitWork\`\` (\`#1927 \`\_\_) - Add \`\`w3.eth.get\_work\`\`, deprecate \`\`w3.eth.getWork\`\` (\`#1934 \`\_\_) - Adds public get\_block\_number method. (\`#1937 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add ABI type examples to docs (\`#1890 \`\_\_) - Promote the new Ethereum Python Discord server on the README. (\`#1898 \`\_\_) - Escape reserved characters in install script of Contributing docs. (\`#1909 \`\_\_) - Add detailed event filtering examples. (\`#1910 \`\_\_) - Add docs example for tuning log levels. (\`#1928 \`\_\_) - Add some performance tips in troubleshooting docs. (\`#1929 \`\_\_) - Add existing contract interaction to docs examples. (\`#1933 \`\_\_) - Replace Gitter links with the Python Discord server. (\`#1936 \`\_\_) Misc ~~~~ - \`#1887 \`\_\_, \`#1907 \`\_\_, \`#1917 \`\_\_, \`#1930 \`\_\_, \`#1935 \`\_\_ v5.17.0 (2021-02-24) -------------------- Features ~~~~~~~~ - Added \`\`get\_transaction\_count\`\`, and deprecated \`\`getTransactionCount\`\` (\`#1844 \`\_\_) - Add \`\`w3.eth.send\_transaction\`\`, deprecate \`\`w3.eth.sendTransaction\`\` (\`#1878 \`\_\_) - Add \`\`web3.eth.sign\_transaction\`\`, deprecate \`\`web3.eth.signTransaction\`\` (\`#1879 \`\_\_) - Add \`\`w3.eth.send\_raw\_transaction\`\`, deprecate \`\`w3.eth.sendRawTransaction\`\` (\`#1880 \`\_\_) - Add \`\`w3.eth.replace\_transaction\`\` deprecate \`\`w3.eth.replaceTransaction\`\` (\`#1882 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix return type of \`\`send\_transaction\`\` in docs. (\`#686 \`\_\_) v5.16.0 (2021-02-04) -------------------- Features ~~~~~~~~ - Added \`\`get\_block\_transaction\_count\`\`, and deprecated \`\`getBlockTransactionCount\`\` (\`#1841 \`\_\_) - Move \`\`defaultAccount\`\` to \`\`default\_account\`\`. Deprecate \`\`defaultAccount\`\`. (\`#1848 \`\_\_) - Add \`\`eth.default\_block\`\`, deprecate \`\`eth.defaultBlock\`\`. Also adds \`\`parity.default\_block\`\`, and deprecates \`\`parity.defaultBlock\`\`. (\`#1849 \`\_\_) - Add \`\`eth.gas\_price\`\`, deprecate \`\`eth.gasPrice\`\` (\`#1850 \`\_\_) - Added \`\`eth.block\_number\`\` property. Deprecated \`\`eth.blockNumber\`\` (\`#1851 \`\_\_) - Add \`\`eth.chain\_id\`\`, deprecate \`\`eth.chainId\`\` (\`#1852 \`\_\_) - Add \`\`eth.protocol\_version\`\`, deprecate \`\`eth.protocolVersion\`\` (\`#1853 \`\_\_) - Add \`\`eth.get\_code\`\`, deprecate \`\`eth.getCode\`\` (\`#1856 \`\_\_) - Deprecate \`\`eth.getProof\`\`, add \`\`eth.get\_proof\`\` (\`#1857 \`\_\_) - Add \`\`eth.get\_transaction\`\`, deprecate \`\`eth.getTransaction\`\` (\`#1858 \`\_\_) - Add \`\`eth.get\_transaction\_by\_block\`\`, deprecate \`\`eth.getTransactionByBlock\`\` (\`#1859 \`\_\_) - Add get\_uncle\_by\_block, deprecate getUncleByBlock (\`#1862 \`\_\_) - Add get\_uncle\_count, deprecate getUncleCount (\`#1863 \`\_\_) Bugfixes ~~~~~~~~ - Fix event filter creation if the event ABI contains a \`\`values\`\` key. (\`#1807 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Remove v5 breaking changes link from the top of the release notes. (\`#1837 \`\_\_) - Add account creation troubleshooting docs. (\`#1855 \`\_\_) - Document passing a struct into a contract function. (\`#1860 \`\_\_) - Add instance configuration troubleshooting docs. (\`#1865 \`\_\_) - Clarify nonce lookup in sendRawTransaction docs. (\`#1866 \`\_\_) - Updated docs for web3.eth methods: eth.getTransactionReceipt and eth.waitForTransactionReceipt (\`#1868 \`\_\_) v5.15.0 (2021-01-15) -------------------- Features ~~~~~~~~ - Add \`\`get\_storage\_at\`\` method and deprecate \`\`getStorageAt\`\`. (\`#1828 \`\_\_) - Add \`\`eth.get\_block\`\` method and deprecate \`\`eth.getBlock\`\`. (\`#1829 \`\_\_) Bugfixes ~~~~~~~~ - PR #1585 changed the error that was coming back from eth-tester when the Revert opcode was called, which broke some tests in downstream libraries. This PR reverts back to raising the original error. (\`#1813 \`\_\_) - Added a new \`\`ContractLogicError\`\` for when a contract reverts a transaction. \`\`ContractLogicError\`\` will replace \`\`SolidityError\`\`, in v6. (\`#1814 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Introduce Beacon API documentation (\`#1836 \`\_\_) Misc ~~~~ - \`#1602 \`\_\_, \`#1827 \`\_\_, \`#1831 \`\_\_, \`#1833 \`\_\_, \`#1834 \`\_\_ v5.14.0 (2021-01-05) -------------------- Bugfixes ~~~~~~~~ - Remove docs/web3.\* from the gitignore to allow for the beacon docs to be added to git, and add \`\`beacon\`\` to the default web3 modules that get loaded. (\`#1824 \`\_\_) - Remove auto-documenting from the Beacon API (\`#1825 \`\_\_) Features ~~~~~~~~ - Introduce experimental Ethereum 2.0 beacon node API (\`#1758 \`\_\_) - Add new get\_balance method on Eth class. Deprecated getBalance. (\`#1806 \`\_\_) Misc ~~~~ - \`#1815 \`\_\_, \`#1816 \`\_\_ v5.13.1 (2020-12-03) -------------------- Bugfixes ~~~~~~~~ - Handle revert reason parsing for Ganache (\`#1794 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Document Geth and Parity/OpenEthereum fixture generation (\`#1787 \`\_\_) Misc ~~~~ - \`#1778 \`\_\_, \`#1780 \`\_\_, \`#1790 \`\_\_, \`#1791 \`\_\_, \`#1796 \`\_\_ v5.13.0 (2020-10-29) -------------------- Features ~~~~~~~~ - Raise \`SolidityError\` exceptions that contain the revert reason when a \`call\` fails. (\`#941 \`\_\_) Bugfixes ~~~~~~~~ - Update eth-tester dependency to fix tester environment install version conflict. (\`#1782 \`\_\_) Misc ~~~~ - \`#1757 \`\_\_, \`#1767 \`\_\_ v5.12.3 (2020-10-21) -------------------- Misc ~~~~ - \`#1752 \`\_\_, \`#1759 \`\_\_, \`#1773 \`\_\_, \`#1775 \`\_\_ v5.12.2 (2020-10-12) -------------------- Bugfixes ~~~~~~~~ - Address the use of multiple providers in the docs (\`#1701 \`\_\_) - Remove stale connection errors from docs (\`#1737 \`\_\_) - Allow ENS name resolution for methods that use the \`\`Method\`\` class (\`#1749 \`\_\_) Misc ~~~~ - \`#1727 \`\_\_, \`#1728 \`\_\_, \`#1733 \`\_\_, \`#1735 \`\_\_, \`#1741 \`\_\_, \`#1746 \`\_\_, \`#1748 \`\_\_, \`#1753 \`\_\_, \`#1768 \`\_\_ v5.12.1 (2020-09-02) -------------------- Misc ~~~~ - \`#1708 \`\_\_, \`#1709 \`\_\_, \`#1715 \`\_\_, \`#1722 \`\_\_, \`#1724 \`\_\_ v5.12.0 (2020-07-16) -------------------- Features ~~~~~~~~ - Update \`web3.pm\` and \`ethpm\` module to EthPM v3 specification. (\`#1652 \`\_\_) - Allow consumer to initialize \`HttpProvider\` with their own \`requests.Session\`. This allows the \`HttpAdapter\` connection pool to be tuned as desired. (\`#1469 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Use ethpm v3 packages in examples documentation. (\`#1683 \`\_\_) - Modernize the deploy contract example. (\`#1679 \`\_\_) - Add contribution guidelines and a code of conduct. (\`#1691 \`\_\_) Misc ~~~~ - \`#1687 \`\_\_ - \`#1690 \`\_\_ v5.12.0-beta.3 (2020-07-15) --------------------------- Bugfixes ~~~~~~~~ - Include ethpm-spec solidity examples in distribution. (\`#1686 \`\_\_) v5.12.0-beta.2 (2020-07-14) --------------------------- Bugfixes ~~~~~~~~ - Support ethpm-spec submodule in distributions. (\`#1682 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Modernize the deploy contract example. (\`#1679 \`\_\_) - Use ethpm v3 packages in examples documentation. (\`#1683 \`\_\_) v5.12.0-beta.1 (2020-07-09) --------------------------- Features ~~~~~~~~ - Allow consumer to initialize \`HttpProvider\` with their own \`requests.Session\`. This allows the \`HttpAdapter\` connection pool to be tuned as desired. (\`#1469 \`\_\_) - Update \`web3.pm\` and \`ethpm\` module to EthPM v3 specification. (\`#1652 \`\_\_) Bugfixes ~~~~~~~~ - Update outdated reference url in ethpm docs and tests. (\`#1680 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add a :meth:\`~web3.eth.Eth.getBalance\` example and provide more context for using the \`fromWei\` and \`toWei\` utility methods. (\`#1676 \`\_\_) - Overhaul the Overview documentation to provide a tour of major features. (\`#1681 \`\_\_) v5.11.1 (2020-06-17) -------------------- Bugfixes ~~~~~~~~ - Added formatter rules for eth\_tester middleware to allow :meth:\`~web3.eth.Eth.getBalance\` by using integer block numbers (\`#1660 \`\_\_) - Fix type annotations within the \`\`eth.py\`\` module. Several arguments that defaulted to \`\`None\`\` were not declared \`\`Optional\`\`. (\`#1668 \`\_\_) - Fix type annotation warning when using string URI to instantiate an HTTP or WebsocketProvider. (\`#1669 \`\_\_) - Fix type annotations within the \`\`web3\`\` modules. Several arguments that defaulted to \`\`None\`\` were not declared \`\`Optional\`\`. (\`#1670 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Breaks up links into three categories (Intro, Guides, and API) and adds content to the index page: a lib introduction and some "Getting Started" links. (\`#1671 \`\_\_) - Fills in some gaps in the Quickstart guide and adds provider connection details for local nodes. (\`#1673 \`\_\_) v5.11.0 (2020-06-03) -------------------- Features ~~~~~~~~ - Accept a block identifier in the \`\`Contract.estimateGas\`\` method. Includes a related upgrade of eth-tester to v0.5.0-beta.1. (\`#1639 \`\_\_) - Introduce a more specific validation error, \`\`ExtraDataLengthError\`\`. This enables tools to detect when someone may be connected to a POA network, for example, and provide a smoother developer experience. (\`#1666 \`\_\_) Bugfixes ~~~~~~~~ - Correct the type annotations of \`FilterParams.address\` (\`#1664 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Corrects the return value of \`\`getTransactionReceipt\`\`, description of caching middleware, and deprecated method names. (\`#1663 \`\_\_) - Corrects documentation of websocket timeout configuration. (\`#1665 \`\_\_) v5.10.0 (2020-05-18) -------------------- Features ~~~~~~~~ - An update of \`\`eth-tester\`\` includes a change of the default fork from Constantinople to Muir Glacier. \`#1636 \`\_\_ Bugfixes ~~~~~~~~ - \`\`my\_contract.events.MyEvent\`\` was incorrectly annotated so that \`\`MyEvent\`\` was marked as a \`\`ContractEvent\`\` instance. Fixed to be a class type, i.e., \`\`Type\[ContractEvent\]\`\`. (\`#1646 \`\_\_) - IPCProvider correctly handled \`\`pathlib.Path\`\` input, but warned against its type. Fixed to permit Path objects in addition to strings. (\`#1647 \`\_\_) Misc ~~~~ - \`#1636 \`\_\_ v5.9.0 (2020-04-30) ------------------- Features ~~~~~~~~ - Upgrade eth-account to use v0.5.2+. eth-account 0.5.2 adds support for hd accounts Also had to pin eth-keys to get dependencies to resolve. (\`#1622 \`\_\_) Bugfixes ~~~~~~~~ - Fix local\_filter\_middleware new entries bug (\`#1514 \`\_\_) - ENS \`\`name\`\` and ENS \`\`address\`\` can return \`\`None\`\`. Fixes return types. (\`#1633 \`\_\_) v5.8.0 (2020-04-23) ------------------- Features ~~~~~~~~ - Introduced \`\`list\_wallets\`\` method to the \`\`GethPersonal\`\` class. (\`#1516 \`\_\_) - Added block\_identifier parameter to \`ContractConstructor.estimateGas\` method. (\`#1588 \`\_\_) - Add snake\_case methods to Geth and Parity Personal Modules. Deprecate camelCase methods. (\`#1589 \`\_\_) - Added new weighted keyword argument to the time based gas price strategy. If \`\`True\`\`, it will more give more weight to more recent block times. (\`#1614 \`\_\_) - Adds support for Solidity's new(ish) receive function. Adds a new contract API that mirrors the existing fallback API: \`\`contract.receive\`\` (\`#1623 \`\_\_) Bugfixes ~~~~~~~~ - Fixed hasattr overloader method in the web3.ContractEvent, web3.ContractFunction, and web3.ContractCaller classes by implementing a try/except handler that returns False if an exception is raised in the \_\_getattr\_\_ overloader method (since \_\_getattr\_\_ HAS to be called in every \_\_hasattr\_\_ call). Created two new Exception classes, 'ABIEventFunctionNotFound' and 'ABIFunctionNotFound', which inherit from both AttributeError and MismatchedABI, and replaced the MismatchedABI raises in ContractEvent, ContractFunction, and ContractCaller with a raise to the created class in the \_\_getattr\_\_ overloader method of the object. (\`#1594 \`\_\_) - Change return type of rpc\_gas\_price\_strategy from int to Wei (\`#1612 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Fix typo in "Internals" docs. Changed asyncronous --> asynchronous (\`#1607 \`\_\_) - Improve documentation that introduces and troubleshoots Providers. (\`#1609 \`\_\_) - Add documentation for when to use each transaction method. (\`#1610 \`\_\_) - Remove incorrect web3 for w3 in doc example (\`#1615 \`\_\_) - Add examples for using web3.contract via the ethpm module. (\`#1617 \`\_\_) - Add dark mode to documentation. Also fixes a bunch of formatting issues in docs. (\`#1626 \`\_\_) Misc ~~~~ - \`#1545 \`\_\_ v5.7.0 (2020-03-16) ------------------- Features ~~~~~~~~ - Add snake\_case methods for the net module Also moved net module to use ModuleV2 instead of Module (\`#1592 \`\_\_) Bugfixes ~~~~~~~~ - Fix return type of eth\_getCode. Changed from Hexstr to HexBytes. (\`#1601 \`\_\_) Misc ~~~~ - \`#1590 \`\_\_ v5.6.0 (2020-02-26) ------------------- Features ~~~~~~~~ - Add snake\_case methods to Geth Miner class, deprecate camelCase methods (\`#1579 \`\_\_) - Add snake\_case methods for the net module, deprecate camelCase methods (\`#1581 \`\_\_) - Add PEP561 type marker (\`#1583 \`\_\_) Bugfixes ~~~~~~~~ - Increase replacement tx minimum gas price bump Parity/OpenEthereum requires a replacement transaction's gas to be a minimum of 12.5% higher than the original (vs. Geth's 10%). (\`#1570 \`\_\_) v5.5.1 (2020-02-10) ------------------- Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Documents the \`getUncleCount\` method. (\`#1534 \`\_\_) Misc ~~~~ - \`#1576 \`\_\_ v5.5.0 (2020-02-03) ------------------- Features ~~~~~~~~ - ENS had to release a new registry to push a bugfix. See \`this article \`\_ for background information. web3.py uses the new registry for all default ENS interactions, now. (\`#1573 \`\_\_) Bugfixes ~~~~~~~~ - Minor bugfix in how ContractCaller looks up abi functions. (\`#1552 \`\_\_) - Update modules to use compatible typing-extensions import. (\`#1554 \`\_\_) - Make 'from' and 'to' fields checksum addresses in returned transaction receipts (\`#1562 \`\_\_) - Use local Trinity's IPC socket if it is available, for newer versions of Trinity. (\`#1563 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Add Matomo Tracking to Docs site. Matomo is an Open Source web analytics platform that allows us to get better insights and optimize for our audience without the negative consequences of other compareable platforms. Read more: https://matomo.org/why-matomo/ (\`#1541 \`\_\_) - Fix web3 typo in docs (\`#1559 \`\_\_) Misc ~~~~ - \`#1521 \`\_\_, \`#1546 \`\_\_, \`#1571 \`\_\_ v5.4.0 (2019-12-06) ------------------- Features ~~~~~~~~ - Add \_\_str\_\_ to IPCProvider (\`#1536 \`\_\_) Bugfixes ~~~~~~~~ - Add required typing-extensions library to setup.py (\`#1544 \`\_\_) v5.3.1 (2019-12-05) ------------------- Bugfixes ~~~~~~~~ - Only apply hexbytes formatting to r and s values in transaction if present (\`#1531 \`\_\_) - Update eth-utils dependency which contains mypy bugfix. (\`#1537 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update Contract Event documentation to show correct example (\`#1515 \`\_\_) - Add documentation to methods that raise an error in v5 instead of returning \`\`None\`\` (\`#1527 \`\_\_) Misc ~~~~ - \`#1518 \`\_\_, \`#1532 \`\_\_ v5.3.0 (2019-11-14) ------------------- Features ~~~~~~~~ - Support handling ENS domains in ERC1319 URIs. (\`#1489 \`\_\_) Bugfixes ~~~~~~~~ - Make local block filter return empty list when when no blocks mined (\`#1255 \`\_\_) - Google protobuf dependency was updated to \`3.10.0\` (\`#1493 \`\_\_) - Infura websocket provider works when no secret key is present (\`#1501 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update Quickstart instructions to use the auto Infura module instead of the more complicated web3 auto module (\`#1482 \`\_\_) - Remove outdated py.test command from readme (\`#1483 \`\_\_) Misc ~~~~ - \`#1461 \`\_\_, \`#1471 \`\_\_, \`#1475 \`\_\_, \`#1476 \`\_\_, \`#1479 \`\_\_, \`#1488 \`\_\_, \`#1492 \`\_\_, \`#1498 \`\_\_ v5.2.2 (2019-10-21) ------------------- Features ~~~~~~~~ - Add poll\_latency to waitForTransactionReceipt (\`#1453 \`\_\_) Bugfixes ~~~~~~~~ - Fix flaky Parity whisper module test (\`#1473 \`\_\_) Misc ~~~~ - \`#1472 \`\_\_, \`#1474 \`\_\_ v5.2.1 (2019-10-17) ------------------- Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Update documentation for unlock account duration (\`#1464 \`\_\_) - Clarify module installation command for OSX>=10.15 (\`#1467 \`\_\_) Misc ~~~~ - \`#1468 \`\_\_ v5.2.0 (2019-09-26) ------------------- Features ~~~~~~~~ - Add \`\`enable\_strict\_bytes\_type\_checking\`\` flag to web3 instance (\`#1419 \`\_\_) - Move Geth Whisper methods to snake case and deprecate camel case methods (\`#1433 \`\_\_) Bugfixes ~~~~~~~~ - Add null check to logsbloom formatter (\`#1445 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Reformat autogenerated towncrier release notes (\`#1460 \`\_\_) Web3 5.1.0 (2019-09-18) ----------------------- Features ~~~~~~~~ - Add \`\`contract\_types\`\` property to \`\`Package\`\` class. (\`#1440 \`\_\_) Bugfixes ~~~~~~~~ - Fix flaky parity integration test in the whisper module (\`#1147 \`\_\_) Improved Documentation ~~~~~~~~~~~~~~~~~~~~~~ - Remove whitespace, move \`\`topics\`\` key -> \`\`topic\`\` in Geth docs (\`#1425 \`\_\_) - Enforce stricter doc checking, turning warnings into errors to fail CI builds to catch issues quickly. Add missing \`\`web3.tools.rst\`\` to the table of contents and fix incorrectly formatted JSON example. (\`#1437 \`\_\_) - Add example using Geth POA Middleware with Infura Rinkeby Node (\`#1444 \`\_\_) Misc ~~~~ - \`#1446 \`\_\_, \`#1451 \`\_\_ v5.0.2 ------ Released August 22, 2019 - Bugfixes - \[ethPM\] Fix bug in package id and release id fetching strategy - \`#1427 \`\_ v5.0.1 ------ Released August 15, 2019 - Bugfixes - \[ethPM\] Add begin/close chars to package name regex - \`#1418 \`\_ - \[ethPM\] Update deployments to work when only abi available - \`#1417 \`\_ - Fix tuples handled incorrectly in \`\`decode\_function\_input\`\` - \`#1410 \`\_ - Misc - Eliminate \`\`signTransaction\`\` warning - \`#1404 \`\_ v5.0.0 ------ Released August 1, 2019 - Features - \`\`web3.eth.chainId\`\` now returns an integer instead of hex - \`#1394 \`\_ - Bugfixes - Deprecation Warnings now show for methods that have a \`\`@combomethod\`\` decorator - \`#1401 \`\_ - Misc - \[ethPM\] Add ethPM to the docker file - \`#1405 \`\_ - Docs - Docs are updated to use checksummed addresses - \`#1390 \`\_ - Minor doc formatting fixes - \`#1338 \`\_ & \`#1345 \`\_ v5.0.0-beta.5 ------------- Released July 31, 2019 \*This is intended to be the final release before the stable v5 release.\* - Features - Parity operating mode can be read and set - \`#1355 \`\_ - Process a single event log, instead of a whole transaction receipt - \`#1354 \`\_ - Docs - Remove doctest dependency on ethtoken - \`#1395 \`\_ - Bugfixes - \[ethPM\] Bypass IPFS validation for large files - \`#1393 \`\_ - Misc - \[ethPM\] Update default Registry solidity contract - \`#1400 \`\_ - \[ethPM\] Update web3.pm to use new simple Registry implementation - \`#1398 \`\_ - Update dependency requirement formatting for releasing - \`#1403 \`\_ v5.0.0-beta.4 ------------- Released July 18,2019 - Features - \[ethPM\] Update registry uri to support basic uris w/o package id - \`#1389 \`\_ - Docs - Clarify in docs the return of \`\`Eth.sendRawTransaction()\`\` as a HexBytes object, not a string. - \`#1384 \`\_ - Misc - \[ethPM\] Migrate tests over from pytest-ethereum - \`#1385 \`\_ v5.0.0-beta.3 ------------- Released July 15, 2019 - Features - Add eth\_getProof support - \`#1185 \`\_ - Implement web3.pm.get\_local\_package() - \`#1372 \`\_ - Update registry URIs to support chain IDs - \`#1382 \`\_ - Add error flags to \`\`event.processReceipt\`\` - \`#1366 \`\_ - Bugfixes - Remove full IDNA processing in favor of UTS46 - \`#1364 \`\_ - Misc - Migrate py-ethpm library to web3/ethpm - \`#1379 \`\_ - Relax canonical address requirement in ethPM - \`#1380 \`\_ - Replace ethPM's infura strategy with web3's native infura support - \`#1383 \`\_ - Change \`\`combine\_argument\_formatters\`\` to \`\`apply\_formatters\_to\_sequence\`\` - \`#1360 \`\_ - Move \`\`pytest.xfail\`\` instances to \`\`@pytest.mark.xfail\`\` - \`#1376 \`\_ - Change \`\`net.version\`\` to \`\`eth.chainId\`\` in default transaction params - \`#1378 \`\_ v5.0.0-beta.2 ------------- Released May 13, 2019 - Features - Mark deprecated sha3 method as static - \`#1350 \`\_ - Upgrade to eth-account v0.4.0 - \`#1348 \`\_ - Docs - Add note about web3\[tester\] in documentation - \`#1325 \`\_ - Misc - Replace \`\`web3.\_utils.toolz\`\` imports with \`\`eth\_utils.toolz\`\` - \`#1317 \`\_ v5.0.0-beta.1 ------------- Released May 6, 2019 - Features - Add support for tilda in provider IPC Path - \`#1049 \`\_ - EIP 712 Signing Supported - \`#1319 \`\_ - Docs - Update contract example to use \`\`compile\_standard\`\` - \`#1263 \`\_ - Fix typo in middleware docs - \`#1339 \`\_ v5.0.0-alpha.11 --------------- Released April 24, 2019 - Docs - Add documentation for web3.py unit tests - \`#1324 \`\_ - Misc - Update deprecated collections.abc imports - \`#1334 \`\_ - Fix documentation typo - \`#1335 \`\_ - Upgrade eth-tester version - \`#1332 \`\_ v5.0.0-alpha.10 --------------- Released April 15, 2019 - Features - Add getLogs by blockHash - \`#1269 \`\_ - Implement chainId endpoint - \`#1295 \`\_ - Moved non-standard JSON-RPC endpoints to applicable Parity/Geth docs. Deprecated \`\`web3.version\`\` for \`\`web3.api\`\` - \`#1290 \`\_ - Moved Whisper endpoints to applicable Geth or Parity namespace - \`#1308 \`\_ - Added support for Goerli provider - \`#1286 \`\_ - Added addReservedPeer to Parity module - \`#1311 \`\_ - Bugfixes - Cast gas price values to integers in gas strategies - \`#1297 \`\_ - Missing constructor function no longer ignores constructor args - \`#1316 \`\_ - Misc - Require eth-utils >= 1.4, downgrade Go version for integration tests - \`#1310 \`\_ - Fix doc build warnings - \`#1331 \`\_ - Zip Fixture data - \`#1307 \`\_ - Update Geth version for integration tests - \`#1301 \`\_ - Remove unneeded testrpc - \`#1322 \`\_ - Add ContractCaller docs to v5 migration guide - \`#1323 \`\_ v5.0.0-alpha.9 -------------- Released March 26, 2019 - Breaking Changes - Raise error if there is no Infura API Key - \`#1294 \`\_ & - \`#1299 \`\_ - Misc - Upgraded Parity version for integration testing - \`#1292 \`\_ v5.0.0-alpha.8 -------------- Released March 20, 2019 - Breaking Changes - Removed \`\`web3/utils\`\` directory in favor of \`\`web3/\_utils\`\` - \`#1282 \`\_ - Relocated personal RPC endpoints to Parity and Geth class - \`#1211 \`\_ - Deprecated \`\`web3.net.chainId()\`\`, \`\`web3.eth.getCompilers()\`\`, and \`\`web3.eth.getTransactionFromBlock()\`\`. Removed \`\`web3.eth.enableUnauditedFeatures()\`\` - \`#1270 \`\_ - Relocated eth\_protocolVersion and web3\_clientVersion - \`#1274 \`\_ - Relocated \`\`web3.txpool\`\` to \`\`web3.geth.txpool\`\` - \`#1275 \`\_ - Relocated admin module to Geth namespace - \`#1288 \`\_ - Relocated miner module to Geth namespace - \`#1287 \`\_ - Features - Implement \`\`eth\_submitHashrate\`\` and \`\`eth\_submitWork\`\` JSONRPC endpoints. - \`#1280 \`\_ - Implement \`\`web3.eth.signTransaction\`\` - \`#1277 \`\_ - Docs - Added v5 migration docs - \`#1284 \`\_ v5.0.0-alpha.7 -------------- Released March 11, 2019 - Breaking Changes - Updated JSON-RPC calls that lookup txs or blocks to raise an error if lookup fails - \`#1218 \`\_ and \`#1268 \`\_ - Features - Tuple ABI support - \`#1235 \`\_ - Bugfixes - One last \`\`middleware\_stack\`\` was still hanging on. Changed to \`\`middleware\_onion\`\` - \`#1262 \`\_ v5.0.0-alpha.6 -------------- Released February 25th, 2019 - Features - New \`\`NoABIFound\`\` error for cases where there is no ABI - \`#1247 \`\_ - Misc - Interact with Infura using an API Key. Key will be required after March 27th. - \`#1232 \`\_ - Remove \`\`process\_type\`\` utility function in favor of eth-abi functionality - \`#1249 \`\_ v5.0.0-alpha.5 -------------- Released February 13th, 2019 - Breaking Changes - Remove deprecated \`\`buildTransaction\`\`, \`\`call\`\`, \`\`deploy\`\`, \`\`estimateGas\`\`, and \`\`transact\`\` methods - \`#1232 \`\_ - Features - Adds \`\`Web3.toJSON\`\` method - \`#1173 \`\_ - Contract Caller API Implemented - \`#1227 \`\_ - Add Geth POA middleware to use Rinkeby with Infura Auto - \`#1234 \`\_ - Add manifest and input argument validation to \`\`pm.release\_package()\`\` - \`#1237 \`\_ - Misc - Clean up intro and block/tx sections in Filter docs - \`#1223 \`\_ - Remove unnecessary \`\`EncodingError\`\` exception catching - \`#1224 \`\_ - Improvements to \`\`merge\_args\_and\_kwargs\`\` utility function - \`#1228 \`\_ - Update vyper registry assets - \`#1242 \`\_ v5.0.0-alpha.4 -------------- Released January 23rd, 2019 - Breaking Changes - Rename \`\`middleware\_stack\`\` to \`\`middleware\_onion\`\` - \`#1210 \`\_ - Drop already deprecated \`\`web3.soliditySha3\`\` - \`#1217 \`\_ - ENS: Stop inferring \`\`.eth\`\` TLD on domain names - \`#1205 \`\_ - Bugfixes - Validate \`\`ethereum\_tester\`\` class in \`\`EthereumTesterProvider\`\` - \`#1217 \`\_ - Support \`\`getLogs()\`\` method without creating filters - \`#1192 \`\_ - Features - Stablize the \`\`PM\`\` module - \`#1125 \`\_ - Implement async \`\`Version\`\` module - \`#1166 \`\_ - Misc - Update .gitignore to ignore \`\`.DS\_Store\`\` and \`\`.mypy\_cache/\`\` - \`#1215 \`\_ - Change CircleCI badge link to CircleCI project - \`#1214 \`\_ v5.0.0-alpha.3 -------------- Released January 15th, 2019 - Breaking Changes - Remove \`\`web3.miner.hashrate\`\` and \`\`web3.version.network\`\` - \`#1198 \`\_ - Remove \`\`web3.providers.tester.EthereumTesterProvider\`\` and \`\`web3.providers.tester.TestRPCProvider\`\` - \`#1199 \`\_ - Change \`\`manager.providers\`\` from list to single \`\`manager.provider\`\` - \`#1200 \`\_ - Replace deprecated \`\`web3.sha3\`\` method with \`\`web3.keccak\`\` method - \`#1207 \`\_ - Drop auto detect testnets for IPCProvider - \`#1206 \`\_ - Bugfixes - Add check to make sure blockHash exists - \`#1158 \`\_ - Misc - Remove some unreachable code in \`providers/base.py\` - \`#1160 \`\_ - Migrate tester provider results from middleware to defaults - \`#1188 \`\_ - Fix doc formatting for build\_filter method - \`#1187 \`\_ - Add ERC20 example in docs - \`#1178 \`\_ - Code style improvements - \`#1194 \`\_ & \`#1191 \`\_ - Convert Web3 instance variables to w3 - \`#1186 \`\_ - Update eth-utils dependencies and clean up other dependencies - \`#1195 \`\_ v5.0.0-alpha.2 -------------- Released December 20th, 2018 - Breaking Changes - Remove support for python3.5, drop support for eth-abi v1 - \`#1163 \`\_ - Features - Support for custom ReleaseManager was fixed - \`#1165 \`\_ - Misc - Fix doctest nonsense with unicorn token - \`3b2047 \`\_ - Docs for installing web3 in FreeBSD - \`#1156 \`\_ - Use latest python in readthedocs - \`#1162 \`\_ - Use twine in release script - \`#1164 \`\_ - Upgrade eth-tester, for eth-abi v2 support - \`#1168 \`\_ v5.0.0-alpha.1 -------------- Released December 13th, 2018 - Features - Add Rinkeby and Kovan Infura networks; made mainnet the default - \`#1150 \`\_ - Add parity-specific \`\`listStorageKeys\`\` RPC - \`#1145 \`\_ - Deprecated \`\`Web3.soliditySha3\`\`; use \`\`Web3.solidityKeccak\`\` instead. - \`#1139 \`\_ - Add default trinity locations to IPC path guesser - \`#1121 \`\_ - Add wss to \`\`AutoProvider\`\` - \`#1110 \`\_ - Add timeout for \`\`WebsocketProvider\`\` - \`#1109 \`\_ - Receipt timeout raises \`\`TimeExhausted\`\` - \`#1070 \`\_ - Allow specification of block number for \`\`eth\_estimateGas\`\` - \`#1046 \`\_ - Misc - Removed \`\`web3.\_utils.six\`\` support - \`#1116 \`\_ - Upgrade eth-utils to 1.2.0 - \`#1104 \`\_ - Require Python version 3.5.3 or greater - \`#1095 \`\_ - Bump websockets version to 7.0.0 - \`#1146 \`\_ - Bump parity test binary to 1.11.11 - \`#1064 \`\_ v4.8.2 -------- Released November 15, 2018 - Misc - Reduce unneeded memory usage - \`#1138 \`\_ v4.8.1 -------- Released October 28, 2018 - Features - Add timeout for WebsocketProvider - \`#1119 \`\_ - Reject transactions that send ether to non-payable contract functions - \`#1115 \`\_ - Add Auto Infura Ropsten support: \`\`from web3.auto.infura.ropsten import w3\`\` - \`#1124 \`\_ - Auto-detect trinity IPC file location - \`#1129 \`\_ - Misc - Require Python >=3.5.3 - \`#1107 \`\_ - Upgrade eth-tester and eth-utils - \`#1085 \`\_ - Configure readthedocs dependencies - \`#1082 \`\_ - soliditySha3 docs fixup - \`#1100 \`\_ - Update ropsten faucet links in troubleshooting docs v4.7.2 -------- Released September 25th, 2018 - Bugfixes - IPC paths starting with \`\`~\`\` are appropriately resolved to the home directory - \`#1072 \`\_ - You can use the local signing middleware with :class:\`bytes\`-type addresses - \`#1069 \`\_ v4.7.1 -------- Released September 11th, 2018 - Bugfixes - \`old pip bug \`\_ used during release made it impossible for non-windows users to install 4.7.0. v4.7.0 -------- Released September 10th, 2018 - Features - Add traceFilter method to the parity module. - \`#1051 \`\_ - Move :mod:\`~web3.utils.datastructures\` to public namespace :mod:\`~web3.datastructures\` to improve support for type checking. - \`#1038 \`\_ - Optimization to contract calls - \`#944 \`\_ - Bugfixes - ENS name resolution only attempted on mainnet by default. - \`#1037 \`\_ - Fix attribute access error when attributedict middleware is not used. - \`#1040 \`\_ - Misc - Upgrade eth-tester to 0.1.0-beta.32, and remove integration tests for py-ethereum. - Upgrade eth-hash to 0.2.0 with pycryptodome 3.6.6 which resolves a vulnerability. v4.6.0 -------- Released Aug 24, 2018 - Features - Support for Python 3.7, most notably in :class:\`~web3.providers.websocket.WebsocketProvider\` - \`#996 \`\_ - You can now decode a transaction's data to its original function call and arguments with: :meth:\`contract.decode\_function\_input() \` - \`#991 \`\_ - Support for :class:\`~web3.providers.ipc.IPCProvider\` in FreeBSD (and more readme docs) - \`#1008 \`\_ - Bugfixes - Fix crash in time-based gas strategies with small number of transactions - \`#983 \`\_ - Fx crash when passing multiple addresses to :meth:\`w3.eth.getLogs() \` - \`#1005 \`\_ - Misc - Disallow configuring filters with both manual and generated topic lists - \`#976 \`\_ - Add support for the upcoming eth-abi v2, which does ABI string decoding differently - \`#974 \`\_ - Add a lot more filter tests - \`#997 \`\_ - Add more tests for filtering with \`\`None\`\`. Note that geth & parity differ here. - \`#985 \`\_ - Follow-up on Parity bug that we reported upstream (\`parity#7816 \`\_): they resolved in 1.10. We removed xfail on that test. - \`#992 \`\_ - Docs: add an example of interacting with an ERC20 contract - \`#995 \`\_ - A couple doc typo fixes - \`#1006 \`\_ - \`#1010 \`\_ v4.5.0 -------- Released July 30, 2018 - Features - Accept addresses supplied in :class:\`bytes\` format (which does not provide checksum validation) - Improve estimation of gas prices - Bugfixes - Can now use a block number with :meth:\`~web3.eth.Eth.getCode\` when connected to :class:\`~web3.providers.eth\_tester.EthereumTesterProvider\` (without crashing) - Misc - Test Parity 1.11.7 - Parity integration tests upgrade to use sha256 instead of md5 - Fix some filter docs - eth-account upgrade to v0.3.0 - eth-tester upgrade to v0.1.0-beta.29 v4.4.1 -------- Released June 29, 2018 - Bugfixes - eth-pm package was renamed (old one deleted) which broke the web3 release. eth-pm was removed from the web3.py install until it's stable. - Misc - :class:\`~web3.providers.ipc.IPCProvider\` now accepts a :class:\`pathlib.Path\` argument for the IPC path - Docs explaining the new custom autoproviders in web3 v4.4.0 -------- Released June 21, 2018 - Features - Add support for https in WEB3\_PROVIDER\_URI environment variable - Can send websocket connection parameters in :class:\`~web3.providers.websocket.WebsocketProvider\` - Two new auto-initialization options: - \`\`from web3.auto.gethdev import w3\`\` - \`\`from web3.auto.infura import w3\`\` (After setting the \`\`INFURA\_API\_KEY\`\` environment variable) - Alpha support for a new package management tool based on ethpm-spec - Bugfixes - Can now receive large responses in :class:\`~web3.providers.websocket.WebsocketProvider\` by specifying a large \`\`max\_size\`\` in the websocket connection parameters. - Misc - Websockets dependency upgraded to v5 - Raise deprecation warning on :meth:\`~web3.eth.Eth.getTransactionFromBlock\` - Fix docs for :meth:\`~web3.eth.Eth.waitForTransactionReceipt\` - Developer Dockerfile now installs testing dependencies v4.3.0 -------- Released June 6, 2018 - Features - Support for the ABI types like: \`fixedMxN \`\_ which is used by Vyper. - In-flight transaction-signing middleware: Use local keys as if they were hosted keys using the new \`\`sign\_and\_send\_raw\_middleware\`\` - New :meth:\`~web3.eth.Eth.getUncleByBlock\` API - New name :meth:\`~web3.eth.Eth.getTransactionByBlock\`, which replaces the deprecated :meth:\`~web3.eth.Eth.getTransactionFromBlock\` - Add several new Parity trace functions - New API to resolve ambiguous function calls, for example: - Two functions with the same name that accept similar argument types, like \`\`myfunc(uint8)\`\` and \`\`myfunc(int8)\`\`, and you want to call \`\`contract.functions.myfunc(1).call()\`\` - See how to use it at: :ref:\`ambiguous-contract-functions\` - Bugfixes - Gas estimation doesn't crash, when 0 blocks are available. (ie~ on the genesis block) - Close out all HTTPProvider sessions, to squash warnings on exit - Stop adding Contract address twice to the filter. It was making some nodes unhappy - Misc - Friendlier json encoding/decoding failure error messages - Performance improvements, when the responses from the node are large (by reducing the number of times we evaluate if the response is valid json) - Parity CI test fixes (ugh, environment setup hell, thanks to the community for cleaning this up!) - Don't crash when requesting a transaction that was created with the parity bug (which allowed an unsigned transaction to be included, so \`\`publicKey\`\` is \`\`None\`\`) - Doc fixes: addresses must be checksummed (or ENS names on mainnet) - Enable local integration testing of parity on non-Debian OS - README: - Testing setup for devs - Change the build badge from Travis to Circle CI - Cache the parity binary in Circle CI, to reduce the impact of their binary API going down - Dropped the dot: \`\`py.test\`\` -> \`\`pytest\`\` v4.2.1 -------- Released May 9, 2018 - Bugfixes - When :meth:\`getting a transaction \` with data attached and trying to :meth:\`modify it \` (say, to increase the gas price), the data was not being reattached in the new transaction. - :meth:\`web3.personal.sendTransaction\` was crashing when using a transaction generated with \`\`buildTransaction()\`\` - Misc - Improved error message when connecting to a geth-style PoA network - Improved error message when address is not checksummed - Started in on support for \`\`fixedMxN\`\` ABI arguments - Lots of documentation upgrades, including: - Guide for understanding nodes/networks/connections - Simplified Quickstart with notes for common issues - A new Troubleshooting section - Potential pypy performance improvements (use toolz instead of cytoolz) - eth-tester upgraded to beta 24 v4.2.0 -------- Released Apr 25, 2018 - Removed audit warning and opt-in requirement for \`\`w3.eth.account\`\`. See more in: :ref:\`eth-account\` - Added an API to look up contract functions: \`\`fn = contract.functions\['function\_name\_here'\]\`\` - Upgrade Whisper (shh) module to use v6 API - Bugfix: set 'to' field of transaction to empty when using \`\`transaction = contract.constructor().buildTransaction()\`\` - You can now specify \`nonce\` in \`\`buildTransaction()\`\` - Distinguish between chain id and network id -- currently always return \`None\` for :attr:\`~web3.net.Net.chainId\` - Better error message when trying to use a contract function that has 0 or >1 matches - Better error message when trying to install on a python version <3.5 - Installs pypiwin32 during pip install, for a better Windows experience - Cleaned up a lot of test warnings by upgrading from deprecated APIs, especially from the deprecated \`\`contract.deploy(txn\_dict, args=contract\_args)\`\` to the new \`\`contract.constructor(\*contract\_args).transact(txn\_dict)\`\` - Documentation typo fixes - Better template for Pull Requests v4.1.0 -------- Released Apr 9, 2018 - New :class:\`~web3.providers.websocket.WebsocketProvider\`. If you're looking for better performance than HTTP, check out websockets. - New :meth:\`w3.eth.waitForTransactionReceipt() \` - Added name collision detection to ConciseContract and ImplicitContract - Bugfix to allow fromBlock set to 0 in createFilter, like \`\`contract.events.MyEvent.createFilter(fromBlock=0, ...)\`\` - Bugfix of ENS automatic connection - eth-tester support for Byzantium - New migration guide for v3 -> v4 upgrade - Various documentation updates - Pinned eth-account to older version v4.0.0 ----------------- Released Apr 2, 2018 - Marked beta.13 as stable - Documentation tweaks v4.0.0-beta.13 ----------------- Released Mar 27, 2018 \*This is intended to be the final release before the stable v4 release.\* - Add support for geth 1.8 (fixed error on :meth:\`~web3.eth.Eth.getTransactionReceipt\`) - You can now call a contract method at a specific block with the \`\`block\_identifier\`\` keyword argument, see: :meth:\`~web3.contract.ContractFunction.call\` - In preparation for stable release, disable \`\`w3.eth.account\`\` by default, until a third-party audit is complete & resolved. - New API for contract deployment, which enables gas estimation, local signing, etc. See :meth:\`~web3.contract.Contract.constructor\`. - Find contract events with :ref:\`contract.events.$my\_event.createFilter() \` - Support auto-complete for contract methods. - Upgrade most dependencies to stable - eth-abi - eth-utils - hexbytes - \*not included: eth-tester and eth-account\* - Switch the default EthereumTesterProvider backend from eth-testrpc to eth-tester: :class:\`web3.providers.eth\_tester.EthereumTesterProvider\` - A lot of documentation improvements - Test node integrations over a variety of providers - geth 1.8 test suite v4.0.0-beta.12 ----------------- A little hiccup on release. Skipped. v4.0.0-beta.11 ----------------- Released Feb 28, 2018 - New methods to modify or replace pending transactions - A compatibility option for connecting to \`\`geth --dev\`\` -- see :ref:\`geth-poa\` - A new :attr:\`web3.net.chainId\` - Create a filter object from an existing filter ID. - eth-utils v1.0.1 (stable) compatibility v4.0.0-beta.10 ----------------- Released Feb 21, 2018 - bugfix: Compatibility with eth-utils v1-beta2 (the incompatibility was causing fresh web3.py installs to fail) - bugfix: crash when sending the output of \`\`contract.functions.myFunction().buildTransaction()\`\` to :meth:\`~web3.eth.Eth.sendTransaction\`. Now, having a chainID key does not crash sendTransaction. - bugfix: a TypeError when estimating gas like: \`\`contract.functions.myFunction().estimateGas()\`\` is fixed - Added parity integration tests to the continuous integration suite! - Some py3 and docs cleanup v4.0.0-beta.9 ------------- Released Feb 8, 2018 - Access event log parameters as attributes - Support for specifying nonce in eth-tester - \`Bugfix \`\_ dependency conflicts between eth-utils, eth-abi, and eth-tester - Clearer error message when invalid keywords provided to contract constructor function - New docs for working with private keys + set up doctests - First parity integration tests - replace internal implementation of w3.eth.account with :class:\`eth\_account.account.Account\` v4.0.0-beta.8 ------------- Released Feb 7, 2018, then recalled. It added 32MB of test data to git history, so the tag was deleted, as well as the corresponding release. (Although the release would not have contained that test data) v4.0.0-beta.7 ------------- Released Jan 29, 2018 - Support for :meth:\`web3.eth.Eth.getLogs\` in eth-tester with py-evm - Process transaction receipts with Event ABI, using \`Contract.events.myEvent(\*args, \*\*kwargs).processReceipt(transaction\_receipt)\` see :ref:\`event-log-object\` for the new type. - Add timeout parameter to :class:\`web3.providers.ipc.IPCProvider\` - bugfix: make sure \`idna\` package is always installed - Replace ethtestrpc with py-evm, in all tests - Dockerfile fixup - Test refactoring & cleanup - Reduced warnings during tests v4.0.0-beta.6 ------------- Released Jan 18, 2018 - New contract function call API: \`my\_contract.functions.my\_func().call()\` is preferred over the now deprecated \`my\_contract.call().my\_func()\` API. - A new, sophisticated gas estimation algorithm, based on the https://ethgasstation.info approach. You must opt-in to the new approach, because it's quite slow. We recommend using the new caching middleware. See :meth:\`web3.gas\_strategies.time\_based.construct\_time\_based\_gas\_price\_strategy\` - New caching middleware that can cache based on time, block, or indefinitely. - Automatically retry JSON-RPC requests over HTTP, a few times. - ConciseContract now has the address directly - Many eth-tester fixes. :class:\`web3.providers.eth\_tester.main.EthereumTesterProvider\` is now a legitimate alternative to :class:\`web3.providers.tester.EthereumTesterProvider\`. - ethtest-rpc removed from testing. Tests use eth-tester only, on pyethereum. Soon it will be eth-tester with py-evm. - Bumped several dependencies, like eth-tester - Documentation updates v4.0.0-beta.5 ------------- Released Dec 28, 2017 \* Improvements to working with eth-tester, using :class:\`~web3.providers.eth\_tester.EthereumTesterProvider\`: \* Bugfix the key names in event logging \* Add support for :meth:\`~web3.eth.Eth.sendRawTransaction\` \* :class:\`~web3.providers.ipc.IPCProvider\` now automatically retries on a broken connection, like when you restart your node \* New gas price engine API, laying groundwork for more advanced gas pricing strategies v4.0.0-beta.4 ------------- Released Dec 7, 2017 \* New :meth:\`~web3.contract.Contract.buildTransaction\` method to prepare contract transactions, offline \* New automatic provider detection, for \`\`w3 = Web3()\`\` initialization \* Set environment variable \`WEB3\_PROVIDER\_URI\` to suggest a provider for automatic detection \* New API to set providers like: \`\`w3.providers = \[IPCProvider()\]\`\` \* Crashfix: :meth:\`web3.eth.Eth.filter\` when retrieving logs with the argument 'latest' \* Bump eth-tester to v0.1.0-beta.5, with bugfix for filtering by topic \* Removed GPL lib \`\`pylru\`\`, now believed to be in full MIT license compliance. v4.0.0-beta.3 ------------- Released Dec 1, 2017 \* Fix encoding of ABI types: \`\`bytes\[\]\`\` and \`\`string\[\]\`\` \* Windows connection error bugfix \* Bugfix message signatures that were broken ~1% of the time (zero-pad \`\`r\`\` and \`\`s\`\`) \* Autoinit web3 now produces None instead of raising an exception on \`\`from web3.auto import w3\`\` \* Clearer errors on formatting failure (includes field name that failed) \* Python modernization, removing Py2 compatibility cruft \* Update dependencies with changed names, now: \* \`\`eth-abi\`\` \* \`\`eth-keyfile\`\` \* \`\`eth-keys\`\` \* \`\`eth-tester\`\` \* \`\`eth-utils\`\` \* Faster Travis CI builds, with cached geth binary v4.0.0-beta.2 ------------- Released Nov 22, 2017 Bug Fixes: \* :meth:\`~web3.eth.Eth.sendRawTransaction\` accepts raw bytes \* :meth:\`~web3.eth.Eth.contract\` accepts an ENS name as contract address \* :meth:\`~web3.account.Account.signTransaction\` returns the expected hash (\*after\* signing the transaction) \* :class:\`~web3.account.Account\` methods can all be called statically, like: \`\`Account.sign(...)\`\` \* :meth:\`~web3.eth.Eth.getTransactionReceipt\` returns the \`\`status\`\` field as an \`\`int\`\` \* :meth:\`Web3.soliditySha3\` looks up ENS names if they are supplied with an "address" ABI \* If running multiple threads with the same w3 instance, \`\`ValueError: Recursively called ...\`\` is no longer raised Plus, various python modernization code cleanups, and testing against geth 1.7.2. v4.0.0-beta.1 ------------- \* Python 3 is now required \* ENS names can be used anywhere that a hex address can \* Sign transactions and messages with local private keys \* New filter mechanism: :meth:\`~web3.utils.filters.Filter.get\_all\_entries\` and :meth:\`~web3.utils.filters.Filter.get\_new\_entries\` \* Quick automatic initialization with \`\`from web3.auto import w3\`\` \* All addresses must be supplied with an EIP-55 checksum \* All addresses are returned with a checksum \* Renamed \`\`Web3.toDecimal()\`\` to \`\`toInt()\`\`, see: :ref:\`overview\_type\_conversions\` \* All filter calls are synchronous, gevent integration dropped \* Contract :meth:\`~web3.contract.Contract.eventFilter\` has replaced both \`\`Contract.on()\`\` and \`\`Contract.pastEvents()\`\` \* Contract arguments of \`\`bytes\`\` ABI type now accept hex strings. \* Contract arguments of \`\`string\`\` ABI type now accept python \`\`str\`\`. \* Contract return values of \`\`string\`\` ABI type now return python \`\`str\`\`. \* Many methods now return a \`\`bytes\`\`-like object where they used to return a hex string, like in :meth:\`Web3.sha3()\` \* IPC connection left open and reused, rather than opened and closed on each call \* A number of deprecated methods from v3 were removed 3.16.1 ------ \* Addition of \`\`ethereum-tester\`\` as a dependency 3.16.0 ------ \* Addition of \*named\* middlewares for easier manipulation of middleware stack. \* Provider middlewares can no longer be modified during runtime. \* Experimental custom ABI normalization API for Contract objects. 3.15.0 ------ \* Change docs to use RTD theme \* Experimental new \`\`EthereumTesterProvider\`\` for the \`\`ethereum-tester\`\` library. \* Bugfix for \`\`function\`\` type abi encoding via \`\`ethereum-abi-utils\`\` upgrade to \`\`v0.4.1\`\` \* Bugfix for \`\`Web3.toHex\`\` to conform to RPC spec. 3.14.2 ------ \* Fix PyPi readme text. 3.14.1 ------ \* Fix PyPi readme text. 3.14.0 ------ \* New \`\`stalecheck\_middleware\`\` \* Improvements to \`\`Web3.toHex\`\` and \`\`Web3.toText\`\`. \* Improvements to \`\`Web3.sha3\`\` signature. \* Bugfixes for \`\`Web3.eth.sign\`\` api 3.13.5 ------ \* Add experimental \`\`fixture\_middleware\`\` \* Various bugfixes introduced in middleware API introduction and migration to formatter middleware. 3.13.4 ------ \* Bugfix for formatter handling of contract creation transaction. 3.13.3 ------ \* Improved testing infrastructure. 3.13.2 ------ \* Bugfix for retrieving filter changes for both new block filters and pending transaction filters. 3.13.1 ------ \* Fix mispelled \`\`attrdict\_middleware\`\` (was spelled \`\`attrdict\_middlware\`\`). 3.13.0 ------ \* New Middleware API \* Support for multiple providers \* New \`\`web3.soliditySha3\`\` \* Remove multiple functions that were never implemented from the original web3. \* Deprecated \`\`web3.currentProvider\`\` accessor. Use \`\`web3.provider\`\` now instead. \* Deprecated password prompt within \`\`web3.personal.newAccount\`\`. 3.12.0 ------ \* Bugfix for abi filtering to correctly handle \`\`constructor\`\` and \`\`fallback\`\` type abi entries. 3.11.0 ------ \* All web3 apis which accept \`\`address\`\` parameters now enforce checksums if the address \*looks\* like it is checksummed. \* Improvements to error messaging with when calling a contract on a node that may not be fully synced \* Bugfix for \`\`web3.eth.syncing\`\` to correctly handle \`\`False\`\` 3.10.0 ------ \* Web3 now returns \`\`web3.utils.datastructures.AttributeDict\`\` in places where it previously returned a normal \`\`dict\`\`. \* \`\`web3.eth.contract\`\` now performs validation on the \`\`address\`\` parameter. \* Added \`\`web3.eth.getWork\`\` API 3.9.0 ----- \* Add validation for the \`\`abi\`\` parameter of \`\`eth\`\` \* Contract return values of \`\`bytes\`\`, \`\`bytesXX\`\` and \`\`string\`\` are no longer converted to text types and will be returned in their raw byte-string format. 3.8.1 ----- \* Bugfix for \`\`eth\_sign\`\` double hashing input. \* Removed deprecated \`\`DelegatedSigningManager\`\` \* Removed deprecate \`\`PrivateKeySigningManager\`\` 3.8.0 ----- \* Update pyrlp dependency to \`\`>=0.4.7\`\` \* Update eth-testrpc dependency to \`\`>=1.2.0\`\` \* Deprecate \`\`DelegatedSigningManager\`\` \* Deprecate \`\`PrivateKeySigningManager\`\` 3.7.1 ----- \* upstream version bump for bugfix in eth-abi-utils 3.7.0 ----- \* deprecate \`\`eth.defaultAccount\`\` defaulting to the coinbase account. 3.6.2 ----- \* Fix error message from contract factory creation. \* Use \`\`ethereum-utils\`\` for utility functions. 3.6.1 ----- \* Upgrade \`\`ethereum-abi-utils\`\` dependency for upstream bugfix. 3.6.0 ----- \* Deprecate \`\`Contract.code\`\`: replaced by \`\`Contract.bytecode\`\` \* Deprecate \`\`Contract.code\_runtime\`\`: replaced by \`\`Contract.bytecode\_runtime\`\` \* Deprecate \`\`abi\`\`, \`\`code\`\`, \`\`code\_runtime\`\` and \`\`source\`\` as arguments for the \`\`Contract\`\` object. \* Deprecate \`\`source\`\` as a property of the \`\`Contract\`\` object \* Add \`\`Contract.factory()\`\` API. \* Deprecate the \`\`construct\_contract\_factory\`\` helper function. 3.5.3 ----- \* Bugfix for how \`\`requests\`\` library is used. Now reuses session. 3.5.2 ----- \* Bugfix for construction of \`\`request\_kwargs\`\` within HTTPProvider 3.5.1 ----- \* Allow \`\`HTTPProvider\`\` to be imported from \`\`web3\`\` module. \* make \`\`HTTPProvider\`\` accessible as a property of \`\`web3\`\` instances. 3.5.0 ----- \* Deprecate \`\`web3.providers.rpc.RPCProvider\`\` \* Deprecate \`\`web3.providers.rpc.KeepAliveRPCProvider\`\` \* Add new \`\`web3.providers.rpc.HTTPProvider\`\` \* Remove hard dependency on gevent. 3.4.4 ----- \* Bugfix for \`\`web3.eth.getTransaction\`\` when the hash is unknown. 3.4.3 ----- \* Bugfix for event log data decoding to properly handle dynamic sized values. \* New \`\`web3.tester\`\` module to access extra RPC functionality from \`\`eth-testrpc\`\` 3.4.2 ----- \* Fix package so that \`\`eth-testrpc\`\` is not required. 3.4.1 ----- \* Force gevent<1.2.0 until this issue is fixed: https://github.com/gevent/gevent/issues/916 3.4.0 ----- \* Bugfix for contract instances to respect \`\`web3.eth.defaultAccount\`\` \* Better error reporting when ABI decoding fails for contract method response. 3.3.0 ----- \* New \`\`EthereumTesterProvider\`\` now available. Faster test runs than \`\`TestRPCProvider\`\` \* Updated underlying eth-testrpc requirement. 3.2.0 ----- \* \`\`web3.shh\`\` is now implemented. \* Introduced \`\`KeepAliveRPCProvider\`\` to correctly recycle HTTP connections and use HTTP keep alive 3.1.1 ----- \* Bugfix for contract transaction sending not respecting the \`\`web3.eth.defaultAccount\`\` configuration. 3.1.0 ----- \* New DelegatedSigningManager and PrivateKeySigningManager classes. 3.0.2 ----- \* Bugfix or IPCProvider not handling large JSON responses well. 3.0.1 ----- \* Better RPC compliance to be compatable with the Parity JSON-RPC server. 3.0.0 ----- \* \`\`Filter\`\` objects now support controlling the interval through which they poll using the \`\`poll\_interval\`\` property 2.9.0 ----- \* Bugfix generation of event topics. \* Web3.Iban now allows access to Iban address tools. 2.8.1 ----- \* Bugfix for \`\`geth.ipc\`\` path on linux systems. 2.8.0 ----- \* Changes to the \`\`Contract\`\` API: \* \`\`Contract.deploy()\`\` parameter arguments renamed to args \* \`\`Contract.deploy()\`\` now takes args and kwargs parameters to allow constructing with keyword arguments or positional arguments. \* \`\`Contract.pastEvents\`\` now allows you to specify a \`\`fromBlock or \`\`toBlock.\`\` Previously these were forced to be \`\`'earliest'\`\` and \`\`web3.eth.blockNumber\`\` respectively. \* \`\`Contract.call\`\`, \`\`Contract.transact\`\` and \`\`Contract.estimateGas\`\` are now callable as class methods as well as instance methods. When called this way, an address must be provided with the transaction parameter. \* \`\`Contract.call\`\`, \`\`Contract.transact\`\` and \`\`Contract.estimateGas\`\` now allow specifying an alternate address for the transaction. \* \`\`RPCProvider\`\` now supports the following constructor arguments. \* \`\`ssl\`\` for enabling SSL \* \`\`connection\_timeout\`\` and \`\`network\_timeout\`\` for controlling the timeouts for requests. 2.7.1 ----- \* Bugfix: Fix KeyError in merge\_args\_and\_kwargs helper fn. 2.7.0 ----- \* Bugfix for usage of block identifiers 'latest', 'earliest', 'pending' \* Sphinx documentation \* Non-data transactions now default to 90000 gas. \* Web3 object now has helpers set as static methods rather than being set at initialization. \* RPCProvider now takes a \`\`path\`\` parameter to allow configuration for requests to go to paths other than \`\`/\`\`. 2.6.0 ----- \* TestRPCProvider no longer dumps logging output to stdout and stderr. \* Bugfix for return types of \`\`address\[\]\`\` \* Bugfix for event data types of \`\`address\`\` 2.5.0 ----- \* All transactions which contain a \`\`data\`\` element will now have their gas automatically estimated with 100k additional buffer. This was previously only true with transactions initiated from a \`\`Contract\`\` object. 2.4.0 ----- \* Contract functions can now be called using keyword arguments. 2.3.0 ----- \* Upstream fixes for filters \* Filter APIs \`\`on\`\` and \`\`pastEvents\`\` now callable as both instance and class methods. 2.2.0 ----- \* The filters that come back from the contract \`\`on\`\` and \`\`pastEvents\`\` methods now call their callbacks with the same data format as \`\`web3.js\`\`. 2.1.1 ----- \* Cast RPCProvider port to an integer. 2.1.0 ----- \* Remove all monkeypatching 2.0.0 ----- \* Pull in downstream updates to proper gevent usage. \* Fix \`\`eth\_sign\`\` \* Bugfix with contract operations mutating the transaction object that is passed in. \* More explicit linting ignore statements. 1.9.0 ----- \* BugFix: fix for python3 only \`\`json.JSONDecodeError\`\` handling. 1.8.0 ----- \* BugFix: \`\`RPCProvider\`\` not sending a content-type header \* Bugfix: \`\`web3.toWei\`\` now returns an integer instead of a decimal.Decimal 1.7.1 ----- \* \`\`TestRPCProvider\`\` can now be imported directly from \`\`web3\`\` 1.7.0 ----- \* Add \`\`eth.admin\`\` interface. \* Bugfix: Format the return value of \`\`web3.eth.syncing\`\` \* Bugfix: IPCProvider socket interactions are now more robust. 1.6.0 ----- \* Downstream package upgrades for \`\`eth-testrpc\`\` and \`\`ethereum-tester-client\`\` to handle configuration of the Homestead and DAO fork block numbers. 1.5.0 ----- \* Rename \`\`web3.contract.\_Contract\`\` to \`\`web3.contract.Contract\`\` to expose it for static analysis and auto completion tools \* Allow passing string parameters to functions \* Automatically compute gas requirements for contract deployment and \* transactions. \* Contract Filters \* Block, Transaction, and Log filters \* \`\`web3.eth.txpool\`\` interface \* \`\`web3.eth.mining\`\` interface \* Fixes for encoding. 1.4.0 ----- \* Bugfix to allow address types in constructor arguments. 1.3.0 ----- \* Partial implementation of the \`\`web3.eth.contract\`\` interface. 1.2.0 ----- \* Restructure project modules to be more \*flat\* \* Add ability to run test suite without the \*slow\* tests. \* Breakup \`\`encoding\`\` utils into smaller modules. \* Basic pep8 formatting. \* Apply python naming conventions to internal APIs \* Lots of minor bugfixes. \* Removal of dead code left behind from \`\`1.0.0\`\` refactor. \* Removal of \`\`web3/solidity\`\` module. 1.1.0 ----- \* Add missing \`\`isConnected()\`\` method. \* Add test coverage for \`\`setProvider()\`\` 1.0.1 ----- \* Specify missing \`\`pyrlp\`\` and \`\`gevent\`\` dependencies 1.0.0 ----- \* Massive refactor to the majority of the app. 0.1.0 ----- \* Initial release ---