ape
ape copied to clipboard
Cache `get_code` requests
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)
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
do you want to set the call as a cached_property?
from functools import cached_property
...
@cached_property
def __call__(self, *args, **kwargs) -> ReceiptAPI:
...
?
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.
Brownie has some code around detecting selfdestructs https://github.com/eth-brownie/brownie/blob/89bb74fc283bf6561521ea3dee9747eb977cabaa/brownie/network/middlewares/caching.py#L33-L83