web3 / web3.js

Collection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.
https://web3js.org/
Other
19.16k stars 4.91k forks source link

Add a way to retrieve the ChainId of the current network #526

Closed adridadou closed 6 years ago

adridadou commented 7 years ago

EIP-155 introduced the need to know the chainId in order to sign a transaction.

It means that if you want to sign a transaction locally (and not on the node itself), then you need to set the chainId manually.

It would help to have a simple way to get it

sachabest commented 6 years ago

Is there an update on this? Or is there a way to sign transactions via private key without having to hardcode the chain ID into the client? That does not seem right.

fcorneli commented 6 years ago

Any progress on this one? Would be handy to be able to retrieve the ChainId when working on private networks.

kwaazaar commented 6 years ago

Try this: https://web3js.readthedocs.io/en/1.0/web3-net.html#getid

web3.eth.net.getId()
.then(console.log);

1

sohkai commented 5 years ago

@nivida It looks like web3.eth.getId() returns the networkId, not the chainId (sometimes the same, but sometimes different). There's a eth_chainId JSON-RPC endpoint available to find the chainId.

Actually it looks like this has been built 😅 (https://github.com/ethereum/web3.js/blob/cd32de24bf8751ab0d70f892dd968bbff25d7796/packages/web3-core-method/src/methods/network/ChainIdMethod.js); maybe it just needs to be added to the docs?

cbruguera commented 4 years ago

@sohkai How to call it with web3 though? I can't find anything on the docs. :-/

ryanio commented 4 years ago

hey @cbruguera, here you go: https://web3js.readthedocs.io/en/v1.2.8/web3-eth.html#getchainid

cbruguera commented 4 years ago

@ryanio yeah I just saw it. I'm using an older version of web3 though (v1.2.1) which is what comes with latest truffle version... I'll have to figure out another way. Or just use newer web3 for the actual production signing scripts (currently truffle-testing on ganache).

woodydeck commented 2 years ago

Hello from 2021. Five years and Web3 is still a mess...

I don't get why this call needs to be async. It should be returned procedurally. This is an antipattern. Let's just make dealing with accounts more difficult to the point we all learn Rust and develop for Solana.

Honestly, at this point it's easier to start from zero. This is just levels of dumb I can't comprehend.

Edit: And to anyone looking for the answer, save a global variable when you lookup and test the chain ID. It's going to be convoluted anyway, so what's one more variable?