Mines num_blocks new blocks, returning an iterable of the newly mined block hashes.
EthereumTester.mine_block(coinbase=ZERO_ADDRESS)
Mines a single new block, returning the mined block's hash.
Auto-mining transactions
By default, all transactions are mined immediately. This means that each transaction you send will result in a new block being mined, and that all blocks will only ever have at most a single transaction. This behavior can be controlled with the following methods.
EthereumTester.enable_auto_mine_transactions()
Turns on auto-mining of transactions.
EthereumTester.disable_auto_mine_transactions()
Turns off auto-mining of transactions.
Accounts
The following API can be used to interact with account data. The account
parameter in these methods must be a hexadecimal encoded address.
EthereumTester.get_accounts()
Returns an iterable of the accounts that the tester knows about. All accounts
in this list will be EIP55 checksummed.
By default, added accounts are unlocked and do not have a password. If you
would like to add an account which has a password, you can supply the password
as the second parameter.
By default, accounts will be unlocked indefinitely. You can however unlock an
account for a specified amount of time by providing the desired duration in
seconds.
Returns the block for the given block_number. See block
numbers for named block numbers you can use. If
full_transactions is truthy, then the transactions array will be populated
with full transaction objects as opposed to their hashes.
Raises BlockNotFound if a block for the given number
cannot be found.
Receipts for unmined transactions will have all of block_hash, block_number and transaction_index set to None.
Receipts for transactions which create a contract will have the created contract address in the contract_address field.
Transaction Sending
A transaction is a formatted as a dictionary with the following keys and
values.
from: The address of the account sending the transaction (hexadecimal string).
to: The address of the account the transaction is being sent to. Empty string should be used to trigger contract creation (hexadecimal string).
gas: Sets the gas limit for transaction execution (integer).
value: The amount of ether in wei that should be sent with the transaction (integer).
data: The data for the transaction (hexadecimal string).
chain_id: The integer id for the chain the transaction is meant to interact with.
In addition to the above, the following parameters are added based on the type of transaction being sent:
Legacy transactions
gas_price: Sets the price per unit of gas in wei that will be paid for transaction execution (integer).
Access list transactions (EIP-2930)
gas_price: Sets the price per unit of gas in wei that will be paid for transaction execution (integer).
access_list (optional): Specifies accounts and storage slots expected to be accessed, based on the transaction, in order to
gain a discount on the gas for those executions (see quickstart example for usage).
Dynamic fee transactions (EIP-1559)
max_fee_per_gas: Sets the maximum fee per unit of gas in wei that will be paid for transaction execution (integer).
max_priority_fee_per_gas: Sets the fee per unit of gas in wei that is sent to the coinbase address as an incentive for including the transaction (integer).
access_list (optional): Specifies accounts and storage slots expected to be accessed, based on the transaction, in order to
gain a discount on the gas for those executions (see quickstart example for usage).
Executes the provided transaction object at the evm state from the block
denoted by the block_number parameter, returning the resulting bytes return
value from the evm.
Executes the provided transaction object at the evm state from the block
denoted by the block_number parameter, measuring and returning the gas
consumption.
Return the historical gas information for the number of blocks specified as the block_count starting from newest_block.
Note that specifying reward_percentiles has no effect on the response and so reward will always return an empty list.
Logs and Filters
EthereumTester.create_block_filter() -> integer
Creates a new filter for newly mined blocks. Returns the filter_id which can
be used to retrieve the block hashes for the mined blocks.
Creates a new filter for pending transactions. Returns the filter_id which
can be used to retrieve the transaction hashes for the pending transactions.
Removes the filter for the provided filter_id. If no filter is found for the
given filter_id, raises FilterNotFound.
EthereumTester.get_only_filter_changes(filter_id) -> transaction_hash or block_hash or log_entry
Returns all new values for the provided filter_id that have not previously
been returned through this API. Raises
FilterNotFound if no filter is found for the given
filter_id.
EthereumTester.get_all_filter_logs(filter_id) -> transaction_hash or block_hash or log_entry
Returns all values for the provided filter_id. Raises
FilterNotFound if no filter is found for the given
filter_id.
Snapshots and Resetting
EthereumTester.take_snapshot() -> snapshot_id
Takes a snapshot of the current chain state and returns the snapshot id.
EthereumTester.revert_to_snapshot(snapshot_id)
Reverts the chain to the chain state associated with the given snapshot_id.
Raises SnapshotNotFound if no snapshot is known
for the given id.
Errors and Exceptions
eth_tester.exceptions.TransactionNotFound
Raised in cases where a transaction cannot be found for the provided transaction hash.
eth_tester.exceptions.BlockNotFound
Raised in cases where a block cannot be found for either a provided number or
hash.
eth_tester.exceptions.FilterNotFound
Raised in cases where a filter cannot be found for the provided filter id.
eth_tester.exceptions.SnapshotNotFound
Raised in cases where a snapshot cannot be found for the provided snapshot id.
Backends
Ethereum tester is written using a pluggable backend system.
Backend Dependencies
Ethereum tester does not install any of the dependencies needed to use the
various backends by default. You can however install ethereum tester with the
necessary dependencies using the following method.
You can select which backend in a few different ways.
The most direct way is to manually pass in the backend instance you wish to
use.
>>> from eth_tester import EthereumTester, MockBackend
>>> t = EthereumTester(backend=MockBackend())
Ethereum tester also supports configuration using the environment variable
ETHEREUM_TESTER_CHAIN_BACKEND. This should be set to the import path for the
backend class you wish to use.
Available Backends
Ethereum tester can be used with the following backends.
MockBackend
PyEVM (experimental)
MockBackend
This backend has limited functionality. It cannot perform any VM computations.
It mocks out all of the objects and interactions.
>>> from eth_tester import EthereumTester, MockBackend
>>> t = EthereumTester(MockBackend())
PyEVM (experimental)
WARNING Py-EVM is experimental and should not be relied on for mission critical testing at this stage.
Uses the experimental Py-EVM library.
>>> from eth_tester import EthereumTester, PyEVMBackend
>>> t = EthereumTester(PyEVMBackend())
PyEVM Genesis Parameters and State
If you need to specify custom genesis parameters and state, you can build your own parameters dict to use instead of the default
when initializing a backend. Only default values can be overridden or a ValueError will be raised.
Then pass the generated custom_genesis_paramsdict to the backend's __init__
>>> from eth_tester import PyEVMBackend, EthereumTester
>>> pyevm_backend = PyEVMBackend(genesis_parameters=custom_genesis_params)
>>> t = EthereumTester(backend=pyevm_backend)
Similarly to genesis_parameters, override the genesis state by passing in an overridesdict
to PyEVMBackend.generate_genesis_state. Optionally, provide num_accounts to set the number of accounts.
For more control on which accounts the backend generates, use the from_mnemonic() classmethod. Give it
a mnemonic (and optionally the number of accounts) and it will use that information to generate the accounts.
Optionally, provide a genesis_state_overridesdict to adjust the genesis_state.
>>> from eth_tester import PyEVMBackend, EthereumTester
>>> from eth_utils import to_wei
>>> from hexbytes import HexBytes
>>>
>>> pyevm_backend = PyEVMBackend.from_mnemonic(
>>> 'test test test test test test test test test test test junk',
>>> genesis_state_overrides={'balance': to_wei(1000000, 'ether')}
>>> )
>>> t = EthereumTester(backend=pyevm_backend)
>>> print(t.get_accounts()[0]) # Outputs 0x1e59ce931B4CFea3fe4B875411e280e173cB7A9C
>>> print(t.get_balance('0x1e59ce931B4CFea3fe4B875411e280e173cB7A9C')) # Outputs 1000000000000000000000000
NOTE: The same state is applied to all generated test accounts.
For Example, to create 3 test accounts, each with a balance of 100 ETH each:
>>> from eth_tester import EthereumTester, PyEVMBackend
>>> from eth_utils import to_wei
>>> state_overrides = {'balance': to_wei(100, 'ether')}
>>> custom_genesis_state = PyEVMBackend.generate_genesis_state(overrides=state_overrides, num_accounts=3)
# Then pass the generated `custom_genesis_state` `dict` to the backend's `__init__`
>>> pyevm_backend = PyEVMBackend(genesis_state=custom_genesis_state)
>>> t = EthereumTester(backend=pyevm_backend)
Implementing Custom Backends
The base class eth_tester.backends.base.BaseChainBackend is the recommended
base class to begin with if you wish to write your own backend.
Details on implementation are beyond the scope of this document.
Data Formats
Ethereum tester uses two formats for data.
The normal format is the data format that is expected as input arguments to all EthereumTester methods as well as the return types from all method calls.
The canonical format is the data format that is used internally by the backend class.
Ethereum tester enforces strict validation rules on these formats.
Canonical Formats
The canonical format is intended for low level handling by backends.
32 byte hashes: bytes of length 32
Arbitrary length strings: bytes
Addresses: bytes of length 20
Integers: int
Array Types: tuple
Normal Formats
The normal format is intended for use by end users.
Addresses: 0x prefixed and EIP55 checksummed hexadecimal encoded text strings (not byte strings)
Integers: int
Array Types: tuple
Normalization and Validation
Beware! Here there be dragons... This section of the documentation is only
relevant if you intend to build tooling on top of this library.
The ethereum tester provides strong guarantees that backends can be swapped out
seamlessly without affecting the data formats of both the input arguments and
return values. This is accomplished using a two-step process of strict
normalization and validation.
All inputs to the methods of the EthereumTester are first validated then
normalized to a canonical format. Return values are put through this process
as well, first validating the data returned by the backend, and then
normalizing it from the canonical format to the normal form before being
returned.
Normalization
The EthereumTester delegates normalization to whatever normalizer was
passed in during instantiation. If no value was provided, the default
normalizer will be used from
eth_tester.normalization.default.DefaultNormalizer.
The specifics of this object are beyond the scope of this document.
Validation
The EthereumTester delegates validation to whatever validator was
passed in during instantiation. If no value was provided, the default
validator will be used from
eth_tester.validation.default.DefaultValidator.
The specifics of this object are beyond the scope of this document.
Use with Web3.py
See the web3.py documentation for
information on the EthereumTester provider which integrates with this
library.
Developer Setup
If you would like to hack on eth-tester, please check out the Snake Charmers
Tactical Manual
for information on how we do:
Testing
Pull Requests
Documentation
We use prek to maintain consistent code style. Once
installed, it will run automatically with every commit. You can also run it manually
with uv run prek run --all-files. If you need to make a commit that skips the prek checks, you
can do so with git commit --no-verify.
Development Environment Setup
You can set up your dev environment with the dev dependency group, which is
installed by default when you run uv sync.
git clone git@github.com:ApeWorX/eth-tester.git
cd eth-tester
uv sync --all-extras
uv run prek install
Release setup
To release a new version:
Create a GitHub Release with the desired tag, for example v0.13.0-beta.2.
GitHub Actions builds the package from that tag.
setuptools-scm derives the package version from the release tag.
The release workflow publishes to PyPI through trusted publishing.
Works well with
Use together with eth-tester: extensions, drivers, servers and companion tools.
eth-accountPythie’s Index: 52eth-account: Sign Ethereum transactions and messages with local private keys6.5M downloads/mo
eth-utilsPythie’s Index: 36eth-utils: Common utility functions for python code that interacts with Ethereum8.3M downloads/mo
eth-abiPythie’s Index: 46eth_abi: Python utilities for working with Ethereum ABI definitions, especially encoding and decoding7.7M downloads/mo