Skip to content

Commit

Permalink
fix: dont cache when block id givne
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey committed Jan 28, 2025
1 parent 87f6e27 commit ea8325d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
12 changes: 8 additions & 4 deletions src/ape/managers/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -970,17 +970,21 @@ def get_code(
self, address: AddressType, block_id: Optional["BlockID"] = None
) -> "ContractCode":
network = self.provider.network
if network.is_dev:
# Avoid caching when dev, as you can manipulate the chain more
# (and there is isolation).

# Two reasons to avoid caching:
# 1. dev networks - chain isolation makes this mess up
# 2. specifying block_id= kwarg - likely checking if code
# exists at the time and shouldn't use cache.
skip_cache = network.is_dev or block_id is not None
if skip_cache:
return self.provider.get_code(address, block_id=block_id)

self._code.setdefault(network.ecosystem.name, {})
self._code[network.ecosystem.name].setdefault(network.name, {})
if address in self._code[network.ecosystem.name][network.name]:
return self._code[network.ecosystem.name][network.name][address]

# Get from RPC for the first time.
# Get from RPC for the first time AND use cache.
code = self.provider.get_code(address)
self._code[network.ecosystem.name][network.name][address] = code
return code
2 changes: 1 addition & 1 deletion tests/functional/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ def create_mock_sepolia(ethereum, eth_tester_provider, vyper_contract_instance):
@contextmanager
def fn():
# Ensuring contract exists before hack.
# This allow the network to be past genesis which is more realistic.
# This allows the network to be past genesis which is more realistic.
_ = vyper_contract_instance
eth_tester_provider.network.name = "sepolia"
yield eth_tester_provider.network
Expand Down
18 changes: 18 additions & 0 deletions tests/functional/geth/test_chain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from tests.conftest import geth_process_test


@geth_process_test
def test_get_code(mocker, chain, geth_contract, mock_sepolia):
# NOTE: Using mock_sepolia because code doesn't get cached in local networks.
actual = chain.get_code(geth_contract.address)
expected = chain.provider.get_code(geth_contract.address)
assert actual == expected

# Ensure uses cache (via not using provider).
provider_spy = mocker.spy(chain.provider.web3.eth, "get_code")
_ = chain.get_code(geth_contract.address)
assert provider_spy.call_count == 0

# block_id test, cache should interfere.
actual_2 = chain.get_code(geth_contract.address, block_id=0)
assert not actual_2 # Doesn't exist at block 0.

0 comments on commit ea8325d

Please sign in to comment.