Skip to content

Add chain_id setter to avoid eth_chainId requests #2207

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/2207.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add setter for the Eth.chain_id property
13 changes: 12 additions & 1 deletion tests/core/eth-module/test_eth_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@


def test_eth_protocol_version(w3):
assert w3.eth.protocol_version == '63'
with pytest.warns(DeprecationWarning):
assert w3.eth.protocol_version == '63'


def test_eth_protocolVersion(w3):
Expand All @@ -17,3 +18,13 @@ def test_eth_chain_id(w3):
def test_eth_chainId(w3):
with pytest.warns(DeprecationWarning):
assert w3.eth.chainId == 61


def test_set_chain_id(w3):
assert w3.eth.chain_id == 61

w3.eth.chain_id = 72
assert w3.eth.chain_id == 72

w3.eth.chain_id = None
assert w3.eth.chain_id == 61
10 changes: 9 additions & 1 deletion web3/eth.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
class BaseEth(Module):
_default_account: Union[ChecksumAddress, Empty] = empty
_default_block: BlockIdentifier = "latest"
_default_chain_id: Optional[int] = None
gasPriceStrategy = None

_gas_price: Method[Callable[[], Wei]] = Method(
Expand Down Expand Up @@ -629,7 +630,14 @@ def blockNumber(self) -> BlockNumber:

@property
def chain_id(self) -> int:
return self._chain_id()
if self._default_chain_id is None:
return self._chain_id()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to set _default_chain_id here before returning the value?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it totally would! (That's what I meant with: "As a further improvement, it may be beneficial to cache the result of the first eth_chainId request.")

But that would also change the current behavior and I don't know if that's something that is wanted.

else:
return self._default_chain_id

@chain_id.setter
def chain_id(self, value: int) -> None:
self._default_chain_id = value

@property
def chainId(self) -> int:
Expand Down