I'm using the web3 Python module. Every time I call a function on the blockchain the module seems to call the eth_chainId
method first, apparently for validation reasons. This is very annoying due to log being full of these calls and also will be expensive due to the number of extra calls made.
Is there a way to disable these calls?
Best Answer
Before fix this issue
To understand why chain_id requested each time please read about the web3.py middleware and
middleware onion
. https://web3py.readthedocs.io/en/stable/middleware.htmlRoot cause (each time you execute a call or send a transaction,
chain_id
checked to be equal in your connection vs in your call): https://github.com/ethereum/web3.py/blob/68cc94769b531149ad33f6c0e5818a1880fc8486/web3/middleware/validation.py#L60Using simple cache mechanism (more web3.py way)
Read more about the web3.py cache: https://web3py.readthedocs.io/en/stable/middleware.html#cache
You can use
simple_cache_middleware
to cache everything out-of-box. Or use more sophisticatedtime_based_cache_middleware
andlatest_block_based_cache_middleware
.More gentle version of @kfx solution
Note: please be aware that this method will affect on library level. If you have several instances of Web3 (i.e. to with different accounts or to different blockchain ids), this change will affect all connections in current Python process (theoretically threads will be affected as well, but better to double check).
Performance
I was testing with scripts that included many
.call()
calls and severalbuild_transaction
."W/o optimisation (11:32)", "With skip validation (11:35)", "Cache chain_id (11:37)" test results is on graphic below.
Comments: