{"eip":1344,"title":"ChainID opcode","description":"This EIP adds an opcode that returns the current chain's EIP-155 unique identifier.","authors":["Richard Meissner (@rmeissner)","Bryant Eisenbach (@fubuloubu)"],"status":"Final","type":"Standards Track","category":"Core","created":"2018-08-22","requires":[155],"discussionsTo":"https://ethereum-magicians.org/t/add-chain-id-opcode-for-replay-protection-when-handling-signed-messages-in-contracts/1131","repo":"EIPs","label":"EIP-1344","officialUrl":"https://eips.ethereum.org/EIPS/eip-1344","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1344.md","url":"https://eips.huatuo.xyz/eip-1344/","tldr":{"en":"Added the CHAINID opcode (0x46) so contracts can read the current chain ID at runtime and bind signatures to one chain, preventing cross-chain replay.","ja":"CHAINID opcode（0x46）を追加。コントラクトが実行時に現在のチェーン ID を読み取り、署名を 1 つのチェーンに結び付けて、クロスチェーンのリプレイを防げるようにした。","ko":"CHAINID 옵코드(0x46)를 추가해, 컨트랙트가 런타임에 현재 체인 ID를 읽고 서명을 하나의 체인에 묶어 크로스체인 리플레이를 막을 수 있게 했다.","zh":"新增 CHAINID 操作码（0x46），让合约可以在运行时读取当前链 ID，把签名绑定到某一条链，从而防止跨链重放。"},"tags":["opcode","evm","chain-id","signatures","istanbul"],"explainers":{"en":{"lang":"en","tldr":"Added the CHAINID opcode (0x46) so contracts can read the current chain ID at runtime and bind signatures to one chain, preventing cross-chain replay.","tags":["opcode","evm","chain-id","signatures","istanbul"],"related":[155,712,2294,1271],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-1344/","markdown":"## What problem does it solve?\n\n[EIP-155](/eip-155/) put a chain ID into transaction signatures so a transaction signed for one network cannot be replayed on another. Smart contracts that verify their own signatures (meta-transactions, permits, multisigs, L2 schemes using [EIP-712](/eip-712/)) had no such protection: they could only hard-code the chain ID at deploy time.\n\nA hard-coded value breaks if a chain splits and one side changes its ID, and it is an easy place for human error. If the same contract and signer exist on two chains, a signature produced for one could be replayed on the other.\n\nEIP-1344 lets a contract ask the EVM which chain it is running on. It shipped in the Istanbul upgrade.\n\n## How it works\n\n- New opcode `CHAINID` at `0x46`. It takes no stack inputs and pushes the chain ID as a 256-bit value.\n- Cost: `G_base` (2 gas), the same tier as other simple environment opcodes.\n- The value comes from the client's chain configuration, i.e. the EIP-155 chain ID it accepts in transactions. It is returned even if the current transaction was signed without a chain ID.\n\nIn Solidity it is exposed as `block.chainid` (0.8.0 and later) or `chainid()` in inline assembly.\n\n## Sample code\n\nComputing an EIP-712 domain separator at runtime, and recomputing it if the chain ID ever changes (the pattern used by OpenZeppelin's `EIP712`):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Domain {\n    bytes32 private constant TYPE_HASH = keccak256(\n        \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n    );\n    bytes32 private immutable _cachedSeparator;\n    uint256 private immutable _cachedChainId;\n\n    constructor() {\n        _cachedChainId = block.chainid;              // CHAINID opcode\n        _cachedSeparator = _build();\n    }\n\n    function domainSeparator() public view returns (bytes32) {\n        // After a contentious fork the chain ID may differ: rebuild instead of trusting the cache.\n        return block.chainid == _cachedChainId ? _cachedSeparator : _build();\n    }\n\n    function _build() private view returns (bytes32) {\n        return keccak256(abi.encode(\n            TYPE_HASH, keccak256(\"MyApp\"), keccak256(\"1\"), block.chainid, address(this)\n        ));\n    }\n}\n```\n\nReading the same value off-chain (ethers v6):\n\n```ts\nconst { chainId } = await provider.getNetwork(); // bigint, e.g. 1n on mainnet\n```\n\n## Things to know\n\n- The opcode returns whatever chain ID the node is configured with; it is not derived from the transaction.\n- The spec explicitly warns that a chain ID can change after a contentious split. Long-lived signed messages should be designed so that such a change does not silently invalidate or replay them; caching the ID forever is the bug this EIP was meant to avoid.\n- Because the value is 256-bit, tooling and RLP encoding may break on huge IDs. [EIP-2294](/eip-2294/) proposes an explicit upper bound.\n- Contract-based signature checks such as [ERC-1271](/eip-1271/) rely on including the chain ID in the signed data to get replay protection.\n"},"ja":{"lang":"ja","tldr":"CHAINID opcode（0x46）を追加。コントラクトが実行時に現在のチェーン ID を読み取り、署名を 1 つのチェーンに結び付けて、クロスチェーンのリプレイを防げるようにした。","tags":["opcode","evm","chain-id","signatures","istanbul"],"related":[155,712,2294,1271],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-1344/","markdown":"## 何を解決するのか\n\n[EIP-155](/eip-155/) はトランザクション署名にチェーン ID を入れ、あるネットワーク向けに署名されたトランザクションを別のネットワークでリプレイできないようにしました。自分で署名を検証するスマートコントラクト（メタトランザクション、permit、マルチシグ、[EIP-712](/eip-712/) を使う L2 の仕組み）にはそのような保護がなく、デプロイ時にチェーン ID をハードコードするしかありませんでした。\n\nハードコードした値は、チェーンが分岐して片方が ID を変更すると壊れますし、人為的なミスも起こりやすい場所です。同じコントラクトと署名者が 2 つのチェーンに存在する場合、一方で作られた署名が他方でリプレイされる可能性があります。\n\nEIP-1344 は、コントラクトがどのチェーンで動いているかを EVM に問い合わせられるようにします。Istanbul アップグレードで導入されました。\n\n## 仕組み\n\n- 新しい opcode `CHAINID` は `0x46` です。スタックからの入力はなく、チェーン ID を 256 ビットの値として push します。\n- コスト: `G_base`（2 gas）で、他の単純な環境系 opcode と同じ区分です。\n- 値は、クライアントのチェーン設定、つまりトランザクションで受け付ける EIP-155 のチェーン ID から取得されます。現在のトランザクションがチェーン ID なしで署名されていても返されます。\n\nSolidity では `block.chainid`（0.8.0 以降）として、インラインアセンブリでは `chainid()` として公開されています。\n\n## サンプルコード\n\nEIP-712 のドメインセパレーターを実行時に計算し、チェーン ID が変わった場合は再計算する例（OpenZeppelin の `EIP712` が使うパターン）:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Domain {\n    bytes32 private constant TYPE_HASH = keccak256(\n        \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n    );\n    bytes32 private immutable _cachedSeparator;\n    uint256 private immutable _cachedChainId;\n\n    constructor() {\n        _cachedChainId = block.chainid;              // CHAINID opcode\n        _cachedSeparator = _build();\n    }\n\n    function domainSeparator() public view returns (bytes32) {\n        // After a contentious fork the chain ID may differ: rebuild instead of trusting the cache.\n        return block.chainid == _cachedChainId ? _cachedSeparator : _build();\n    }\n\n    function _build() private view returns (bytes32) {\n        return keccak256(abi.encode(\n            TYPE_HASH, keccak256(\"MyApp\"), keccak256(\"1\"), block.chainid, address(this)\n        ));\n    }\n}\n```\n\n同じ値をオフチェーンで読む（ethers v6）:\n\n```ts\nconst { chainId } = await provider.getNetwork(); // bigint, e.g. 1n on mainnet\n```\n\n## 知っておくべきこと\n\n- この opcode は、ノードに設定されたチェーン ID をそのまま返します。トランザクションから導かれるものではありません。\n- 仕様は、対立を伴う分岐の後にチェーン ID が変わり得ると明確に警告しています。長期間有効な署名付きメッセージは、そのような変更によって黙って無効になったりリプレイされたりしないように設計すべきです。ID を永久にキャッシュするのは、この EIP が避けようとしたバグそのものです。\n- 値が 256 ビットであるため、非常に大きな ID ではツールや RLP エンコーディングが壊れる可能性があります。[EIP-2294](/eip-2294/) は明示的な上限を提案しています。\n- [ERC-1271](/eip-1271/) のようなコントラクトベースの署名チェックは、リプレイ保護を得るために、署名対象のデータにチェーン ID を含めることに依存しています。\n"},"ko":{"lang":"ko","tldr":"CHAINID 옵코드(0x46)를 추가해, 컨트랙트가 런타임에 현재 체인 ID를 읽고 서명을 하나의 체인에 묶어 크로스체인 리플레이를 막을 수 있게 했다.","tags":["opcode","evm","chain-id","signatures","istanbul"],"related":[155,712,2294,1271],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-1344/","markdown":"## 어떤 문제를 해결하나요?\n\n[EIP-155](/eip-155/)는 트랜잭션 서명에 체인 ID를 넣어, 한 네트워크용으로 서명된 트랜잭션을 다른 네트워크에서 리플레이할 수 없게 했습니다. 자체적으로 서명을 검증하는 스마트 컨트랙트(메타 트랜잭션, permit, 멀티시그, [EIP-712](/eip-712/)를 쓰는 L2 방식)에는 이런 보호가 없었습니다. 배포 시점에 체인 ID를 하드코딩하는 수밖에 없었습니다.\n\n하드코딩한 값은 체인이 갈라져 한쪽이 ID를 바꾸면 깨지며, 사람의 실수가 생기기 쉬운 지점이기도 합니다. 같은 컨트랙트와 서명자가 두 체인에 존재하면, 한 체인용으로 만든 서명이 다른 체인에서 리플레이될 수 있습니다.\n\nEIP-1344는 컨트랙트가 자신이 어느 체인에서 실행되고 있는지 EVM에 물어볼 수 있게 합니다. Istanbul 업그레이드에서 적용되었습니다.\n\n## 어떻게 동작하나요?\n\n- 새 옵코드 `CHAINID`는 `0x46`입니다. 스택 입력이 없으며 체인 ID를 256비트 값으로 push합니다.\n- 비용: `G_base`(2 gas)로, 다른 단순한 환경 옵코드와 같은 구간입니다.\n- 값은 클라이언트의 체인 설정, 즉 트랜잭션에서 허용하는 EIP-155 체인 ID에서 가져옵니다. 현재 트랜잭션이 체인 ID 없이 서명되었더라도 반환됩니다.\n\nSolidity에서는 `block.chainid`(0.8.0 이상) 또는 인라인 어셈블리의 `chainid()`로 노출됩니다.\n\n## 샘플 코드\n\nEIP-712 도메인 구분자를 런타임에 계산하고, 체인 ID가 바뀌면 다시 계산하는 예(OpenZeppelin의 `EIP712`가 쓰는 패턴):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Domain {\n    bytes32 private constant TYPE_HASH = keccak256(\n        \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n    );\n    bytes32 private immutable _cachedSeparator;\n    uint256 private immutable _cachedChainId;\n\n    constructor() {\n        _cachedChainId = block.chainid;              // CHAINID opcode\n        _cachedSeparator = _build();\n    }\n\n    function domainSeparator() public view returns (bytes32) {\n        // After a contentious fork the chain ID may differ: rebuild instead of trusting the cache.\n        return block.chainid == _cachedChainId ? _cachedSeparator : _build();\n    }\n\n    function _build() private view returns (bytes32) {\n        return keccak256(abi.encode(\n            TYPE_HASH, keccak256(\"MyApp\"), keccak256(\"1\"), block.chainid, address(this)\n        ));\n    }\n}\n```\n\n같은 값을 오프체인에서 읽기(ethers v6):\n\n```ts\nconst { chainId } = await provider.getNetwork(); // bigint, e.g. 1n on mainnet\n```\n\n## 알아둘 점\n\n- 이 옵코드는 노드에 설정된 체인 ID를 그대로 반환합니다. 트랜잭션에서 유도되는 것이 아닙니다.\n- 명세는 논쟁적인 분열 이후 체인 ID가 바뀔 수 있다고 분명히 경고합니다. 오래 유효한 서명 메시지는 그런 변경이 조용히 서명을 무효로 만들거나 리플레이되게 하지 않도록 설계해야 합니다. ID를 영원히 캐시하는 것은 이 EIP가 피하려던 바로 그 버그입니다.\n- 값이 256비트이므로 아주 큰 ID에서는 도구와 RLP 인코딩이 깨질 수 있습니다. [EIP-2294](/eip-2294/)는 명시적인 상한을 제안합니다.\n- [ERC-1271](/eip-1271/) 같은 컨트랙트 기반 서명 검사는 리플레이 방지를 위해 서명 데이터에 체인 ID를 포함하는 것에 의존합니다.\n"},"zh":{"lang":"zh","tldr":"新增 CHAINID 操作码（0x46），让合约可以在运行时读取当前链 ID，把签名绑定到某一条链，从而防止跨链重放。","tags":["opcode","evm","chain-id","signatures","istanbul"],"related":[155,712,2294,1271],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-1344/","markdown":"## 它解决什么问题？\n\n[EIP-155](/eip-155/) 把链 ID 放进交易签名，使为某个网络签署的交易无法在另一个网络上重放。自己验证签名的智能合约（元交易、permit、多签、使用 [EIP-712](/eip-712/) 的 L2 方案）没有这样的保护：它们只能在部署时把链 ID 硬编码进去。\n\n硬编码的值在链分叉、其中一方更改 ID 时就会失效，而且也是容易出现人为错误的地方。如果同一个合约和签名者存在于两条链上，为其中一条链生成的签名就可能在另一条链上被重放。\n\nEIP-1344 让合约可以向 EVM 询问它正在哪条链上运行。它随 Istanbul 升级上线。\n\n## 它如何运作\n\n- 新操作码 `CHAINID`，编码为 `0x46`。它没有栈输入，把链 ID 作为 256 位的值压栈。\n- 成本：`G_base`（2 gas），与其他简单的环境类操作码同档。\n- 该值来自客户端的链配置，即它在交易中接受的 EIP-155 链 ID。即使当前交易是在不带链 ID 的情况下签名的，也会返回该值。\n\n在 Solidity 中，它以 `block.chainid`（0.8.0 及更高版本）暴露，在内联汇编中则是 `chainid()`。\n\n## 示例代码\n\n在运行时计算 EIP-712 域分隔符，并在链 ID 发生变化时重新计算（OpenZeppelin 的 `EIP712` 使用的模式）：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Domain {\n    bytes32 private constant TYPE_HASH = keccak256(\n        \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n    );\n    bytes32 private immutable _cachedSeparator;\n    uint256 private immutable _cachedChainId;\n\n    constructor() {\n        _cachedChainId = block.chainid;              // CHAINID opcode\n        _cachedSeparator = _build();\n    }\n\n    function domainSeparator() public view returns (bytes32) {\n        // After a contentious fork the chain ID may differ: rebuild instead of trusting the cache.\n        return block.chainid == _cachedChainId ? _cachedSeparator : _build();\n    }\n\n    function _build() private view returns (bytes32) {\n        return keccak256(abi.encode(\n            TYPE_HASH, keccak256(\"MyApp\"), keccak256(\"1\"), block.chainid, address(this)\n        ));\n    }\n}\n```\n\n在链下读取同一个值（ethers v6）：\n\n```ts\nconst { chainId } = await provider.getNetwork(); // bigint, e.g. 1n on mainnet\n```\n\n## 需要注意\n\n- 该操作码返回节点所配置的任何链 ID；它不是从交易中推导出来的。\n- 规范明确警告，在有争议的分裂之后，链 ID 可能会改变。长期有效的已签名消息在设计时应确保这种变化不会悄悄使它们失效或被重放；永久缓存 ID 正是这个 EIP 想要避免的 bug。\n- 由于该值是 256 位的，工具和 RLP 编码在遇到极大的 ID 时可能出问题。[EIP-2294](/eip-2294/) 提议了一个明确的上限。\n- 像 [ERC-1271](/eip-1271/) 这样基于合约的签名检查，依赖于把链 ID 包含在被签名的数据中来获得重放保护。\n"}},"requiredBy":[1077,1679]}
