17

Is there a way to directly be able to retrieve CHAIN_ID information about the executing chain from a smart contract?

I know that for any chain that has EIP-155 implemented, CHAIN_IDs are retrievable from the v component of a signature but would require the passing of one for extraction.

Since CHAIN_ID is information about the chain I suspect that there should be a way to access this. Is there a way for Solidity to directly get this information?

1
  • 2
    Alternative: Because you are deploying the contract on a different chain you can give the chain id as a constructor parameter. Aug 17, 2018 at 14:40

3 Answers 3

17

As of version 0.5.12, Solidity includes an assembly function chainid() that provides access to the new CHAINID opcode:

function getChainID() external view returns (uint256) {
    uint256 id;
    assembly {
        id := chainid()
    }
    return id;
}

To use it, ensure you set the compiler's EVM version to Istanbul with the --evm-version istanbul flag.

Related documentation: Solidity Assembly - v0.5.12

3
30

chainid is available in native solidity 0.8.0. So you can get chain id like block timestamp or block number.

Here is the code.

block.chainid;

Documentation https://docs.soliditylang.org/en/v0.8.0/units-and-global-variables.html

Solidity update PR is here. https://github.com/ethereum/solidity/pull/10557

6
  • 2
    TypeError: "chainid" is not supported by the VM version (v0.8.0)
    – Jim
    Nov 24, 2021 at 19:56
  • 1
    FYI "Chain ID is a 256-bit value." - eips.ethereum.org/EIPS/eip-1344
    – Stiin
    Jan 12, 2022 at 20:43
  • I think the VM version and solidity version is a different thing. Solidity version v0.8.0 has "block.chainId" but VM implements eip-1344. Feb 3, 2022 at 11:15
  • That's seems like the better answer
    – Roy Toledo
    Apr 8, 2022 at 16:29
  • 1
    @Barney Chambers, solidity version and EVM version are two different things, you need to make sure the selected EVM version is at least Istanbul for block.chainid to compile.
    – hellopeach
    Dec 28, 2022 at 12:42
2

There isn't as of yet, but Istanbul (the upcoming hardfork) includes eip-1344, which includes a CHAINID opcode that pushes the chain id to the stack. I assume Solidity will add block.chainId or something similar, or at least add it to Solidity Assembly so that libraries can access it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.