This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.
Overview
Opcode:0x46Introduced: Istanbul (EIP-1344)CHAINID retrieves the unique identifier for the current blockchain network. This enables contracts to implement replay protection and chain-specific behavior, preventing transactions from one chain being replayed on another.
Specification
Stack Input:
(none)
Stack Output:
chain_id (u256)
Gas Cost: 2 (GasQuickStep)Operation:
stack.push(chainId)
Hardfork: Available from Istanbul onwards
Behavior
CHAINID pushes the chain identifier onto the stack as a 256-bit unsigned integer:
contract CrossChainSafe { // VULNERABLE: No chain verification function vulnerableTransfer( address to, uint256 amount, bytes memory signature ) external { bytes32 hash = keccak256(abi.encodePacked(to, amount)); require(verify(hash, signature), "Invalid sig"); // Signature from mainnet could work on testnet! } // SAFE: Include chainid function safeTransfer( address to, uint256 amount, bytes memory signature ) external { bytes32 hash = keccak256(abi.encodePacked( to, amount, block.chainid // Prevents cross-chain replay )); require(verify(hash, signature), "Invalid sig"); // Execute }}
Pre-Istanbul Compatibility
contract BackwardCompatible { // Check if CHAINID is available function getChainId() public view returns (uint256) { uint256 chainId; assembly { // CHAINID opcode (0x46) chainId := chainid() } // If chainId is 0, might be pre-Istanbul // (or actual chainId is 0, which is unlikely) return chainId; } // Fallback for pre-Istanbul function getChainIdLegacy() public pure returns (uint256) { // Must be hardcoded or use assembly checks return 1; // Assume mainnet }}
Implementation
TypeScript
/** * CHAINID opcode (0x46) - Get chain ID * Available: Istanbul+ */export function chainid(frame: FrameType): EvmError | null { // Check hardfork availability if (frame.evm.hardfork.isBefore('ISTANBUL')) { return { type: "InvalidOpcode" }; } // Consume gas (GasQuickStep = 2) frame.gasRemaining -= 2n; if (frame.gasRemaining < 0n) { frame.gasRemaining = 0n; return { type: "OutOfGas" }; } // Push chain ID to stack if (frame.stack.length >= 1024) return { type: "StackOverflow" }; frame.stack.push(frame.evm.blockContext.chain_id); frame.pc += 1; return null;}