ape icon indicating copy to clipboard operation
ape copied to clipboard

Cache `get_code` requests

Open fubuloubu opened this issue 3 years ago • 4 comments

Just tried running a polling script and noticed that the following is_contract check is performed every time a call is made to the contract: https://github.com/ApeWorX/ape/blob/431f70020673f7e0d92da77e3480ff1468c68a47/src/ape/contracts/base.py#L197

This call is very easy to cache, as code should be immutable (in most circumstances)

fubuloubu avatar Feb 08 '22 05:02 fubuloubu

Note: even for contracts that can change their code (e.g. re-initializable proxies, contracts w/ selfdestruct opcodes, etc.), a quick call to EXTCODEHASH can sometimes save having to make a heavier call for getting the entire code

fubuloubu avatar Feb 08 '22 06:02 fubuloubu

do you want to set the call as a cached_property?

from functools import cached_property
...
@cached_property
def __call__(self, *args, **kwargs) -> ReceiptAPI:
...
?

johnson2427 avatar Feb 09 '22 15:02 johnson2427

do you want to set the call as a cached_property?

from functools import cached_property
...
@cached_property
def __call__(self, *args, **kwargs) -> ReceiptAPI:
...
?

No, each time a call is made by a contract we'd want the unique response there.

This is a deeper optimization needed, every time a ProviderAPI.get_code request is performed, it should check some sort of local cache to see if the request for that address has already been made (via chain manager?). It should then fetch the local cached copy if it's available, maybe doing a few checks to make sure it's still valid (EXTCODEHASH is the hash of the code), if the address has a contract that can somehow change itself (contains SELFDESTRUCT or is CREATE2 re-initializable). Contracts that can't change themselves won't ever need to be checked again because they are immutable.

fubuloubu avatar Feb 09 '22 19:02 fubuloubu

Brownie has some code around detecting selfdestructs https://github.com/eth-brownie/brownie/blob/89bb74fc283bf6561521ea3dee9747eb977cabaa/brownie/network/middlewares/caching.py#L33-L83

banteg avatar May 25 '22 10:05 banteg