Skip to content
Verified contractExactMIT

L1MessageRoot

Address0xf16788bdca4cd89efb5a7d8568d8630dd138a9cc
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

3 more contracts

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 9,999,999 runs
EVM version
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,444,190
Creation transaction
0x890eb18072…85e5680c24

37 files

contracts/core/message-root/L1MessageRoot.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {MessageRootBase} from "./MessageRootBase.sol";
import {IBridgehubBase} from "../bridgehub/IBridgehubBase.sol";
import {V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE} from "./IMessageRoot.sol";
import {IL1MessageRoot} from "./IL1MessageRoot.sol";
import {
    CurrentBatchNumberAlreadySet,
    InvalidSettlementLayerForBatch,
    OnlyOnSettlementLayer,
    TotalBatchesExecutedLessThanV31UpgradeChainBatchNumber,
    TotalBatchesExecutedZero,
    LocallyNoChainsAtGenesis,
    V31UpgradeChainBatchNumberAlreadySet,
    NotAllChainsOnL1
} from "../bridgehub/L1BridgehubErrors.sol";
import {IGetters} from "../../state-transition/chain-interfaces/IGetters.sol";
import {ZeroAddress} from "../../common/L1ContractErrors.sol";
import {MessageHashing, ProofData} from "../../common/libraries/MessageHashing.sol";
import {IL1ChainAssetHandler} from "../chain-asset-handler/IL1ChainAssetHandler.sol";

/// @author Matter Labs
/// @custom:security-contact [email protected]
/// @dev The MessageRoot contract is responsible for storing the cross message roots of the chains and the aggregated root of all chains.
contract L1MessageRoot is MessageRootBase, IL1MessageRoot {
    /// @dev Bridgehub smart contract that is used to operate with L2 via asynchronous L2 <-> L1 communication.
    address public immutable BRIDGE_HUB;

    /// @dev The chain asset handler contract.
    address public immutable CHAIN_ASSET_HANDLER;

    /// @notice The chain id of the Gateway chain.
    uint256 public immutable ERA_GATEWAY_CHAIN_ID;

    /// @notice The mapping storing the batch number at the moment the chain was updated to V31.
    /// Starting from this batch, if a settlement layer has agreed to a proof, it will be held accountable for the content of the message, e.g.
    /// if a withdrawal happens, the balance of the settlement layer will be reduced and not the chain.
    /// @notice This is also the first batch starting from which we store batch roots on L1.
    /// @notice Due to the definition above, this mapping will have the default value (0) for newly added chains, so all their batches are under v31 rules.
    /// For chains that existed at the moment of the upgrade, its value will be populated with V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE until
    /// they call this contract to establish the batch when the upgrade has happened.
    /// @dev The fact that `chainBatchRoots` is populated only after the v31UpgradeChainBatchNumber batch is implicitly enforced:
    /// as during the v31 upgrade all chains settle on L1, so before they start submitting batches on GW to L2MessageRoot implementation,
    /// the `currentChainBatchNumber` will be properly migrated.
    /// @notice Also, as a consequence of the above, the MessageRoot on a settlement layer will require that all messages after this batch go through the asset tracker
    /// to ensure balance consistency.
    /// @dev A completely malicious chain (i.e. with malicious DiamondProxy implementation) could provide a wrongful value for this variable, e.g. it could be too low or too high.
    /// The system should be ready to handle such cases as long as no settlement layer (except for L1) is allowed. Before a settlement layer is added, it is the responsibility of the governance to double check that
    /// no malicious activity has happened before the transition of the ownership of the CTMs within the ecosystem.
    /// @dev Once set on a settlement layer, it will always stay the same. After v31 upgrade is complete, it will be replaced with a library of constant
    /// values for cheaper access.
    mapping(uint256 chainId => uint256 batchNumber) public v31UpgradeChainBatchNumber;

    /// @dev This contract is expected to be used as a proxy implementation on L1.
    /// @param _bridgehub Address of the Bridgehub.
    /// @param _eraGatewayChainId Chain ID of the Era Gateway chain.
    constructor(address _bridgehub, uint256 _eraGatewayChainId, address _chainAssetHandler) {
        require(_bridgehub != address(0), ZeroAddress());
        require(_chainAssetHandler != address(0), ZeroAddress());
        BRIDGE_HUB = _bridgehub;
        ERA_GATEWAY_CHAIN_ID = _eraGatewayChainId;
        CHAIN_ASSET_HANDLER = _chainAssetHandler;
        _disableInitializers();
    }

    /// @dev This initializer is used in local deployments.
    function initialize() external reinitializer(2) {
        _initialize();
        uint256[] memory allZKChains = IBridgehubBase(BRIDGE_HUB).getAllZKChainChainIDs();
        uint256 allZKChainsLength = allZKChains.length;
        /// locally there are no chains deployed before.
        require(allZKChainsLength == 0, LocallyNoChainsAtGenesis());
    }

    /// @notice Returns whether a chain has not finalized its v31 upgrade marker yet.
    /// @param _chainId The chain id to query.
    /// @return True if the chain still stores the pre-v31 placeholder value.
    function isPreV31(uint256 _chainId) external view returns (bool) {
        return v31UpgradeChainBatchNumber[_chainId] == V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE;
    }

    /// @dev This initializer is used in the v31 upgrade. It is expected that it does not call `_initialize`, since
    /// all the actions from there should've been already performed during the previous deployment.
    function initializeL1V31Upgrade() external reinitializer(2) {
        uint256[] memory allZKChains = IBridgehubBase(BRIDGE_HUB).getAllZKChainChainIDs();
        _v31InitializeInner(allZKChains);
    }

    function _v31InitializeInner(uint256[] memory _allZKChains) internal virtual {
        uint256 allZKChainsLength = _allZKChains.length;
        for (uint256 i = 0; i < allZKChainsLength; ++i) {
            require(IBridgehubBase(_bridgehub()).settlementLayer(_allZKChains[i]) == block.chainid, NotAllChainsOnL1());
            v31UpgradeChainBatchNumber[_allZKChains[i]] = V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE;
        }
    }

    function saveV31UpgradeChainBatchNumber(uint256 _chainId) external onlyChain(_chainId) {
        // While it is checked in other places that all chains settle on L1 at the time of the v31 upgrade,
        // we have this double check just in case.
        require(block.chainid == IBridgehubBase(_bridgehub()).settlementLayer(_chainId), OnlyOnSettlementLayer());
        uint256 totalBatchesExecuted = IGetters(msg.sender).getTotalBatchesExecuted();
        require(totalBatchesExecuted > 0, TotalBatchesExecutedZero());
        require(
            totalBatchesExecuted < V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE - 1,
            TotalBatchesExecutedLessThanV31UpgradeChainBatchNumber()
        );
        require(
            v31UpgradeChainBatchNumber[_chainId] == V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE,
            V31UpgradeChainBatchNumberAlreadySet()
        );
        require(currentChainBatchNumber[_chainId] == 0, CurrentBatchNumberAlreadySet());

        currentChainBatchNumber[_chainId] = totalBatchesExecuted;
        v31UpgradeChainBatchNumber[_chainId] = totalBatchesExecuted + 1;
    }

    function _proveL2LeafInclusionOnSettlementLayer(
        uint256 _chainId,
        uint256 _batchNumber,
        ProofData memory _proofData,
        bytes32[] calldata _proof,
        uint256 _depth
    ) internal view virtual override returns (bool) {
        bool isValid = IL1ChainAssetHandler(CHAIN_ASSET_HANDLER).isValidSettlementLayer(
            _chainId,
            _batchNumber,
            _proofData.settlementLayerChainId,
            _proofData.settlementLayerBatchNumber
        );
        require(isValid, InvalidSettlementLayerForBatch(_chainId, _batchNumber, _proofData.settlementLayerChainId));

        return
            this.proveL2LeafInclusionSharedRecursive({
                _chainId: _proofData.settlementLayerChainId,
                _blockOrBatchNumber: _proofData.settlementLayerBatchNumber,
                _leafProofMask: _proofData.settlementLayerBatchRootMask,
                _leaf: _proofData.chainIdLeaf,
                _proof: MessageHashing.extractSliceUntilEnd(_proof, _proofData.ptr),
                _depth: _depth + 1
            });
    }

    /// @inheritdoc MessageRootBase
    function _noBatchFallback(uint256 _chainId, uint256 _batchNumber) internal view virtual override returns (bytes32) {
        uint256 v31UpgradeBatchNumber = v31UpgradeChainBatchNumber[_chainId];
        if (
            v31UpgradeBatchNumber == V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE ||
            _batchNumber < v31UpgradeBatchNumber
        ) {
            return IGetters(IBridgehubBase(_bridgehub()).getZKChain(_chainId)).l2LogsRootHash(_batchNumber);
        }
        return bytes32(0);
    }

    /*//////////////////////////////////////////////////////////////
                        IMMUTABLE GETTERS
    //////////////////////////////////////////////////////////////*/

    function _bridgehub() internal view override returns (address) {
        return BRIDGE_HUB;
    }

    // solhint-disable-next-line func-name-mixedcase
    function L1_CHAIN_ID() public view override returns (uint256) {
        return block.chainid;
    }

    function _chainAssetHandler() internal view override returns (address) {
        return CHAIN_ASSET_HANDLER;
    }
}

../system-contracts/contracts/Constants.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.20;

/// @notice This file contains pure value constants and enums.
/// Interface-typed constants (e.g. IContractDeployer constant DEPLOYER_SYSTEM_CONTRACT) are in Contracts.sol.

/// @dev All the system contracts introduced by ZKsync have their addresses
/// started from 2^15 in order to avoid collision with Ethereum precompiles.
uint160 constant SYSTEM_CONTRACTS_OFFSET = 0x8000; // 2^15

/// @dev Unlike the value above, it is not overridden for the purpose of testing and
/// is identical to the constant value actually used as the system contracts offset on
/// mainnet.
uint160 constant REAL_SYSTEM_CONTRACTS_OFFSET = 0x8000;

/// @dev All the system contracts must be located in the kernel space,
/// i.e. their addresses must be below 2^16.
uint160 constant MAX_SYSTEM_CONTRACT_ADDRESS = 0xffff; // 2^16 - 1

/// @dev The offset from which the built-in, but user space contracts are located.
uint160 constant USER_CONTRACTS_OFFSET = MAX_SYSTEM_CONTRACT_ADDRESS + 1;

address constant ECRECOVER_SYSTEM_CONTRACT = address(0x01);
address constant SHA256_SYSTEM_CONTRACT = address(0x02);
address constant IDENTITY_SYSTEM_CONTRACT = address(0x04);
address constant MODEXP_SYSTEM_CONTRACT = address(0x05);
address constant ECADD_SYSTEM_CONTRACT = address(0x06);
address constant ECMUL_SYSTEM_CONTRACT = address(0x07);
address constant ECPAIRING_SYSTEM_CONTRACT = address(0x08);

/// @dev The number of gas that need to be spent for a single byte of pubdata regardless of the pubdata price.
/// This variable is used to ensure the following:
/// - That the long-term storage of the operator is compensated properly.
/// - That it is not possible that the pubdata counter grows too high without spending proportional amount of computation.
uint256 constant COMPUTATIONAL_PRICE_FOR_PUBDATA = 80;

/// @dev The maximal possible address of an L1-like precompie. These precompiles maintain the following properties:
/// - Their extcodehash is EMPTY_STRING_KECCAK
/// - Their extcodesize is 0 despite having a bytecode formally deployed there.
uint256 constant CURRENT_MAX_PRECOMPILE_ADDRESS = 0xff;

address payable constant BOOTLOADER_FORMAL_ADDRESS = payable(address(SYSTEM_CONTRACTS_OFFSET + 0x01));

// A contract that is allowed to deploy any codehash
// on any address. To be used only during an upgrade.
address constant FORCE_DEPLOYER = address(SYSTEM_CONTRACTS_OFFSET + 0x07);
address constant MSG_VALUE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x09);

// It will be a different value for tests, while shouldn't. But for now, this constant is not used by other contracts, so that's fine.
address constant EVENT_WRITER_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x0d);

// Hardcoded because even for tests we should keep the address. (Instead `SYSTEM_CONTRACTS_OFFSET + 0x10`)
// Precompile call depends on it.
// And we don't want to mock this contract.
address constant KECCAK256_SYSTEM_CONTRACT = address(0x8010);

address constant CODE_ORACLE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x12);

address constant EVM_GAS_MANAGER = address(SYSTEM_CONTRACTS_OFFSET + 0x13);
address constant EVM_PREDEPLOYS_MANAGER = address(SYSTEM_CONTRACTS_OFFSET + 0x14);

address constant L2_DA_VALIDATOR = address(SYSTEM_CONTRACTS_OFFSET + 0x16);

address constant L2_NATIVE_TOKEN_VAULT_ADDR = address(USER_CONTRACTS_OFFSET + 0x04);
// Note, that on its own this contract does not provide much functionality, but having it on a constant address
// serves as a convenient storage for its bytecode to be accessible via `extcodehash`.
address constant SLOAD_CONTRACT_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x06);

address constant WRAPPED_BASE_TOKEN_IMPL_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x07);
address constant L2_CHAIN_ASSET_HANDLER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0a);
address constant L2_UPGRADEABLE_BEACON_DEPLOYER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0b);
address constant L2_SYSTEM_CONTRACT_PROXY_ADMIN_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0c);

address constant L2_INTEROP_CENTER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0d);
address constant L2_INTEROP_HANDLER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0e);
address constant L2_ASSET_TRACKER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0f);
address constant GW_ASSET_TRACKER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x10);

/// @dev If the bitwise AND of the extraAbi[2] param when calling the MSG_VALUE_SIMULATOR
/// is non-zero, the call will be assumed to be a system one.
uint256 constant MSG_VALUE_SIMULATOR_IS_SYSTEM_BIT = 1;

/// @dev The maximal msg.value that context can have
uint256 constant MAX_MSG_VALUE = type(uint128).max;

/// @dev Prefix used during derivation of account addresses using CREATE2
/// @dev keccak256("zksyncCreate2")
bytes32 constant CREATE2_PREFIX = 0x2020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494;
/// @dev Prefix used during derivation of account addresses using CREATE
/// @dev keccak256("zksyncCreate")
bytes32 constant CREATE_PREFIX = 0x63bae3a9951d38e8a3fbb7b70909afc1200610fc5bc55ade242f815974674f23;

/// @dev Prefix used during derivation of account addresses using CREATE2 within the EVM
bytes1 constant CREATE2_EVM_PREFIX = 0xff;

/// @dev Each state diff consists of 156 bytes of actual data and 116 bytes of unused padding, needed for circuit efficiency.
uint256 constant STATE_DIFF_ENTRY_SIZE = 272;

/// @dev Bytes in raw L2 to L1 log
/// @dev Equal to the bytes size of the tuple - (uint8 ShardId, bool isService, uint16 txNumberInBlock, address sender, bytes32 key, bytes32 value)
uint256 constant L2_TO_L1_LOG_SERIALIZE_SIZE = 88;

/// @dev The value of default leaf hash for L2 to L1 logs Merkle tree
/// @dev An incomplete fixed-size tree is filled with this value to be a full binary tree
/// @dev Actually equal to the `keccak256(new bytes(L2_TO_L1_LOG_SERIALIZE_SIZE))`
bytes32 constant L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH = 0x72abee45b59e344af8a6e520241c4744aff26ed411f4c4b00f8af09adada43ba;

/// @dev The current version of state diff compression being used.
uint256 constant STATE_DIFF_COMPRESSION_VERSION_NUMBER = 1;

/// @dev Enum used for system logs emitted by the bootloader.
enum SystemLogKey {
    L2_TO_L1_LOGS_TREE_ROOT_KEY,
    PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY,
    CHAINED_PRIORITY_TXN_HASH_KEY,
    NUMBER_OF_LAYER_1_TXS_KEY,
    // Note, that it is important that `PREV_BATCH_HASH_KEY` has position
    // `4` since it is the same as it was in the previous protocol version and
    // it is the only one that is emitted before the system contracts are upgraded.
    PREV_BATCH_HASH_KEY,
    L2_DA_VALIDATOR_OUTPUT_HASH_KEY,
    USED_L2_DA_VALIDATION_COMMITMENT_SCHEME_KEY,
    MESSAGE_ROOT_ROLLING_HASH_KEY,
    L2_TXS_STATUS_ROLLING_HASH_KEY,
    SETTLEMENT_LAYER_CHAIN_ID_KEY,
    EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY
}

/// @dev The number of leaves in the L2->L1 log Merkle tree.
/// While formally a tree of any length is acceptable, the node supports only a constant length of 16384 leaves.
uint256 constant L2_TO_L1_LOGS_MERKLE_TREE_LEAVES = 16_384;

uint256 constant L2_TO_L1_LOGS_MERKLE_TREE_DEPTH = 14 + 1;

/// @dev The length of the derived key in bytes inside compressed state diffs.
uint256 constant DERIVED_KEY_LENGTH = 32;
/// @dev The length of the enum index in bytes inside compressed state diffs.
uint256 constant ENUM_INDEX_LENGTH = 8;
/// @dev The length of value in bytes inside compressed state diffs.
uint256 constant VALUE_LENGTH = 32;

/// @dev The length of the compressed initial storage write in bytes.
uint256 constant COMPRESSED_INITIAL_WRITE_SIZE = DERIVED_KEY_LENGTH + VALUE_LENGTH;
/// @dev The length of the compressed repeated storage write in bytes.
uint256 constant COMPRESSED_REPEATED_WRITE_SIZE = ENUM_INDEX_LENGTH + VALUE_LENGTH;

/// @dev The position from which the initial writes start in the compressed state diffs.
uint256 constant INITIAL_WRITE_STARTING_POSITION = 4;

/// @dev Each storage diffs consists of the following elements:
/// [20bytes address][32bytes key][32bytes derived key][8bytes enum index][32bytes initial value][32bytes final value]
/// @dev The offset of the derived key in a storage diff.
uint256 constant STATE_DIFF_DERIVED_KEY_OFFSET = 52;
/// @dev The offset of the enum index in a storage diff.
uint256 constant STATE_DIFF_ENUM_INDEX_OFFSET = 84;
/// @dev The offset of the final value in a storage diff.
uint256 constant STATE_DIFF_FINAL_VALUE_OFFSET = 124;

/// @dev Total number of bytes in a blob. Blob = 4096 field elements * 31 bytes per field element
/// @dev EIP-4844 defines it as 131_072 but we use 4096 * 31 within our circuits to always fit within a field element
/// @dev Our circuits will prove that a EIP-4844 blob and our internal blob are the same.
uint256 constant BLOB_SIZE_BYTES = 126_976;

/// @dev Max number of blobs currently supported
uint256 constant MAX_NUMBER_OF_BLOBS = 6;

/// @dev Marker of EraVM bytecode
uint8 constant ERA_VM_BYTECODE_FLAG = 1;
/// @dev Marker of EVM bytecode
uint8 constant EVM_BYTECODE_FLAG = 2;

address constant SERVICE_CALL_PSEUDO_CALLER = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;

/// @dev Pubdata commitment scheme used for DA.
/// @param NONE Invalid option.
/// @param EMPTY_NO_DA No DA commitment, used by Validiums.
/// @param PUBDATA_KECCAK256 Keccak of stateDiffHash and keccak(pubdata). Can be used by custom DA solutions.
/// @param BLOBS_AND_PUBDATA_KECCAK256 This commitment includes EIP-4844 blobs data. Used by default RollupL1DAValidator.
/// @param BLOBS_ZKSYNC_OS Keccak of blob versioned hashes filled with pubdata. This commitment scheme is used only for ZKsyncOS.
enum L2DACommitmentScheme {
    NONE,
    EMPTY_NO_DA,
    PUBDATA_KECCAK256,
    BLOBS_AND_PUBDATA_KECCAK256,
    BLOBS_ZKSYNC_OS
}

/// @dev The metadata version that is supported by the ZK Chains to prove that an L2->L1 log was included in a batch.
uint256 constant SUPPORTED_PROOF_METADATA_VERSION = 1;

/// @dev The server has a hardcoded chainId 270 which is updated to the real value in the L2GenesisUpgradeTxs
/// see link: https://github.com/matter-labs/zksync-era/blob/54dc61c6faff53d314227ffe26961b1abfc999a7/core/node/genesis/src/lib.rs#L182
/// https://github.com/matter-labs/zksync-era/blob/54dc61c6faff53d314227ffe26961b1abfc999a7/core/lib/basic_types/src/lib.rs#L228
uint256 constant HARD_CODED_CHAIN_ID = 270;

contracts/bridge/asset-router/IAssetRouterBase.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

/// @dev The encoding version used for legacy txs.
bytes1 constant LEGACY_ENCODING_VERSION = 0x00;

/// @dev The encoding version used for new txs.
bytes1 constant NEW_ENCODING_VERSION = 0x01;

/// @dev The encoding version used for txs that set the asset handler on the counterpart contract.
bytes1 constant SET_ASSET_HANDLER_COUNTERPART_ENCODING_VERSION = 0x02;

/// @title L1 Bridge contract interface
/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IAssetRouterBase {
    event BridgehubDepositBaseTokenInitiated(
        uint256 indexed chainId,
        address indexed from,
        bytes32 assetId,
        uint256 amount
    );

    event BridgehubDepositInitiated(
        uint256 indexed chainId,
        bytes32 indexed txDataHash,
        address indexed from,
        bytes32 assetId,
        bytes bridgeMintCalldata
    );

    event AssetDeploymentTrackerSet(
        bytes32 indexed assetId,
        address indexed assetDeploymentTracker,
        bytes32 indexed additionalData
    );

    event AssetHandlerRegistered(bytes32 indexed assetId, address indexed _assetHandlerAddress);

    event DepositFinalizedAssetRouter(uint256 indexed chainId, bytes32 indexed assetId, bytes assetData);

    function assetHandlerAddress(bytes32 _assetId) external view returns (address);
}

contracts/bridge/interfaces/IAssetHandler.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

/// @title Asset Handler contract interface
/// @author Matter Labs
/// @custom:security-contact [email protected]
/// @notice Used for any asset handler and called by the AssetRouter
interface IAssetHandler {
    /// @dev Emitted when a token is minted
    event BridgeMint(uint256 indexed chainId, bytes32 indexed assetId, address receiver, uint256 amount);

    /// @dev Emitted when a token is burned
    event BridgeBurn(
        uint256 indexed chainId,
        bytes32 indexed assetId,
        address indexed sender,
        address receiver,
        uint256 amount
    );

    /// @param _chainId the chainId that the message is from
    /// @param _assetId the assetId of the asset being bridged
    /// @param _data the actual data specified for the function
    /// @dev Note, that while payable, this function will only receive base token on L2 chains,
    /// while L1 the provided msg.value is always 0. However, this may change in the future,
    /// so if your AssetHandler implementation relies on it, it is better to explicitly check it.
    /// @dev Note, that it is the responsibility of the asset handler to ensure that the provided data
    /// is correct, since a malicious `_chainId` can provide arbitrary data here.
    function bridgeMint(uint256 _chainId, bytes32 _assetId, bytes calldata _data) external payable;

    /// @notice Burns bridged tokens and returns the calldata for L2 <-> L1 message.
    /// @dev In case of native token vault _data is the tuple of _depositAmount and _l2Receiver.
    /// @param _chainId the chainId that the message will be sent to
    /// @param _msgValue the msg.value of the L2 transaction. For now it is always 0.
    /// @param _assetId the assetId of the asset being bridged
    /// @param _originalCaller the original caller of the
    /// @param _data the actual data specified for the function
    /// @return _bridgeMintData The calldata used by counterpart asset handler to unlock tokens for recipient.
    function bridgeBurn(
        uint256 _chainId,
        uint256 _msgValue,
        bytes32 _assetId,
        address _originalCaller,
        bytes calldata _data
    ) external payable returns (bytes memory _bridgeMintData);
}

contracts/bridge/interfaces/IL1AssetDeploymentTracker.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IL1AssetDeploymentTracker {
    function bridgeCheckCounterpartAddress(
        uint256 _chainId,
        bytes32 _assetId,
        address _originalCaller,
        address _assetHandlerAddressOnCounterpart
    ) external view;
}

contracts/common/Config.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

// solhint-disable no-unused-import
import {
    L2DACommitmentScheme,
    L2_TO_L1_LOG_SERIALIZE_SIZE,
    L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH,
    L2_TO_L1_LOGS_MERKLE_TREE_DEPTH,
    SUPPORTED_PROOF_METADATA_VERSION,
    HARD_CODED_CHAIN_ID
} from "system-contracts/contracts/Constants.sol";
// solhint-enable no-unused-import

/// @dev `keccak256("")`
bytes32 constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;

/// @dev The maximum length of the bytes array with L2 -> L1 logs
uint256 constant MAX_L2_TO_L1_LOGS_COMMITMENT_BYTES = 4 + L2_TO_L1_LOG_SERIALIZE_SIZE * 512;

bytes32 constant DEFAULT_L2_LOGS_TREE_ROOT_HASH = bytes32(0);

/// @dev Denotes the type of the ZKsync Era transaction that came from L1.
uint256 constant PRIORITY_OPERATION_L2_TX_TYPE = 255;

/// @dev Denotes the type of the ZKsync Era transaction that is used for system upgrades.
uint256 constant SYSTEM_UPGRADE_L2_TX_TYPE = 254;

/// @dev Denotes the type of the ZKsync OS transaction that came from L1.
uint256 constant ZKSYNC_OS_PRIORITY_OPERATION_L2_TX_TYPE = 127;

/// @dev Denotes the type of the ZKsync OS transaction that is used for system upgrades.
uint256 constant ZKSYNC_OS_SYSTEM_UPGRADE_L2_TX_TYPE = 126;

/// @dev The maximal allowed difference between protocol minor versions in an upgrade. The 100 gap is needed
/// in case a protocol version has been tested on testnet, but then not launched on mainnet, e.g.
/// due to a bug found.
/// We are allowed to jump at most 100 minor versions at a time. The major version is always expected to be 0.
uint256 constant MAX_ALLOWED_MINOR_VERSION_DELTA = 100;

/// @dev Maximum time a priority transaction may remain unprocessed before Priority Mode (escape hatch) can be activated.
/// Note: This is not the full user exit window. The effective exit window is`UPGRADE_NOTICE_PERIOD` - `PRIORITY_EXPIRATION`.
uint256 constant PRIORITY_EXPIRATION = 4 days;

// @dev The chainId of Ethereum Mainnet
uint256 constant MAINNET_CHAIN_ID = 1;

// @dev The chainId of Ethereum Sepolia testnet
uint256 constant SEPOLIA_CHAIN_ID = 11155111;

/// @dev Timestamp - seconds since unix epoch. This value will be used on the mainnet.
uint256 constant MAINNET_COMMIT_TIMESTAMP_NOT_OLDER = 3 days;

/// @dev Timestamp - seconds since unix epoch. This value will be used on testnets.
uint256 constant TESTNET_COMMIT_TIMESTAMP_NOT_OLDER = 30 days;

/// @dev Maximum available error between real commit batch timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 12 seconds)
uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 1 hours;

/// @dev Shift to apply to verify public input before verifying.
uint256 constant PUBLIC_INPUT_SHIFT = 32;

/// @dev The maximum number of L2 gas that a user can request for an L2 transaction
uint256 constant MAX_GAS_PER_TRANSACTION = 80_000_000;

/// @dev Even though the price for 1 byte of pubdata is 16 L1 gas, we have a slightly increased
/// value.
uint256 constant L1_GAS_PER_PUBDATA_BYTE = 17;

/// @dev The intrinsic cost of the L1->l2 transaction in computational L2 gas
uint256 constant L1_TX_INTRINSIC_L2_GAS = 167_157;

/// @dev The intrinsic cost of the L1->l2 transaction in pubdata
uint256 constant L1_TX_INTRINSIC_PUBDATA = 88;

/// @dev The minimal base price for L1 transaction
uint256 constant L1_TX_MIN_L2_GAS_BASE = 173_484;

/// @dev The number of L2 gas the transaction starts costing more with each 544 bytes of encoding
uint256 constant L1_TX_DELTA_544_ENCODING_BYTES = 1656;

/// @dev The number of L2 gas an L1->L2 transaction gains with each new factory dependency
uint256 constant L1_TX_DELTA_FACTORY_DEPS_L2_GAS = 2473;

/// @dev The number of L2 gas an L1->L2 transaction gains with each new factory dependency
uint256 constant L1_TX_DELTA_FACTORY_DEPS_PUBDATA = 64;

/// @dev The number of pubdata an L1->L2 transaction requires with each new factory dependency
uint256 constant MAX_NEW_FACTORY_DEPS = 64;

/// @dev The L2 gasPricePerPubdata required to be used in bridges.
uint256 constant REQUIRED_L2_GAS_PRICE_PER_PUBDATA = 800;

/// @dev Minimum interval between token multiplier updates.
uint256 constant PRICE_UPDATE_INTERVAL = 1 days;
/// @dev Max allowed price increase per update, as a ratio (e.g. 13/10 = 1.3x).
uint256 constant MAX_PRICE_CHANGE_NUMERATOR = 13;
uint256 constant MAX_PRICE_CHANGE_DENOMINATOR = 10;
/// @dev Reference L1 gas price used for price-change bound calculations.
uint256 constant PRICE_REFERENCE_L1_GAS = 1 gwei;

/// @dev The native price for L1->L2 transactions in ZKsync OS.
uint256 constant ZKSYNC_OS_L1_TX_NATIVE_PRICE = 10;

/// @dev The intrinsic cost of the L1->L2 transaction in computational L2 gas for ZKsync OS.
uint256 constant L1_TX_INTRINSIC_L2_GAS_ZKSYNC_OS = 21000;

/// @dev The cost of calldata byte for the L1->L2 transaction in computational L2 gas for ZKsync OS.
uint256 constant L1_TX_CALLDATA_PRICE_L2_GAS_ZKSYNC_OS = 16;

/// @dev The static part of the L1->l2 transaction native cost for ZKsync OS.
/// It includes hashing (126_000) and coinbase/refund mint_base_token intrinsic native worst case costs.
uint256 constant L1_TX_STATIC_NATIVE_ZKSYNC_OS = 2_875_420;

/// @dev The encoding cost per keccak256 round(136 bytes) of the L1->l2 transaction in native resource for ZKsync OS.
uint256 constant L1_TX_ENCODING_136_BYTES_COST_NATIVE_ZKSYNC_OS = 17500;

/// @dev The cost of calldata byte for the L1->L2 transaction in native resource for ZKsync OS.
uint256 constant L1_TX_CALLDATA_COST_NATIVE_ZKSYNC_OS = 1;

/// @dev The intrinsic cost of the L1->l2 transaction in pubdata for ZKsync OS
/// It includes tx log, coinbase, treasury, refund recipient and asset tracker pubdata.
uint256 constant L1_TX_INTRINSIC_PUBDATA_ZKSYNC_OS = 351;

/// @dev The native per gas ratio for 0 gas price(service/upgrade/gateway) transactions in ZKsync OS.
/// This value is big enough to cover computational native resources usage for any operations.
uint256 constant FREE_TX_NATIVE_PER_GAS = 10_000;

/// @dev The mask which should be applied to the packed batch and L2 block timestamp in order
/// to obtain the L2 block timestamp. Applying this mask is equivalent to calculating modulo 2**128
uint256 constant PACKED_L2_BLOCK_TIMESTAMP_MASK = 0xffffffffffffffffffffffffffffffff;

/// @dev Address of the point evaluation precompile used for EIP-4844 blob verification.
address constant POINT_EVALUATION_PRECOMPILE_ADDR = address(0x0A);

/// @dev The overhead for a transaction slot in L2 gas.
/// It is roughly equal to 80kk/MAX_TRANSACTIONS_IN_BATCH, i.e. how many gas would an L1->L2 transaction
/// need to pay to compensate for the batch being closed.
/// @dev It is expected that the L1 contracts will enforce that the L2 gas price will be high enough to compensate
/// the operator in case the batch is closed because of tx slots filling up.
uint256 constant TX_SLOT_OVERHEAD_L2_GAS = 10000;

/// @dev The overhead for each byte of the bootloader memory that the encoding of the transaction.
/// It is roughly equal to 80kk/BOOTLOADER_MEMORY_FOR_TXS, i.e. how many gas would an L1->L2 transaction
/// need to pay to compensate for the batch being closed.
/// @dev It is expected that the L1 contracts will enforce that the L2 gas price will be high enough to compensate
/// the operator in case the batch is closed because of the memory for transactions being filled up.
uint256 constant MEMORY_OVERHEAD_GAS = 10;

/// @dev The maximum gas limit for a priority transaction in L2.
uint256 constant PRIORITY_TX_MAX_GAS_LIMIT = 72_000_000;

/// @dev the address used to identify eth as the base token for chains.
address constant ETH_TOKEN_ADDRESS = address(1);

/// @dev the value returned in bridgehubDeposit in the TwoBridges function.
bytes32 constant TWO_BRIDGES_MAGIC_VALUE = bytes32(uint256(keccak256("TWO_BRIDGES_MAGIC_VALUE")) - 1);

/// @dev https://eips.ethereum.org/EIPS/eip-1352
address constant BRIDGEHUB_MIN_SECOND_BRIDGE_ADDRESS = address(uint160(type(uint16).max));

/// @dev the maximum number of supported chains, this is an arbitrary limit.
/// @dev Note, that in case of a malicious Bridgehub admin, the total number of chains
/// can be up to 2 times higher. This may be possible, in case the old ChainTypeManager
/// had `100` chains and these were migrated to the Bridgehub only after `MAX_NUMBER_OF_ZK_CHAINS`
/// were added to the bridgehub via creation of new chains.
uint256 constant MAX_NUMBER_OF_ZK_CHAINS = 100;

/// @dev Used as the `msg.sender` for transactions that relayed via a settlement layer.
address constant SETTLEMENT_LAYER_RELAY_SENDER = address(uint160(0x1111111111111111111111111111111111111111));

/// @dev The virtual address of the L1 settlement layer.
address constant L1_SETTLEMENT_LAYER_VIRTUAL_ADDRESS = address(
    uint160(uint256(keccak256("L1_SETTLEMENT_LAYER_VIRTUAL_ADDRESS")) - 1)
);

struct PriorityTreeCommitment {
    uint256 nextLeafIndex;
    uint256 startIndex;
    uint256 unprocessedIndex;
    bytes32[] sides;
}

// Info that allows to restore a chain.
struct ZKChainCommitment {
    /// @notice Total number of executed batches i.e. batches[totalBatchesExecuted] points at the latest executed batch
    /// (batch 0 is genesis)
    uint256 totalBatchesExecuted;
    /// @notice Total number of proved batches i.e. batches[totalBatchesProved] points at the latest proved batch
    uint256 totalBatchesVerified;
    /// @notice Total number of committed batches i.e. batches[totalBatchesCommitted] points at the latest committed
    /// batch
    uint256 totalBatchesCommitted;
    /// @notice The hash of the L2 system contracts ugpgrade transaction.
    /// @dev It is non zero if the migration happens while the upgrade is not yet finalized.
    bytes32 l2SystemContractsUpgradeTxHash;
    /// @notice The batch when the system contracts upgrade transaction was executed.
    /// @dev It is non-zero if the migration happens while the batch where the upgrade tx was present
    /// has not been finalized (executed) yet.
    uint256 l2SystemContractsUpgradeBatchNumber;
    /// @notice The hashes of the batches that are needed to keep the blockchain working.
    /// @dev The length of the array is equal to the `totalBatchesCommitted - totalBatchesExecuted + 1`, i.e. we need
    /// to store all the unexecuted batches' hashes + 1 latest executed one.
    bytes32[] batchHashes;
    /// @notice Commitment to the priority merkle tree.
    PriorityTreeCommitment priorityTree;
    /// @notice Whether a chain is a permanent rollup.
    bool isPermanentRollup;
    /// @notice The precommitment to the transactions of the latest batch.
    bytes32 precommitmentForTheLatestBatch;
}

/// @dev Used as the `msg.sender` for system service transactions.
address constant SERVICE_TRANSACTION_SENDER = address(uint160(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF));

/// @dev To avoid higher costs the writes, we avoid making the slot zero.
/// This ensures that the cost of writes is always 5k and avoids the 20k initial write from the non-zero value.
bytes32 constant DEFAULT_PRECOMMITMENT_FOR_THE_LAST_BATCH = bytes32(uint256(1));

/// @dev The length of a packed transaction precommitment in bytes. It consists of two parts: 32-byte tx hash and 1-byte status (0 or 1).
uint256 constant PACKED_L2_PRECOMMITMENT_LENGTH = 33;

/// @dev The L2 data availability commitment scheme that permanent rollups are expected to use.
L2DACommitmentScheme constant ROLLUP_L2_DA_COMMITMENT_SCHEME = L2DACommitmentScheme.BLOBS_AND_PUBDATA_KECCAK256;

/// @dev The start of the pause deposits time window. We pause when migrating to/from gateway.
/// @dev It is set to 0 in this release, since stage1 is not yet supported for chains that settle on top of ZK Gateway.
uint256 constant PAUSE_DEPOSITS_TIME_WINDOW_START_MAINNET = 0;

/// @dev The delay from `pausedDepositsTimestamp` from which the migration is allowed. It equals the PAUSE_DEPOSITS_TIME_WINDOW_START.
/// @dev It is set to 0 in this release, since stage1 is not yet supported for chains that settle on top of ZK Gateway.
uint256 constant CHAIN_MIGRATION_TIME_WINDOW_START_MAINNET = 0;

uint256 constant PAUSE_DEPOSITS_TIME_WINDOW_START_TESTNET = 0;

uint256 constant CHAIN_MIGRATION_TIME_WINDOW_START_TESTNET = 0;

/// @dev Default overhead value in L1 gas for each batch during chain creation.
uint32 constant DEFAULT_BATCH_OVERHEAD_L1_GAS = 1_000_000;

/// @dev Default maximum amount of pubdata per batch during chain creation.
uint32 constant DEFAULT_MAX_PUBDATA_PER_BATCH = 120_000;

/// @dev Default maximum amount of L2 gas per batch during chain creation.
uint32 constant DEFAULT_MAX_L2_GAS_PER_BATCH = 80_000_000;

/// @dev Default maximum amount of pubdata for priority transactions during chain creation.
uint32 constant DEFAULT_PRIORITY_TX_MAX_PUBDATA = 99_000;

/// @dev Default minimum L2 gas price (in wei) for L1->L2 transactions during chain creation.
uint64 constant DEFAULT_MINIMAL_L2_GAS_PRICE = 250_000_000;

/// @notice The struct that describes whether users will be charged for pubdata for L1->L2 transactions.
/// @param Rollup The users are charged for pubdata & it is priced based on the gas price on Ethereum.
/// @param Validium The pubdata is considered free with regard to the L1 gas price.
enum PubdataPricingMode {
    Rollup,
    Validium
}

/// @dev Default pubdata pricing mode during chain creation.
PubdataPricingMode constant DEFAULT_PUBDATA_PRICING_MODE = PubdataPricingMode.Rollup;

/// @dev Default maximum gas limit for priority transactions during chain creation.
uint64 constant DEFAULT_PRIORITY_TX_MAX_GAS_LIMIT = 72_000_000;

/// @dev The initial balance of the BaseTokenHolder contract (2^127 - 1).
/// @dev Used to derive the real circulating supply: circulatingSupply = INITIAL - TotalSupplyBeforeMigration
uint256 constant INITIAL_BASE_TOKEN_HOLDER_BALANCE = (2 ** 127) - 1;

/// @dev The total number of supported interop attributes.
uint256 constant SUPPORTED_INTEROP_ATTRIBUTES = 5;

/// @dev Migration number used when a chain migrates from L1 to a settlement layer.
uint256 constant MIGRATION_NUMBER_L1_TO_SETTLEMENT_LAYER = 1;

/// @dev Migration number used when a chain returns from a settlement layer back to L1.
uint256 constant MIGRATION_NUMBER_SETTLEMENT_LAYER_TO_L1 = 2;

/// @dev Iterated migrations are not supported; chain can migrate only to settlement layer and back once.
uint256 constant MAX_ALLOWED_NUMBER_OF_MIGRATIONS = 2;

/// @dev The mask that should be applied to the packed log data containing both the number of L2 and L1 transactions
/// processed in the batch. Applying this mask is equivalent to calculating modulo 2**128.
uint256 constant PACKED_NUMBER_OF_L1_TRANSACTIONS_LOG_MASK = 0xffffffffffffffffffffffffffffffff;

/// @dev Bit offset for extracting the upper 128 bits (L2 tx count) from the packed log value.
uint256 constant PACKED_NUMBER_OF_L2_TRANSACTIONS_LOG_SPLIT_BITS = 128;

contracts/common/L1ContractErrors.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

import {L2DACommitmentScheme} from "./Config.sol";

// 0x5ecf2d7a
error AccessToFallbackDenied(address target, address invoker);
// 0x3995f750
error AccessToFunctionDenied(address target, bytes4 selector, address invoker);
// 0x0dfb42bf
error AddressAlreadySet(address addr);
// 0x86bb51b8
error AddressHasNoCode(address);
// 0x1f73225f
error AddressMismatch(address expected, address supplied);
// 0x42573d7a
error AddressNotZero();
// 0xb577eb6c
error AlreadyDangerousContract(address);
// 0x2a5989a0
error AlreadyPermanentRollup();
// 0x0bfcef28
error AlreadyWhitelisted(address);
// 0x5e85ae73
error AmountMustBeGreaterThanZero();
// 0xfde974f4
error AssetHandlerDoesNotExist(bytes32 assetId);
// 0x64107968
error AssetHandlerNotRegistered(bytes32 assetId);
// 0xfe919e28
error AssetIdAlreadyRegistered();
// 0x1294e9e1
error AssetIdMismatch(bytes32 expected, bytes32 supplied);
// 0x04a0b7e9
error AssetIdNotSupported(bytes32 assetId);
// 0x11832de8
error AssetRouterAllowanceNotZero();
// 0x9b821ed7
error BadTransferDataLength();
// 0x6ef9a972
error BaseTokenGasPriceDenominatorNotSet();
// 0x764c57db
error BaseTokenHolderAlreadyInitialized();
// 0xd3cd4bd2
error BaseTokenHolderMintFailed();
// 0x7f9159de
error BaseTokenPreV31TotalSupplyAlreadySet();
// 0x00a6b592
error BaseTokenPreV31TotalSupplyNotSet();
// 0xe3ec2bc9
error BaseTokenTransferFailed();
// 0x55ad3fd3
error BatchHashMismatch(bytes32 expected, bytes32 actual);
// 0xbd4455ff
error BatchNumberMismatch(uint256 expectedBatchNumber, uint256 providedBatchNumber);
// 0x41c329f7
error BatchTimestampGreaterThanLastL2BlockTimestamp();
// 0x6cf12312
error BridgeHubAlreadyRegistered();
// 0xdb538614
error BridgeMintNotImplemented();
// 0xaa5f6180
error BurningNativeWETHNotSupported();
// 0x25d8333c
error CallerNotTimerAdmin();
// 0x3331e9c0
error CallNotAllowed(bytes call);
// 0xe85392f9
error CanOnlyProcessOneBatch();
// 0x00c6ead2
error CantExecuteUnprovenBatches();
// 0xe18cb383
error CantRevertExecutedBatch();
// 0x78d2ed02
error ChainAlreadyLive();
// 0x24591d89
error ChainIdAlreadyExists();
// 0x717a1656
error ChainIdCantBeCurrentChain();
// 0x6b617b38
error ChainIdIsHardcoded();
// 0xa179f8c9
error ChainIdMismatch();
// 0x23f3c357
error ChainIdNotRegistered(uint256 chainId);
// 0x8f620a06
error ChainIdTooBig();
// 0x5e361ef9
error ChainRequiresValidatorsSignaturesForCommit();
// 0x8746f42f
error ConstructorsNotSupported();
// 0xec273439
error CTMAlreadyRegistered();
// 0xc630ef3c
error CTMNotRegistered();
// 0x13df796c
error CutDataForProtocolVersionNotAvailable(uint256 oldProtocolVersion);
// 0x907f8e51
error DeadlineNotYetPassed();
// 0xf2885eb3
error DefaultAdminTransferNotAllowed();
// 0xf7a01e4d
error DelegateCallFailed(bytes returnData);
// 0x0a8ed92c
error DenominatorIsZero();
// 0xb4f54111
error DeployFailed();
// 0x138ee1a3
error DeployingBridgedTokenForNativeToken();
// 0x42bce528
error DepositDoesNotExist(bytes32, bytes32);
// 0xad2fa98e
error DepositExists();
// 0x0e7ee319
error DiamondAlreadyFrozen();
// 0xa7151b9a
error DiamondNotFrozen();
// 0x7138356f
error EmptyAddress();
// 0x2d4d012f
error EmptyAssetId();
// 0x1c25715b
error EmptyBytes32();
// 0x99d8fec9
error EmptyData();
// 0x95b66fe9
error EmptyDeposit();
// 0x84286507
error EmptyPrecommitData(uint256 batchNumber);
// 0x456f8f7a
error EmptyProofLength();
// 0x05410cbc
error EmptyPublicInputsLength();
// 0x876e8b23
error EraBytecodeAlreadyPublished(bytes32 bytecodeHash);
// 0x627e0872
error ETHDepositNotSupported();
// 0x61733a89
error EVMBytecodeAlreadyPublished(bytes32 bytecodeHash);
// 0xf4072616
error ExecuteMessageFailed();
// 0xac4a3f98
error FacetExists(bytes4 selector, address);
// 0x3fce21be
error FeeParamsChangeTooLarge(uint256 oldPrice, uint256 newPrice, uint256 maxAllowedPrice);
// 0xc91cf3b1
error GasPerPubdataMismatch();
// 0x5ca97564
error GenesisBatchCommitmentIncorrect();
// 0x6d4a7df8
error GenesisBatchCommitmentZero();
// 0x7940c83f
error GenesisBatchHashZero();
// 0xb4fc6835
error GenesisIndexStorageZero();
// 0x3a1a8589
error GenesisUpgradeZero();
// 0xd356e6ba
error HashedLogIsDefault();
// 0x0b08d5be
error HashMismatch(bytes32 expected, bytes32 actual);
// 0xd7d93e1f
error IncorrectBatchBounds(
    uint256 processFromExpected,
    uint256 processToExpected,
    uint256 processFromProvided,
    uint256 processToProvided
);
// 0xc1b4bc7b
error IncorrectBatchChainId(uint256, uint256);
// 0xdd381a4c
error IncorrectBridgeHubAddress(address bridgehub);
// 0x1929b7de
error IncorrectTokenAddressFromNTV(bytes32 assetId, address tokenAddress);
// 0x03eb8b54
error InsufficientFunds(uint256 required, uint256 actual);
// 0x9bf8b9aa
error InvalidBatchNumber(uint256 provided, uint256 expected);
// 0xd438e1fa
error InvalidBlockRange(uint64 batchNumber, uint64 from, uint64 to);
// 0xcbd9d2e0
error InvalidCaller(address);
// 0x7a47c9a2
error InvalidChainId();
// 0x92daded2
error InvalidDAForPermanentRollup();
// 0x4fbe5dba
error InvalidDelay();
// 0x075aaa80
error InvalidInteropCalldata(bytes4);
// 0x3f98a77e
error InvalidL2DACommitmentScheme(L2DACommitmentScheme);
// 0xc1780bd6
error InvalidLogSender(address sender, uint256 logKey);
// 0x6eca2e4b
error InvalidMessage();
// 0xa1ec1876
error InvalidMessageRoot(bytes32 expectedMessageRoot, bytes32 providedMessageRoot);
// 0xd08a97e6
error InvalidMockProofLength();
// 0xde4c0b96
error InvalidNTVBurnData();
// 0xd8e9405c
error InvalidNumberOfBlobs(uint256 expected, uint256 numCommitments, uint256 numHashes);
// 0x99f6cc22
error InvalidPackedPrecommitmentLength(uint256 length);
// 0x09bde339
error InvalidProof();
// 0x5a1c353a
error InvalidProofFormat();
// 0x48c5fa28
error InvalidProofLengthForFinalNode();
// 0x5428eae7
error InvalidProtocolVersion();
// 0x6f1cf752
error InvalidPubdataPricingMode();
// 0x12ba286f
error InvalidSelector(bytes4 func);
// 0xbe7193d4
error InvalidSystemLogsLength();
// 0x7b7a98f1
error InvalidThreshold(uint256 max, uint256 got);
// 0xd857fbc0
error InvalidTxCountInPriorityMode(uint256 l2TxCount, uint256 l1TxCount);
// 0x5f1aa154
error InvalidUpgradeTxn(UpgradeTxVerifyParam);
// 0xfb5c22e6
error L2TimestampTooBig();
// 0x97e1359e
error L2WithdrawalMessageWrongLength(uint256 messageLen);
// 0x8efef97a
error LegacyBridgeNotSet();
// 0x29963361
error LegacyBridgeUsesNonNativeToken();
// 0xfade089a
error LegacyEncodingUsedForNonL1Token();
// 0x767eed08
error LegacyMethodForNonL1Token();
// 0xe37d2c02
error LengthIsNotDivisibleBy32(uint256 length);
// 0x1b6825bb
error LogAlreadyProcessed(uint8);
// 0x43e266b0
error MalformedBytecode(BytecodeError);
// 0xafbb7a4e
error MerkleIndexOrHeightMismatch();
// 0x9bb54c35
error MerkleIndexOutOfBounds();
// 0xc33e6128
error MerkleNothingToProve();
// 0x8e23ac1a
error MerklePathEmpty();
// 0x09aa9830
error MerklePathLengthMismatch(uint256 pathLength, uint256 expectedLength);
// 0x1c500385
error MerklePathOutOfBounds();
// 0x1b582fcf
error MerkleWrongIndex(uint256 index, uint256 maxNodeNumber);
// 0x485cfcaa
error MerkleWrongLength(uint256 newLeavesLength, uint256 leafNumber);
// 0x3312a450
error MigrationPaused();
// 0x4e98b356
error MigrationsNotPaused();
// 0xfa44b527
error MissingSystemLogs(uint256 expected, uint256 actual);
// 0x1508fb47
error MockVerifierNotSupported();
// 0x4a094431
error MsgValueMismatch(uint256 expectedMsgValue, uint256 providedMsgValue);
// 0xb385a3da
error MsgValueTooLow(uint256 required, uint256 provided);
// 0xedd74330
error MustBeEraChain();
// 0x8b7e144a
error NewDeadlineExceedsMaxDeadline();
// 0x6eef58d1
error NewDeadlineNotGreaterThanCurrent();
// 0x79cc2d22
error NoCallsProvided();
// 0xce63ce17
error NoCTMForAssetId(bytes32 assetId);
// 0xa6fef710
error NoFunctionsForDiamondCut();
// 0xcab098d8
error NoFundsTransferred();
// 0xb20b58ce
error NoLegacySharedBridge();
// 0xc4dc2673
error NonCanonicalRepresentation();
// 0xc21b1ab7
error NonEmptyCalldata();
// 0x536ec84b
error NonEmptyMsgValue();
// 0xd018e08e
error NonIncreasingTimestamp();
// 0x0105f9c0
error NonSequentialBatch();
// 0x0ac76f01
error NonSequentialVersion();
// 0x0e0ff4d9
error NonZeroBlobToVerifyZKsyncOS(uint256 index, bytes32 blobLinearHash, bytes32 blobOpeningCommitment);
// 0xfa5cd00f
error NotAllowed(address addr);
// 0x64846fe4
error NotARestriction(address addr);
// 0xf306a770
error NotAssetRouter(address sender, address assetRouter);
// 0xb49df1f2
error NotAZKChain(address addr);
// 0x7fdf8632
error NotCompatibleWithPriorityMode();
// 0x5e67e793
error NotCurrentSettlementLayer();
// 0x2b1dc354
error NotDangerousContract(address);
// 0x230f9d11
error NotEnoughSigners(uint256 provided, uint256 expected);
// 0xdd7e3621
error NotInitializedReentrancyGuard();
// 0xecb34449
error NotL1(uint256 l1ChainId, uint256 blockChainId);
// 0xc5441a63
error NotL2ToL2(uint256 sourceChainId, uint256 destinationChainId);
// 0xdf17e316
error NotWhitelisted(address);
// 0xf3ed9dfa
error OnlyEraSupported();
// 0x9d7bb13f
error OnlyNormalMode();
// 0xd702c443
error OnlyPriorityMode();
// 0x6c167909
error OnlySelfAllowed();
// 0x1a21feed
error OperationExists();
// 0xeda2fbb1
error OperationMustBePending();
// 0xe1c1ff37
error OperationMustBeReady();
// 0xb926450e
error OriginChainIdNotFound();
// 0x97da9c1c
error PayloadTooShort();
// 0x688c63e5
error PrecommitmentMismatch(uint256 batchNumber, bytes32 expected, bytes32 found);
// 0x9b48e060
error PreviousOperationNotExecuted();
// 0x67c198fe
error PriorityModeActivationTooEarly(uint256 earliestActivationTimestamp, uint256 currentTimestamp);
// 0xdbfcbbef
error PriorityModeIsNotAllowed();
// 0x2b9d9c4c
error PriorityModeRequiresPermanentRollup();
// 0xd5a99014
error PriorityOperationsRollingHashMismatch();
// 0xbeda0935
error PriorityOpsRequestTimestampMissing(uint256 requestId);
// 0xa840274f
error PriorityQueueNotReady();
// 0x1a4d284a
error PriorityTxPubdataExceedsMaxPubDataPerBatch();
// 0xa461f651
error ProtocolIdMismatch(uint256 expectedProtocolVersion, uint256 providedProtocolId);
// 0x64f94ec2
error ProtocolIdNotGreater();
// 0x959f26fb
error PubdataGreaterThanLimit(uint256 limit, uint256 length);
// 0x63c36549
error QueueIsEmpty();
// 0x0a6c1a5c
error ReconstructionMismatch(bytes32, bytes32);
// 0xab143c06
error Reentrancy();
// 0x667d17de
error RemoveFunctionFacetAddressNotZero(address facet);
// 0xa2d4b16c
error RemoveFunctionFacetAddressZero();
// 0xf6fd7071
error RemovingPermanentRestriction();
// 0x3580370c
error ReplaceFunctionFacetAddressZero();
// 0xf126e113
error RestrictionWasAlreadyPresent(address restriction);
// 0x52e22c98
error RestrictionWasNotPresent(address restriction);
// 0x9a67c1cb
error RevertedBatchNotAfterNewLastBatch();
// 0xfe0aa4f2
error RoleAccessDenied(address chainAddress, bytes32 role, address account);
// 0xd3b6535b
error SelectorsMustAllHaveSameFreezability();
// 0x02181a13
error SettlementLayersMustSettleOnL1();
// 0x856d5b77
error SharedBridgeNotSet();
// 0x7774d2f9
error SharedBridgeValueNotSet(SharedBridgeKey);
// 0xabdc734e
error SignatureNotValid(address signer);
// 0xa665a34d
error SignaturesLengthMismatch(uint256 expected, uint256 actual);
// 0x3b94fe24
error SignerNotAuthorized(address signer);
// 0xa7781cbb
error SignersNotSorted();
// 0xdf3a8fdd
error SlotOccupied();
// 0xcc0f168b
error SystemContractProxyInitialized();
// 0xae43b424
error SystemLogsSizeTooBig();
// 0x08753982
error TimeNotReached(uint256 expectedTimestamp, uint256 actualTimestamp);
// 0x7a4902ad
error TimerAlreadyStarted();
// 0xf511412f
error TimerNotStarted();
// 0x2d50c33b
error TimestampError();
// 0xa51fa558
error TokenIsLegacy();
// 0xb1e96bbd
error TokenMultiplierChangeTooFrequent(uint256 nextAllowedTimestamp);
// 0x1850b46b
error TokenNotLegacy();
// 0x06439c6b
error TokenNotSupported(address token);
// 0x23830e28
error TokensWithFeesNotSupported();
// 0x8e3ce3cb
error TooHighDeploymentNonce();
// 0x76da24b9
error TooManyFactoryDeps();
// 0xf0b4e88f
error TooMuchGas();
// 0x00c5a6a9
error TransactionNotAllowed();
// 0x4c991078
error TxHashMismatch();
// 0x2e311df8
error TxnBodyGasLimitNotEnoughGas();
// 0xfcb9b2e1
error UnallowedImplementation(bytes32 implementationHash);
// 0x8e4a23d6
error Unauthorized(address caller);
// 0xe52478c7
error UndefinedDiamondCutAction();
// 0x6aa39880
error UnexpectedSystemLog(uint256 logKey);
// 0x8124d8ff
error UnexpectedUpgradeSelector();
// 0xc352bb73
error UnknownVerifierType();
// 0xf3dd1b9c
error UnsupportedCommitBatchEncoding(uint8 version);
// 0x084a1449
error UnsupportedEncodingVersion();
// 0x14d2ed8a
error UnsupportedExecuteBatchEncoding(uint8 version);
// 0xf338f830
error UnsupportedProofBatchEncoding(uint8 version);
// 0x1906f346
error UnsupportedUpgradeType();
// 0xf093c2e5
error UpgradeBatchNumberIsNotZero();
// 0x04d91f9d
error UpgradeTimestampNotReached(uint256 upgradeTimestamp, uint256 currentTimestamp);
// 0x47b3b145
error ValidateTxnNotEnoughGas();
// 0x626ade30
error ValueMismatch(uint256 expected, uint256 actual);
// 0xe1022469
error VerifiedBatchesExceedsCommittedBatches();
// 0xae899454
error WithdrawalAlreadyFinalized();
// 0x750b219c
error WithdrawFailed();
// 0xf20c5c2a
error WrappedBaseTokenAlreadyRegistered();
// 0xf1ff6cf6
error WrongCTMDeployerVariant();
// 0x15e8e429
error WrongMagicValue(uint256 expectedMagicValue, uint256 providedMagicValue);
// 0xd92e233d
error ZeroAddress();
// 0xc84885d4
error ZeroChainId();
// 0x16787758
error ZeroUpgradeTimestamp();
// 0x601b6882
error ZKChainLimitReached();
// 0x646ac57e
error ZKsyncOSNotForceDeployForExistingContract(address);
// 0xb24b1ccb
error ZKsyncOSNotForceDeployToPrecompileAddress(address);
// 0x3d9d4821
error ZKsyncOSPrecommitsNotSupported();

enum SharedBridgeKey {
    PostUpgradeFirstBatch,
    LegacyBridgeFirstBatch,
    LegacyBridgeLastDepositBatch,
    LegacyBridgeLastDepositTxn
}

enum BytecodeError {
    Version,
    NumberOfWords,
    Length,
    WordsMustBeOdd
}

enum UpgradeTxVerifyParam {
    From,
    To,
    Paymaster,
    Value,
    MaxFeePerGas,
    MaxPriorityFeePerGas,
    Reserved0,
    Reserved1,
    Reserved2,
    Reserved3,
    Signature,
    PaymasterInput,
    ReservedDynamic
}

contracts/common/MessageVerification.sol

// SPDX-License-Identifier: MIT
// solhint-disable func-named-parameters

pragma solidity ^0.8.24;

import {L2Log, L2Message, TxStatus} from "./Messaging.sol";
import {FinalizeL1DepositParams, IMessageVerification} from "./interfaces/IMessageVerification.sol";
import {MessageHashing} from "./libraries/MessageHashing.sol";

/// @title The interface of the ZKsync MessageVerification contract that can be used to prove L2 message inclusion.
/// @dev This contract is abstract and is inherited by the Mailbox and L2MessageVerification contracts.
/// @dev All calls go through via the _proveL2LeafInclusion function, which is different on L1 and L2.
/// @author Matter Labs
/// @custom:security-contact [email protected]
abstract contract MessageVerification is IMessageVerification {
    /// @inheritdoc IMessageVerification
    function proveL2MessageInclusionShared(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _index,
        L2Message calldata _message,
        bytes32[] calldata _proof
    ) public view virtual returns (bool) {
        return
            _proveL2LogInclusion({
                _chainId: _chainId,
                _blockOrBatchNumber: _blockOrBatchNumber,
                _index: _index,
                _log: MessageHashing._l2MessageToLog(_message),
                _proof: _proof
            });
    }

    /// @inheritdoc IMessageVerification
    function proveL2LeafInclusionShared(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof
    ) public view virtual override returns (bool) {
        return
            _proveL2LeafInclusion({
                _chainId: _chainId,
                _blockOrBatchNumber: _blockOrBatchNumber,
                _leafProofMask: _leafProofMask,
                _leaf: _leaf,
                _proof: _proof
            });
    }

    function proveL2LeafInclusionSharedRecursive(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof,
        uint256 _depth
    ) public view virtual returns (bool) {
        // Positional args to work around slither IR generation bug with named args
        return _proveL2LeafInclusionRecursive(_chainId, _blockOrBatchNumber, _leafProofMask, _leaf, _proof, _depth);
    }

    function _proveL2LeafInclusion(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof
    ) internal view virtual returns (bool) {
        // Positional args to work around slither IR generation bug with named args
        return _proveL2LeafInclusionRecursive(_chainId, _blockOrBatchNumber, _leafProofMask, _leaf, _proof, 0);
    }

    function _proveL2LeafInclusionRecursive(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof,
        uint256 _depth
    ) internal view virtual returns (bool);

    /// @dev Prove that a specific L2 log was sent in a specific L2 batch number
    function _proveL2LogInclusion(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _index,
        L2Log memory _log,
        bytes32[] calldata _proof
    ) internal view returns (bool) {
        bytes32 hashedLog = MessageHashing.getLeafHashFromLog(_log);

        // It is ok to not check length of `_proof` array, as length
        // of leaf preimage (which is `L2_TO_L1_LOG_SERIALIZE_SIZE`) is not
        // equal to the length of other nodes preimages (which are `2 * 32`)

        // We can use `index` as a mask, since the `LocalLogsRoot` is on the left part of the tree.

        return
            _proveL2LeafInclusion({
                _chainId: _chainId,
                _blockOrBatchNumber: _blockOrBatchNumber,
                _leafProofMask: _index,
                _leaf: hashedLog,
                _proof: _proof
            });
    }

    /// @inheritdoc IMessageVerification
    function proveL2LogInclusionShared(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _index,
        L2Log calldata _log,
        bytes32[] calldata _proof
    ) public view virtual returns (bool) {
        return
            _proveL2LogInclusion({
                _chainId: _chainId,
                _blockOrBatchNumber: _blockOrBatchNumber,
                _index: _index,
                _log: _log,
                _proof: _proof
            });
    }

    /// @inheritdoc IMessageVerification
    function proveL1ToL2TransactionStatusShared(
        uint256 _chainId,
        bytes32 _l2TxHash,
        uint256 _l2BatchNumber,
        uint256 _l2MessageIndex,
        uint16 _l2TxNumberInBatch,
        bytes32[] calldata _merkleProof,
        TxStatus _status
    ) public view returns (bool) {
        L2Log memory l2Log = MessageHashing.getL2LogFromL1ToL2Transaction(_l2TxNumberInBatch, _l2TxHash, _status);
        return
            _proveL2LogInclusion({
                _chainId: _chainId,
                _blockOrBatchNumber: _l2BatchNumber,
                _index: _l2MessageIndex,
                _log: l2Log,
                _proof: _merkleProof
            });
    }

    function proveL1DepositParamsInclusion(
        FinalizeL1DepositParams calldata _finalizeWithdrawalParams
    ) public view returns (bool success) {
        L2Message memory l2ToL1Message = L2Message({
            txNumberInBatch: _finalizeWithdrawalParams.l2TxNumberInBatch,
            sender: _finalizeWithdrawalParams.l2Sender,
            data: _finalizeWithdrawalParams.message
        });

        success = this.proveL2MessageInclusionShared({
            _chainId: _finalizeWithdrawalParams.chainId,
            _blockOrBatchNumber: _finalizeWithdrawalParams.l2BatchNumber,
            _index: _finalizeWithdrawalParams.l2MessageIndex,
            _message: l2ToL1Message,
            _proof: _finalizeWithdrawalParams.merkleProof
        });
    }
}

contracts/common/Messaging.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

bytes1 constant BUNDLE_IDENTIFIER = 0x01;
bytes1 constant INTEROP_BUNDLE_VERSION = 0x01;
bytes1 constant INTEROP_CALL_VERSION = 0x01;

/// @dev The enum that represents the transaction execution status
/// @param Failure The transaction execution failed
/// @param Success The transaction execution succeeded
enum TxStatus {
    Failure,
    Success
}

/// @dev The log passed from L2
/// @param l2ShardId The shard identifier, 0 - rollup, 1 - porter
/// All other values are not used but are reserved for the future
/// @param isService A boolean flag that is part of the log along with `key`, `value`, and `sender` address.
/// This field is required formally but does not have any special meaning
/// @param txNumberInBatch The L2 transaction number in a Batch, in which the log was sent
/// @param sender The L2 address which sent the log
/// @param key The 32 bytes of information that was sent in the log
/// @param value The 32 bytes of information that was sent in the log
// Both `key` and `value` are arbitrary 32-bytes selected by the log sender
struct L2Log {
    uint8 l2ShardId;
    bool isService;
    uint16 txNumberInBatch;
    address sender;
    bytes32 key;
    bytes32 value;
}

/// @dev An arbitrary length message passed from L2
/// @notice Under the hood it is `L2Log` sent from the special system L2 contract
/// @param txNumberInBatch The L2 transaction number in a Batch, in which the message was sent
/// @param sender The address of the L2 account from which the message was passed
/// @param data An arbitrary length message
struct L2Message {
    uint16 txNumberInBatch;
    address sender;
    bytes data;
}

/// @dev Internal structure that contains the parameters for the writePriorityOp internal function.
/// @param txId The id of the priority transaction.
/// @param l2GasPrice The gas price for the l2 priority operation.
/// @param request The external calldata request for the priority operation.
struct WritePriorityOpParams {
    uint256 txId;
    uint256 l2GasPrice;
    BridgehubL2TransactionRequest request;
}

/// @dev Structure that includes all fields of the L2 transaction
/// @dev The hash of this structure is the "canonical L2 transaction hash" and can
/// be used as a unique identifier of a tx
/// @param txType The tx type number, depending on which the L2 transaction can be
/// interpreted differently
/// @param from The sender's address. `uint256` type for possible address format changes
/// and maintaining backward compatibility
/// @param to The recipient's address. `uint256` type for possible address format changes
/// and maintaining backward compatibility
/// @param gasLimit The L2 gas limit for L2 transaction. Analog to the `gasLimit` on an
/// L1 transactions
/// @param gasPerPubdataByteLimit Maximum number of L2 gas that will cost one byte of pubdata
/// (every piece of data that will be stored on L1 as calldata)
/// @param maxFeePerGas The absolute maximum sender willing to pay per unit of L2 gas to get
/// the transaction included in a Batch. Analog to the EIP-1559 `maxFeePerGas` on an L1 transactions
/// @param maxPriorityFeePerGas The additional fee that is paid directly to the validator
/// to incentivize them to include the transaction in a Batch. Analog to the EIP-1559
/// `maxPriorityFeePerGas` on an L1 transactions
/// @param paymaster The address of the EIP-4337 paymaster, that will pay fees for the
/// transaction. `uint256` type for possible address format changes and maintaining backward compatibility
/// @param nonce The nonce of the transaction. For L1->L2 transactions it is the priority
/// operation Id
/// @param value The value to pass with the transaction
/// @param reserved The fixed-length fields for usage in a future extension of transaction
/// formats
/// @param data The calldata that is transmitted for the transaction call
/// @param signature An abstract set of bytes that are used for transaction authorization
/// @param factoryDeps The set of L2 bytecode hashes whose preimages were shown on L1
/// @param paymasterInput The arbitrary-length data that is used as a calldata to the paymaster pre-call
/// @param reservedDynamic The arbitrary-length field for usage in a future extension of transaction formats
struct L2CanonicalTransaction {
    uint256 txType;
    uint256 from;
    uint256 to;
    uint256 gasLimit;
    uint256 gasPerPubdataByteLimit;
    uint256 maxFeePerGas;
    uint256 maxPriorityFeePerGas;
    uint256 paymaster;
    uint256 nonce;
    uint256 value;
    // In the future, we might want to add some
    // new fields to the struct. The `txData` struct
    // is to be passed to account and any changes to its structure
    // would mean a breaking change to these accounts. To prevent this,
    // we should keep some fields as "reserved"
    // It is also recommended that their length is fixed, since
    // it would allow easier proof integration (in case we will need
    // some special circuit for preprocessing transactions)
    uint256[4] reserved;
    bytes data;
    bytes signature;
    uint256[] factoryDeps;
    bytes paymasterInput;
    // Reserved dynamic type for the future use-case. Using it should be avoided,
    // But it is still here, just in case we want to enable some additional functionality
    bytes reservedDynamic;
}

/// @param sender The sender's address.
/// @param contractL2 The address of the contract on L2 to call.
/// @param mintValue The amount of base token that should be minted on L2 as the result of this transaction.
/// @param l2Value The msg.value of the L2 transaction.
/// @param l2Calldata The calldata for the L2 transaction.
/// @param l2GasLimit The limit of the L2 gas for the L2 transaction
/// @param l2GasPerPubdataByteLimit The price for a single pubdata byte in L2 gas.
/// @param factoryDeps The array of L2 bytecodes that the tx depends on.
/// @param refundRecipient The recipient of the refund for the transaction on L2. If the transaction fails, then
/// this address will receive the `l2Value`.
// solhint-disable-next-line gas-struct-packing
struct BridgehubL2TransactionRequest {
    address sender;
    address contractL2;
    uint256 mintValue;
    uint256 l2Value;
    bytes l2Calldata;
    uint256 l2GasLimit;
    uint256 l2GasPerPubdataByteLimit;
    bytes[] factoryDeps;
    address refundRecipient;
}

/// @dev The structure that contains the parameters for the message root
/// @param chainId The chain id of the dependency chain
/// @param blockOrBatchNumber The block number or the batch number where the message root was created
/// For proof based interop it is block number. For commit based interop it is batch number.
/// @param sides The sides of the dynamic incremental merkle tree emitted in the L2ToL1Messenger for precommit based interop
/// For proof and commit based interop, the sides contain a single root.
struct InteropRoot {
    uint256 chainId;
    uint256 blockOrBatchNumber;
    // We are double overloading this. The sides of the dynamic incremental merkle tree normally contains the root, as well as the sides of the tree.
    // Second overloading: if the length is 1, we are importing a chainBatchRoot/messageRoot instead of sides.
    bytes32[] sides;
}

/// @param chainId The chain ID of the transaction to check.
/// @param l2BatchNumber The L2 batch number where the withdrawal was processed.
/// @param l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
/// @param l2Sender The address of the message sender on L2 (base token system contract address or asset handler)
/// @param l2TxNumberInBatch The L2 transaction number in the batch, in which the log was sent.
/// @param message The L2 withdraw data, stored in an L2 -> L1 message.
/// @param merkleProof The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization.
struct FinalizeL1DepositParams {
    uint256 chainId;
    uint256 l2BatchNumber;
    uint256 l2MessageIndex;
    address l2Sender;
    uint16 l2TxNumberInBatch;
    bytes message;
    bytes32[] merkleProof;
}

/// @dev Struct used to define parameters for adding a single call in an interop bundle.
/// @param to ERC-7930 address to call on the destination chain. Note, that it will have empty ChainReference.
///           This is due to the fact that chain ID is always provided on a bundle level, as a destination chain ID.
///           And in case of sendMessage the chain ID is also provided via the sendMessage interface, so it's redundant to store it here.
/// @param data Calldata payload to send to `to` address on the destination chain.
/// @param callAttributes EIP-7786 Attributes.
struct InteropCallStarter {
    bytes to;
    bytes data;
    bytes[] callAttributes;
}

/// @dev Internal representation of an InteropCallStarter after parsing its parameters.
/// @param to Address to call on the destination chain.
/// @param data Calldata payload to send.
/// @param callAttributes EIP-7786 Attributes.
struct InteropCallStarterInternal {
    address to;
    bytes data;
    CallAttributes callAttributes;
}

/// @param interopCallValue Base token value on destination chain to send for interop call.
/// @param indirectCall An indirect call first calls a contract as specified by the call starter which returns an actual call starter that will be used to form an interop call. In particular, this is used for interop token transfers. In contrast, a direct call uses the call starter to form an interop call.
/// @param indirectCallMessageValue Base token value on sending chain to send for indirect call.
struct CallAttributes {
    uint256 interopCallValue;
    bool indirectCall;
    uint256 indirectCallMessageValue;
}

/// @param executionAddress ERC-7930 Address allowed to execute the bundle on the destination chain. If the byte array is empty then execution is permissionless.
/// @param unbundlerAddress ERC-7930 Address allowed to unbundle the bundle on the destination chain. Note, that it is required to be nonempty, unlike `executionAddress`.
/// @param useFixedFee If true, user pays fixed ZK fees instead of base token fees controlled by chain operator.
///                    This is a bundle-level attribute - all calls within a bundle share the same fee mode.
///                    Users are free to choose which fee mode to use when creating their bundle.
///                    In more details, any user of interop functionality is able to choose between two fee options:
///                    - Fixed fee in ZK (ZK_INTEROP_FEE constant in InteropCenter). User pays this fee directly in ZK tokens via ERC20 transfer.
///                    - Dynamic fee in base token of source chain where the interop is initiated. This value is fully under control of chain operator via interopProtocolFee in InteropCenter.
///                    In any case, gateway settlement fees (gatewaySettlementFee per call, set by governance in GWAssetTracker) are charged from the settlementFeePayer address
///                    (encoded within the batch data of executeBatchesSharedBridge) when the chain settles on Gateway via processLogsAndMessages(). The settlementFeePayer must have pre-approved
///                    GWAssetTracker to spend wrapped ZK tokens.
///                    Note on ZK-as-base-token chains: On chains where ZK is the base token, useFixedFee=true still requires wrapped ZK tokens
///                    (paid via ERC20 transfer), while useFixedFee=false accepts native ZK via msg.value. This is intentional behavior.
///                    IMPORTANT: useFixedFee=true requires ZK token to be bridged to the source chain. If ZK token is not yet available
///                    in the chain's NativeTokenVault, the transaction will revert with ZKTokenNotAvailable().
struct BundleAttributes {
    bytes executionAddress;
    bytes unbundlerAddress;
    bool useFixedFee;
}

/// @dev A single call.
/// @param version Version of the InteropCall.
/// @param shadowAccount If true, execute via a shadow account, otherwise normal. In current release always false, as it's not yet implemented.
///                      Shadow accounts help with interop when `to` doesn't support 7786. In this case, a "shadow" account could be deployed, allowing
///                      the user to hold funds securely on the destination chain, and interact with anything on destination chain using this shadow account.
/// @param to Destination contract address on the target chain.
/// @param from Original sender address that initiated the call.
/// @param value Amount of base token to send with the call.
/// @param data Calldata payload for the call.
struct InteropCall {
    bytes1 version;
    bool shadowAccount;
    address to;
    address from;
    uint256 value;
    bytes data;
}

/// @dev Execution status of an individual call within a bundle.
/// @param Unprocessed Call not yet processed.
/// @param Executed Call was successfully executed.
/// @param Cancelled Call was cancelled during unbundling.
enum CallStatus {
    Unprocessed,
    Executed,
    Cancelled
}

/// @dev A set of `InteropCall`s to send to another chain.
/// @param version Version of the InteropBundle.
/// @param destinationChainId ChainId of the target chain.
/// @param destinationBaseTokenAssetId Asset ID of the base token of the target chain.
/// @param interopBundleSalt Salt of the interopBundle. It's required to ensure that all bundles have distinct hashes.
///                          It's equal to the keccak256(abi.encodePacked(senderOfTheBundle, NumberOfBundleSentByTheSender))
/// @param calls Array of InteropCall structs to execute.
/// @param bundleAttributes Bundle execution and unbundling attributes.
struct InteropBundle {
    bytes1 version;
    uint256 sourceChainId;
    uint256 destinationChainId;
    bytes32 destinationBaseTokenAssetId;
    bytes32 interopBundleSalt;
    InteropCall[] calls;
    BundleAttributes bundleAttributes;
}

/// @dev Processing status of an `InteropBundle`.
/// @param Unreceived Bundle is not processed in any way yet.
/// @param Verified Bundle inclusion proof accepted, but not processed.
/// @param FullyExecuted All calls in the bundle have been executed atomically via executeBundle.
/// @param Unbundled Bundle was processed via unbundling flow.
enum BundleStatus {
    Unreceived,
    Verified,
    FullyExecuted,
    Unbundled
}

/// @dev Message sent by InteropHandler to GWAssetTracker for each successfully executed interop call.
/// @dev Allows GWAssetTracker to move the corresponding balance from pendingInteropBalance to chainBalance.
/// @param destinationBaseTokenAssetId Asset ID of the base token of the destination chain.
/// @param interopCall The interop call that was executed.
struct InteropCallExecutedMessage {
    bytes32 destinationBaseTokenAssetId;
    InteropCall interopCall;
}

/// @dev Inclusion proof for a cross-chain message payload (bundle) coming from L2→L1.
/// @param chainId Source chain identifier.
/// @param l1BatchNumber Batch number on L1 where the message root was committed.
/// @param l2MessageIndex Position in the L2 logs Merkle tree of this message.
/// @param message The raw L2 message payload (including `BUNDLE_IDENTIFIER` prefix).
/// @param proof Merkle‐proof for verifying the message inclusion.
struct MessageInclusionProof {
    uint256 chainId;
    uint256 l1BatchNumber;
    uint256 l2MessageIndex;
    L2Message message;
    bytes32[] proof;
}

/// @dev Inclusion proof for a single L2 log entry passed to L1.
/// @param chainId Source chain identifier.
/// @param l1BatchNumber Batch number on L1 where the message root was committed.
/// @param l2LogIndex Position in the L2 logs Merkle tree of this log.
/// @param log The decoded `L2Log` entry.
/// @param proof Merkle‐proof for verifying the log inclusion.
struct LogInclusionProof {
    uint256 chainId;
    uint256 l1BatchNumber;
    uint256 l2LogIndex;
    L2Log log;
    bytes32[] proof;
}

/// @dev Generic inclusion proof for an arbitrary 32‐byte leaf in the L2→L1 Merkle tree.
/// @param chainId Source chain identifier.
/// @param l1BatchNumber Batch number on L1 where the message root was committed.
/// @param l2LeafProofMask Bitmask indicating this leaf’s position, given as integer.
/// @param leaf The 32-byte leaf whose inclusion is being proven.
/// @param proof Merkle‐proof for verifying the leaf inclusion.
struct LeafInclusionProof {
    uint256 chainId;
    uint256 l1BatchNumber;
    uint256 l2LeafProofMask;
    bytes32 leaf;
    bytes32[] proof;
}

struct ProofData {
    uint256 settlementLayerChainId;
    uint256 settlementLayerBatchNumber;
    uint256 settlementLayerBatchRootMask;
    uint256 batchLeafProofLen;
    bytes32 batchSettlementRoot;
    bytes32 chainIdLeaf;
    uint256 ptr;
    bool finalProofNode;
}

/// @dev L2 -> L1 message payload used when migrating token balance from L1 tracking to Gateway tracking.
/// @param version Encoding version.
/// @param originToken Token address on origin chain.
/// @param chainId Chain that is migrating.
/// @param assetId Asset id being migrated.
/// @param tokenOriginChainId Origin chain for the token.
/// @param chainMigrationNumber Chain migration number this message is tied to.
/// @param assetMigrationNumber Asset migration number currently known on L2. Not yet used, kept for future use.
/// @param totalWithdrawalsToL1 Total withdrawals initiated from L2 to L1 since v31 tracking started.
/// @param totalSuccessfulDepositsFromL1 Total successful deposits finalized on L2 since v31 tracking started.
/// @param totalPreV31TotalSupply Token total supply snapshot captured on L2 before first post-v31 bridge operation.
struct L1ToGatewayTokenBalanceMigrationData {
    bytes1 version;
    address originToken;
    uint256 chainId;
    bytes32 assetId;
    uint256 tokenOriginChainId;
    uint256 chainMigrationNumber;
    uint256 assetMigrationNumber;
    uint256 totalWithdrawalsToL1;
    uint256 totalSuccessfulDepositsFromL1;
    uint256 totalPreV31TotalSupply;
}

/// @dev L2 -> L1 message payload used when migrating token balance from Gateway tracking back to L1 tracking.
/// @param version Encoding version.
/// @param originToken Token address on origin chain.
/// @param chainId Chain that is migrating.
/// @param assetId Asset id being migrated.
/// @param tokenOriginChainId Origin chain for the token.
/// @param amount Chain balance amount to migrate from Gateway to L1.
/// @param chainMigrationNumber Chain migration number this message is tied to.
/// @param assetMigrationNumber Asset migration number currently known on Gateway.
struct GatewayToL1TokenBalanceMigrationData {
    bytes1 version;
    address originToken;
    uint256 chainId;
    bytes32 assetId;
    uint256 tokenOriginChainId;
    uint256 amount;
    uint256 chainMigrationNumber;
    uint256 assetMigrationNumber;
}

/// @dev L1 -> L2 service transaction payload used to confirm migration processing.
/// @param chainId Chain that was migrated.
/// @param assetId Asset id that was migrated.
/// @param tokenOriginChainId Origin chain for the token.
/// @param originToken Token address on origin chain.
/// @param amount Amount moved during the migration finalization on L1.
/// @param assetMigrationNumber New migration number that should be persisted on L2/Gateway.
/// @param isL1ToGateway Whether this confirmation corresponds to L1 -> Gateway direction.
// solhint-disable-next-line gas-struct-packing
struct MigrationConfirmationData {
    uint256 chainId;
    bytes32 assetId;
    uint256 tokenOriginChainId;
    address originToken;
    uint256 amount;
    uint256 assetMigrationNumber;
    bool isL1ToGateway;
}

struct BalanceChange {
    bytes1 version;
    address originToken;
    bytes32 baseTokenAssetId;
    uint256 baseTokenAmount;
    bytes32 assetId;
    uint256 amount;
    uint256 tokenOriginChainId;
}

struct AssetBalanceChange {
    bytes32 assetId;
    uint256 amount;
}

struct InteropBalanceChange {
    bytes1 version;
    uint256 baseTokenAmount;
    AssetBalanceChange[] assetBalanceChanges;
}

/// @param _chainId The ZK chain id to which deposit was initiated.
/// @param _depositSender The address of the entity that initiated the deposit.
/// @param _assetId The unique identifier of the deposited L1 token.
/// @param _assetData The encoded data, which is used by the asset handler to determine L2 recipient and amount. Might include extra information.
/// @param _l2TxHash The L2 transaction hash.
/// @param _l2BatchNumber The L2 batch number where the deposit finalization was processed.
/// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
/// @param _l2TxNumberInBatch The L2 transaction number in a batch, in which the log was sent.
/// @param _merkleProof The Merkle proof of the processing L1 -> L2 transaction with deposit finalization.
/// @param _txStatus The status of the transaction.
struct ConfirmTransferResultData {
    uint256 _chainId;
    address _depositSender;
    uint16 _l2TxNumberInBatch;
    TxStatus _txStatus;
    bytes32 _assetId;
    bytes _assetData;
    bytes32 _l2TxHash;
    uint256 _l2BatchNumber;
    uint256 _l2MessageIndex;
    bytes32[] _merkleProof;
}

struct TokenMetadata {
    string name;
    string symbol;
    uint256 decimals;
}

struct TokenBridgingData {
    bytes32 assetId;
    uint256 originChainId;
    /// The address of the base token on the origin chain.
    address originToken;
}

contracts/common/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

import {NotInitializedReentrancyGuard, Reentrancy, SlotOccupied} from "./L1ContractErrors.sol";

/**
 * @custom:security-contact [email protected]
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * _Since v2.5.0:_ this module is now much more gas efficient, given net gas
 * metering changes introduced in the Istanbul hardfork.
 */
abstract contract ReentrancyGuard {
    /// @dev Address of lock flag variable.
    /// @dev Flag is placed at random memory location to not interfere with Storage contract.
    // keccak256("ReentrancyGuard") - 1;
    uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4;

    // solhint-disable-next-line max-line-length
    // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    modifier reentrancyGuardInitializer() {
        _initializeReentrancyGuard();
        _;
    }

    function _initializeReentrancyGuard() private {
        uint256 lockSlotOldValue;

        // Storing an initial non-zero value makes deployment a bit more
        // expensive but in exchange every call to nonReentrant
        // will be cheaper.
        assembly {
            lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
            sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
        }

        // Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict
        if (lockSlotOldValue != 0) {
            revert SlotOccupied();
        }
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        uint256 _status;
        assembly {
            _status := sload(LOCK_FLAG_ADDRESS)
        }

        if (_status == 0) {
            revert NotInitializedReentrancyGuard();
        }
        // On the first call to nonReentrant, _NOT_ENTERED will be true
        if (_status != _NOT_ENTERED) {
            revert Reentrancy();
        }

        // Any calls to nonReentrant after this point will fail
        assembly {
            sstore(LOCK_FLAG_ADDRESS, _ENTERED)
        }

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        assembly {
            sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
        }
    }
}

contracts/common/interfaces/IMessageVerification.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

import {FinalizeL1DepositParams, L2Log, L2Message, TxStatus} from "../Messaging.sol";

/// @title The interface of the ZKsync MessageVerification contract that can be used to prove L2 message inclusion.
/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IMessageVerification {
    /// @notice Prove that a specific arbitrary-length message was sent in a specific L2 batch/block number.
    /// @param _chainId The chain id of the L2 where the message comes from.
    /// @param _blockOrBatchNumber The executed L2 batch/block number in which the message appeared.
    /// @param _index The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
    /// @param _message Information about the sent message: sender address, the message itself, tx index in the L2 batch where the message was sent.
    /// @param _proof Merkle proof for inclusion of L2 log that was sent with the message.
    /// @return Boolean specifying whether the proof is valid.
    function proveL2MessageInclusionShared(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _index,
        L2Message calldata _message,
        bytes32[] calldata _proof
    ) external view returns (bool);

    /// @notice Prove that a specific L2 log was sent in a specific L2 batch.
    /// @param _chainId The chain id of the L2 where the log comes from.
    /// @param _blockOrBatchNumber The executed L2 batch/block number in which the log appeared.
    /// @param _index The position of the l2log in the L2 logs Merkle tree.
    /// @param _log Information about the sent log.
    /// @param _proof Merkle proof for inclusion of the L2 log.
    /// @return Whether the proof is correct and L2 log is included in batch.
    function proveL2LogInclusionShared(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _index,
        L2Log calldata _log,
        bytes32[] calldata _proof
    ) external view returns (bool);

    /// @dev Proves that a certain leaf was included as part of the log merkle tree.
    /// @dev Warning: this function does not enforce any additional checks on the structure
    /// of the leaf. This means that it can accept intermediate nodes of the Merkle tree as a `_leaf` as
    /// well as the default "empty" leaves. It is the responsibility of the caller to ensure that the
    /// `_leaf` is a hash of a valid leaf.
    /// @param _chainId The chain id of the L2 where the leaf comes from.
    /// @param _blockOrBatchNumber The batch/block number of the leaf to be proven.
    /// @param _leafProofMask The leaf proof mask.
    /// @param _leaf The leaf to be proven.
    /// @param _proof The proof.
    function proveL2LeafInclusionShared(
        uint256 _chainId,
        uint256 _blockOrBatchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof
    ) external view returns (bool);

    /// @notice Prove that the L1 -> L2 transaction was processed with the specified status.
    /// @param _l2TxHash The L2 canonical transaction hash.
    /// @param _l2BatchNumber The L2 batch number where the transaction was processed.
    /// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
    /// @param _l2TxNumberInBatch The L2 transaction number in the batch, in which the log was sent.
    /// @param _merkleProof The Merkle proof of the processing L1 -> L2 transaction.
    /// @param _status The execution status of the L1 -> L2 transaction (true - success & 0 - fail).
    /// @return Whether the proof is correct and the transaction was actually executed with provided status.
    /// NOTE: It may return `false` for incorrect proof, but it doesn't mean that the L1 -> L2 transaction has an opposite status!
    function proveL1ToL2TransactionStatusShared(
        uint256 _chainId,
        bytes32 _l2TxHash,
        uint256 _l2BatchNumber,
        uint256 _l2MessageIndex,
        uint16 _l2TxNumberInBatch,
        bytes32[] calldata _merkleProof,
        TxStatus _status
    ) external view returns (bool);

    /// @notice Prove that the L2 -> L1 transaction was processed with the specified status.
    function proveL1DepositParamsInclusion(
        FinalizeL1DepositParams calldata _finalizeWithdrawalParams
    ) external view returns (bool success);
}

contracts/common/l2-helpers/L2ContractAddresses.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

// solhint-disable-next-line no-unused-import
import {SYSTEM_CONTRACTS_OFFSET} from "system-contracts/contracts/Constants.sol";

/// @dev the offset for the system hooks for ZKsync OS
uint160 constant SYSTEM_HOOKS_OFFSET = 0x7000;

/// @dev The offset from which the built-in, but user space contracts are located.
uint160 constant BUILT_IN_CONTRACTS_OFFSET = 0x10000; // 2^16

////////////////////////////////////////////////////////////
// zksync os system hooks
////////////////////////////////////////////////////////////

/// @dev The address of the L2ToL1Messenger system hook
address constant L1_MESSENGER_HOOK = address(SYSTEM_HOOKS_OFFSET + 0x01);

/// @dev The address of the system hook responsible for setting bytecode on address. Can only be called from L2_COMPLEX_UPGRADER address
address constant SET_BYTECODE_ON_ADDRESS_HOOK = address(SYSTEM_HOOKS_OFFSET + 0x02);

/// @dev The address of the system hook responsible for minting base tokens on ZK OS chains.
/// This hook can only be called from the L2_BASE_TOKEN_SYSTEM_CONTRACT (address 0x800A).
address constant MINT_BASE_TOKEN_HOOK = address(SYSTEM_HOOKS_OFFSET + 0x100);

////////////////////////////////////////////////////////////
// System contracts
////////////////////////////////////////////////////////////

/// @dev The maximum address of the built-in contracts.
uint160 constant MAX_BUILT_IN_CONTRACT_ADDR = BUILT_IN_CONTRACTS_OFFSET + 0x1ffff;

/// @dev The formal address of the initial program of the system: the bootloader
address constant L2_BOOTLOADER_ADDRESS = address(SYSTEM_CONTRACTS_OFFSET + 0x01);

/// @dev The address of the AccountCodeStorage system contract
address constant L2_ACCOUNT_CODE_STORAGE_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x02);

/// @dev The address of the known code storage system contract
address constant L2_KNOWN_CODE_STORAGE_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x04);

/// @dev The address of the L2 deployer system contract.
address constant L2_DEPLOYER_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x06);

/// @dev The special reserved L2 address. It is located in the system contracts space but doesn't have deployed
/// bytecode.
/// @dev The L2 deployer system contract allows changing bytecodes on any address if the `msg.sender` is this address.
/// @dev So, whenever the governor wants to redeploy system contracts, it just initiates the L1 upgrade call deployer
/// system contract
/// via the L1 -> L2 transaction with `sender == L2_FORCE_DEPLOYER_ADDR`. For more details see the
/// `diamond-initializers` contracts.
address constant L2_FORCE_DEPLOYER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x07);

/// @dev The address of the L2ToL1Messenger system contract
address constant L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x08);

/// @dev the address of the msg value system contract
address constant MSG_VALUE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x09);

/// @dev The address of the eth token system contract
address constant L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0a);

/// @dev The address of the context system contract
address constant L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0b);

/// @dev The address of the pubdata chunk publisher contract
address constant L2_PUBDATA_CHUNK_PUBLISHER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x11);

// @dev The address of the compressor contract.
address constant L2_COMPRESSOR_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0e);

/// @dev The address used to execute complex upgrades, also used for the genesis upgrade
address constant L2_COMPLEX_UPGRADER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0f);

////////////////////////////////////////////////////////////
// Built-in contracts
////////////////////////////////////////////////////////////

/// @dev The address of the create2 factory contract
address constant L2_CREATE2_FACTORY_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x00);

/// @dev The address used to execute the genesis upgrade
address constant L2_GENESIS_UPGRADE_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x01);

/// @dev The genesis upgrade address is reused for all version specific upgrades
address constant L2_VERSION_SPECIFIC_UPGRADER_ADDR = L2_GENESIS_UPGRADE_ADDR;

/// @dev The address of the L2 bridge hub system contract, used to start L1->L2 transactions
address constant L2_BRIDGEHUB_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x02);

/// @dev the address of the l2 asset router.
address constant L2_ASSET_ROUTER_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x03);

/// @dev An l2 system contract address, used in the assetId calculation for native assets.
/// This is needed for automatic bridging, i.e. without deploying the AssetHandler contract,
/// if the assetId can be calculated with this address then it is in fact an NTV asset
address constant L2_NATIVE_TOKEN_VAULT_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x04);

/// @dev the address of the l2 message root.
address constant L2_MESSAGE_ROOT_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x05);

/// @dev The address of the SloadContract system contract, which provides a method to read values from arbitrary storage slots
address constant SLOAD_CONTRACT_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x06);

/// @dev The address of the l2 wrapped base token.
address constant L2_WRAPPED_BASE_TOKEN_IMPL_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x07);

/// @dev The address of the L2 interop root storage system contract
address constant L2_INTEROP_ROOT_STORAGE_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x08);

/// @dev The address of the L2 message verification system contract
address constant L2_MESSAGE_VERIFICATION_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x09);

/// @dev The address of the L2 chain handler system contract
address constant L2_CHAIN_ASSET_HANDLER_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x0a);

/// @dev UpgradeableBeaconDeployer that's responsible for deploying the upgradeable beacons for the bridged standard ERC20 tokens
/// @dev Besides separation of concerns, we need it as a separate contract to ensure that L2NativeTokenVaultZKOS
/// does not have to include BridgedStandardERC20 and UpgradeableBeacon and so can fit into the code size limit.
address constant L2_NTV_BEACON_DEPLOYER_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x0b);

/// @dev the address of the L2 system contract proxy admin
address constant L2_SYSTEM_CONTRACT_PROXY_ADMIN_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x0c);

/// @dev the address of the L2 interop center
address constant L2_INTEROP_CENTER_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x0d);

/// @dev the address of the L2 interop handler
address payable constant L2_INTEROP_HANDLER_ADDR = payable(address(BUILT_IN_CONTRACTS_OFFSET + 0x0e));

/// @dev the address of the L2 asset tracker
address constant L2_ASSET_TRACKER_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x0f);

/// @dev the address of the GW asset tracker
address constant GW_ASSET_TRACKER_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x10);

/// @dev The address of the base token holder contract that holds chain's base token reserves.
address constant L2_BASE_TOKEN_HOLDER_ADDR = address(BUILT_IN_CONTRACTS_OFFSET + 0x11);

////////////////////////////////////////////////////////////
// ZKsync OS genesis contracts
////////////////////////////////////////////////////////////

/// @dev The address of Arachnid's deterministic-deployment-proxy (standard EVM CREATE2 factory),
/// predeployed during ZKsync OS genesis. This contract allows anyone to deploy contracts to
/// deterministic addresses and must be restricted on the Gateway to prevent unauthorized deployments.
/// See: https://github.com/Arachnid/deterministic-deployment-proxy
address constant ZKSYNC_OS_DETERMINISTIC_CREATE2_ADDR = 0x4e59b44847b379578588920cA78FbF26c0B4956C;

contracts/common/libraries/DynamicIncrementalMerkle.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {Merkle} from "./Merkle.sol";
import {Arrays} from "@openzeppelin/contracts-v4/utils/Arrays.sol";

/**
 * @dev Library for managing https://wikipedia.org/wiki/Merkle_Tree[Merkle Tree] data structures.
 *
 * Each tree is a complete binary tree with the ability to sequentially insert leaves, changing them from a zero to a
 * non-zero value and updating its root. This structure allows inserting commitments (or other entries) that are not
 * stored, but can be proven to be part of the tree at a later time if the root is kept. See {MerkleProof}.
 *
 * A tree is defined by the following parameters:
 *
 * * Depth: The number of levels in the tree, it also defines the maximum number of leaves as 2**depth.
 * * Zero value: The value that represents an empty leaf. Used to avoid regular zero values to be part of the tree.
 * * Hashing function: A cryptographic hash function used to produce internal nodes.
 *
 * This is a fork of OpenZeppelin's [`MerkleTree`](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/9af280dc4b45ee5bda96ba47ff829b407eaab67e/contracts/utils/structs/MerkleTree.sol)
 * library, with the changes to support dynamic tree growth (doubling the size when full).
 */
library DynamicIncrementalMerkle {
    /**
     * @dev A complete `bytes32` Merkle tree.
     *
     * The `sides` and `zero` arrays are set to have a length equal to the depth of the tree during setup.
     *
     * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to
     * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and
     * lead to unexpected behavior.
     *
     * NOTE: The `root` and the updates history is not stored within the tree. Consider using a secondary structure to
     * store a list of historical roots from the values returned from {setup} and {push} (e.g. a mapping, {BitMaps} or
     * {Checkpoints}).
     *
     * WARNING: Updating any of the tree's parameters after the first insertion will result in a corrupted tree.
     */
    struct Bytes32PushTree {
        uint256 _nextLeafIndex;
        bytes32[] _sides;
        bytes32[] _zeros;
    }

    /**
     * @dev Initialize a {Bytes32PushTree} using {Hashes-Keccak256} to hash internal nodes.
     * The capacity of the tree (i.e. number of leaves) is set to `2**levels`.
     *
     * IMPORTANT: The zero value should be carefully chosen since it will be stored in the tree representing
     * empty leaves. It should be a value that is not expected to be part of the tree.
     */
    function setup(Bytes32PushTree storage self, bytes32 zero) internal returns (bytes32 initialRoot) {
        self._nextLeafIndex = 0;
        self._zeros.push(zero);
        self._sides.push(bytes32(0));
        return bytes32(0);
    }

    /**
     * @dev Resets the tree to a blank state.
     * Calling this function on MerkleTree that was already setup and used will reset it to a blank state.
     * @param zero The value that represents an empty leaf.
     * @return initialRoot The initial root of the tree.
     */
    function reset(Bytes32PushTree storage self, bytes32 zero) internal returns (bytes32 initialRoot) {
        clear(self);
        setup(self, zero);
    }

    /**
     * @dev Clears the trees internal state.
     */
    function clear(Bytes32PushTree storage self) internal {
        self._nextLeafIndex = 0;
        uint256 length = self._zeros.length;
        for (uint256 i = length; 0 < i; --i) {
            self._zeros.pop();
        }
        length = self._sides.length;
        for (uint256 i = length; 0 < i; --i) {
            self._sides.pop();
        }
    }

    /**
     * @dev Insert a new leaf in the tree, and compute the new root. Returns the position of the inserted leaf in the
     * tree, and the resulting root.
     *
     * Hashing the leaf before calling this function is recommended as a protection against
     * second pre-image attacks.
     */
    function push(Bytes32PushTree storage self, bytes32 leaf) internal returns (uint256 index, bytes32 newRoot) {
        // Cache read
        uint256 levels = self._zeros.length - 1;

        // Get leaf index
        // solhint-disable-next-line gas-increment-by-one
        index = self._nextLeafIndex++;

        // Check if tree is full.
        if (index == 1 << levels) {
            bytes32 zero = self._zeros[levels];
            bytes32 newZero = Merkle.efficientHash(zero, zero);
            self._zeros.push(newZero);
            self._sides.push(bytes32(0));
            ++levels;
        }

        // Rebuild branch from leaf to root
        uint256 currentIndex = index;
        bytes32 currentLevelHash = leaf;
        bool updatedSides = false;
        for (uint32 i = 0; i < levels; ++i) {
            // Reaching the parent node, is currentLevelHash the left child?
            bool isLeft = currentIndex % 2 == 0;

            // If so, next time we will come from the right, so we need to save it
            if (isLeft && !updatedSides) {
                Arrays.unsafeAccess(self._sides, i).value = currentLevelHash;
                updatedSides = true;
            }

            // Compute the current node hash by using the hash function
            // with either its sibling (side) or the zero value for that level.
            currentLevelHash = Merkle.efficientHash(
                isLeft ? currentLevelHash : Arrays.unsafeAccess(self._sides, i).value,
                isLeft ? Arrays.unsafeAccess(self._zeros, i).value : currentLevelHash
            );

            // Update node index
            currentIndex >>= 1;
        }

        Arrays.unsafeAccess(self._sides, levels).value = currentLevelHash;
        return (index, currentLevelHash);
    }

    /**
     * @dev Extend until end.
     * @dev here we can extend the array, so the depth is not predetermined.
     */
    function extendUntilEnd(Bytes32PushTree storage self, uint256 finalDepth) internal {
        bytes32 currentZero = self._zeros[self._zeros.length - 1];
        if (self._nextLeafIndex == 0) {
            self._sides[0] = currentZero;
        }
        bytes32 currentSide = self._sides[self._sides.length - 1];
        for (uint256 i = self._sides.length; i < finalDepth; ++i) {
            currentSide = Merkle.efficientHash(currentSide, currentZero);
            currentZero = Merkle.efficientHash(currentZero, currentZero);
            // at i
            self._zeros.push(currentZero);
            self._sides.push(currentSide);
        }
    }

    /**
     * @dev Tree's root.
     */
    function root(Bytes32PushTree storage self) internal view returns (bytes32) {
        return Arrays.unsafeAccess(self._sides, self._sides.length - 1).value;
    }

    /**
     * @dev Tree's height (does not include the root node).
     */
    function height(Bytes32PushTree storage self) internal view returns (uint256) {
        return self._sides.length - 1;
    }
}

contracts/common/libraries/FullMerkle.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {UncheckedMath} from "../../common/libraries/UncheckedMath.sol";
import {Merkle} from "./Merkle.sol";
import {MerkleNothingToProve, MerkleWrongIndex} from "../L1ContractErrors.sol";

/// @author Matter Labs
/// @custom:security-contact [email protected]
library FullMerkle {
    using UncheckedMath for uint256;

    struct FullTree {
        uint256 _height;
        uint256 _leafNumber;
        bytes32[][] _nodes;
        bytes32[] _zeros;
    }

    /**
     * @dev Initialize a {FullTree} using {Merkle.efficientHash} to hash internal nodes.
     * The capacity of the tree (i.e. number of leaves) is set to `2**levels`.
     *
     * IMPORTANT: The zero value should be carefully chosen since it will be stored in the tree representing
     * empty leaves. It should be a value that is not expected to be part of the tree.
     * @param zero The zero value to be used in the tree.
     */
    function setup(FullTree storage self, bytes32 zero) internal returns (bytes32 initialRoot) {
        // Store depth in the dynamic array
        self._zeros.push(zero);
        self._nodes.push([zero]);

        return zero;
    }

    /**
     * @dev Push a new leaf to the tree.
     * @param _leaf The leaf to be added to the tree.
     */
    function pushNewLeaf(FullTree storage self, bytes32 _leaf) internal returns (bytes32 newRoot) {
        // solhint-disable-next-line gas-increment-by-one
        uint256 index = self._leafNumber++;

        if (index == 1 << self._height) {
            uint256 newHeight = self._height.uncheckedInc();
            self._height = newHeight;
            bytes32 topZero = self._zeros[newHeight - 1];
            bytes32 newZero = Merkle.efficientHash(topZero, topZero);
            self._zeros.push(newZero);
            self._nodes.push([newZero]);
        }
        if (index != 0) {
            uint256 oldMaxNodeNumber = index - 1;
            uint256 maxNodeNumber = index;
            for (uint256 i; i < self._height; ++i) {
                if (oldMaxNodeNumber == maxNodeNumber) {
                    break;
                }
                self._nodes[i].push(self._zeros[i]);
                maxNodeNumber /= 2;
                oldMaxNodeNumber /= 2;
            }
        }
        return updateLeaf(self, index, _leaf);
    }

    /**
     * @dev Update a leaf at index in the tree.
     * @param _index The index of the leaf to be updated.
     * @param _itemHash The new hash of the leaf.
     */
    function updateLeaf(FullTree storage self, uint256 _index, bytes32 _itemHash) internal returns (bytes32) {
        uint256 maxNodeNumber = self._leafNumber - 1;
        if (_index > maxNodeNumber) {
            revert MerkleWrongIndex(_index, maxNodeNumber);
        }
        self._nodes[0][_index] = _itemHash;
        bytes32 currentHash = _itemHash;
        for (uint256 i; i < self._height; ++i) {
            if (_index % 2 == 0) {
                currentHash = Merkle.efficientHash(
                    currentHash,
                    maxNodeNumber == _index ? self._zeros[i] : self._nodes[i][_index + 1]
                );
            } else {
                currentHash = Merkle.efficientHash(self._nodes[i][_index - 1], currentHash);
            }
            _index /= 2;
            maxNodeNumber /= 2;
            self._nodes[i + 1][_index] = currentHash;
        }
        return currentHash;
    }

    /**
     * @dev Returns the root of the tree.
     */
    function root(FullTree storage self) internal view returns (bytes32) {
        return self._nodes[self._height][0];
    }

    /**
     * @dev Returns merkle path for a certain leaf index.
     * @param _index The index of the leaf to calculate proof for.
     */
    function merklePath(FullTree storage self, uint256 _index) internal view returns (bytes32[] memory) {
        if (self._leafNumber == 0) {
            revert MerkleNothingToProve();
        }
        uint256 maxNodeNumber = self._leafNumber - 1;
        if (_index > maxNodeNumber) {
            revert MerkleWrongIndex(_index, maxNodeNumber);
        }
        bytes32[] memory proof = new bytes32[](self._height);
        for (uint256 i = 0; i < self._height; i = i.uncheckedInc()) {
            if (_index % 2 == 0) {
                proof[i] = maxNodeNumber == _index ? self._zeros[i] : self._nodes[i][_index + 1];
            } else {
                proof[i] = self._nodes[i][_index - 1];
            }
            _index /= 2;
            maxNodeNumber /= 2;
        }
        return proof;
    }
}

contracts/common/libraries/Merkle.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

import {UncheckedMath} from "../../common/libraries/UncheckedMath.sol";
import {
    MerkleIndexOrHeightMismatch,
    MerkleIndexOutOfBounds,
    MerkleNothingToProve,
    MerklePathEmpty,
    MerklePathLengthMismatch,
    MerklePathOutOfBounds
} from "../../common/L1ContractErrors.sol";

/// @author Matter Labs
/// @custom:security-contact [email protected]
library Merkle {
    using UncheckedMath for uint256;

    /// @dev Calculate Merkle root by the provided Merkle proof.
    /// NOTE: When using this function, check that the _path length is equal to the tree height to prevent shorter/longer paths attack
    /// however, for chains settling on GW the proof includes the GW proof, so the path increases. See Mailbox for more details.
    /// @param _path Merkle path from the leaf to the root
    /// @param _index Leaf index in the tree
    /// @param _itemHash Hash of leaf content
    /// @return The Merkle root
    function calculateRoot(
        bytes32[] calldata _path,
        uint256 _index,
        bytes32 _itemHash
    ) internal pure returns (bytes32) {
        uint256 pathLength = _path.length;
        _validatePathLengthForSingleProof(_index, pathLength);

        bytes32 currentHash = _itemHash;
        for (uint256 i; i < pathLength; ++i) {
            currentHash = (_index % 2 == 0)
                ? efficientHash(currentHash, _path[i])
                : efficientHash(_path[i], currentHash);
            _index /= 2;
        }

        return currentHash;
    }

    /// @dev Calculate Merkle root by the provided Merkle proof.
    /// @dev NOTE: When using this function, check that the _path length is appropriate to prevent shorter/longer paths attack
    /// @param _path Merkle path from the leaf to the root
    /// @param _index Leaf index in the tree.
    /// @dev NOTE the tree can be joined. In this case the second tree's leaves indexes increase by the number of leaves in the first tree.
    /// @param _itemHash Hash of leaf content
    /// @return The Merkle root
    function calculateRootMemory(
        bytes32[] memory _path,
        uint256 _index,
        bytes32 _itemHash
    ) internal pure returns (bytes32) {
        uint256 pathLength = _path.length;
        _validatePathLengthForSingleProof(_index, pathLength);

        bytes32 currentHash = _itemHash;
        for (uint256 i; i < pathLength; ++i) {
            currentHash = (_index % 2 == 0)
                ? efficientHash(currentHash, _path[i])
                : efficientHash(_path[i], currentHash);
            _index /= 2;
        }

        return currentHash;
    }

    /// @dev Calculate Merkle root by the provided Merkle proof for a range of elements
    /// NOTE: When using this function, check that the _startPath and _endPath lengths are equal to the tree height to prevent shorter/longer paths attack
    /// @param _startPath Merkle path from the first element of the range to the root
    /// @param _endPath Merkle path from the last element of the range to the root
    /// @param _startIndex Index of the first element of the range in the tree
    /// @param _itemHashes Hashes of the elements in the range
    /// @return The Merkle root
    function calculateRootPaths(
        bytes32[] memory _startPath,
        bytes32[] memory _endPath,
        uint256 _startIndex,
        bytes32[] memory _itemHashes
    ) internal pure returns (bytes32) {
        uint256 pathLength = _startPath.length;
        if (pathLength != _endPath.length) {
            revert MerklePathLengthMismatch(pathLength, _endPath.length);
        }
        if (pathLength >= 256) {
            revert MerklePathOutOfBounds();
        }
        uint256 levelLen = _itemHashes.length;
        // Edge case: we want to be able to prove an element in a single-node tree.
        if (pathLength == 0 && (_startIndex != 0 || levelLen != 1)) {
            revert MerklePathEmpty();
        }
        if (levelLen == 0) {
            revert MerkleNothingToProve();
        }
        if (_startIndex + levelLen > (1 << pathLength)) {
            revert MerkleIndexOrHeightMismatch();
        }
        bytes32[] memory itemHashes = _itemHashes;

        for (uint256 level; level < pathLength; ++level) {
            uint256 parity = _startIndex % 2;
            // We get an extra element on the next level if on the current level elements either
            // start on an odd index (`parity == 1`) or end on an even index (`levelLen % 2 == 1`)
            uint256 nextLevelLen = levelLen / 2 + (parity | (levelLen % 2));
            for (uint256 i; i < nextLevelLen; ++i) {
                bytes32 lhs = (i == 0 && parity == 1) ? _startPath[level] : itemHashes[2 * i - parity];
                bytes32 rhs = (i == nextLevelLen - 1 && (levelLen - parity) % 2 == 1)
                    ? _endPath[level]
                    : itemHashes[2 * i + 1 - parity];
                itemHashes[i] = efficientHash(lhs, rhs);
            }
            levelLen = nextLevelLen;
            _startIndex /= 2;
        }

        return itemHashes[0];
    }

    /// @dev Keccak hash of the concatenation of two 32-byte words
    function efficientHash(bytes32 _lhs, bytes32 _rhs) internal pure returns (bytes32 result) {
        assembly {
            mstore(0x00, _lhs)
            mstore(0x20, _rhs)
            result := keccak256(0x00, 0x40)
        }
    }

    function _validatePathLengthForSingleProof(uint256 _index, uint256 _pathLength) private pure {
        if (_pathLength >= 256) {
            revert MerklePathOutOfBounds();
        }
        if (_index >= (1 << _pathLength)) {
            revert MerkleIndexOutOfBounds();
        }
    }
}

contracts/common/libraries/MessageHashing.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {Merkle} from "./Merkle.sol";
import {L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH, SUPPORTED_PROOF_METADATA_VERSION} from "../Config.sol";
import {MerklePathEmpty} from "../L1ContractErrors.sol";
import {UncheckedMath} from "./UncheckedMath.sol";
import {L2Log, L2Message, ProofData, TxStatus} from "../Messaging.sol";
import {L2_BOOTLOADER_ADDRESS, L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR} from "../l2-helpers/L2ContractAddresses.sol";

import {UnsupportedProofMetadataVersion} from "../../state-transition/L1StateTransitionErrors.sol";
import {HashedLogIsDefault, InvalidProofLengthForFinalNode} from "../../common/L1ContractErrors.sol";

bytes32 constant BATCH_LEAF_PADDING = keccak256("zkSync:BatchLeaf");
bytes32 constant CHAIN_ID_LEAF_PADDING = keccak256("zkSync:ChainIdLeaf");

library MessageHashing {
    using UncheckedMath for uint256;

    function getLeafHashFromMessage(L2Message memory _message) internal pure returns (bytes32 hashedLog) {
        L2Log memory l2Log = _l2MessageToLog(_message);
        hashedLog = getLeafHashFromLog(l2Log);
    }

    /// @dev Convert arbitrary-length message to the raw L2 log
    function _l2MessageToLog(L2Message memory _message) internal pure returns (L2Log memory) {
        return
            L2Log({
                l2ShardId: 0,
                isService: true,
                txNumberInBatch: _message.txNumberInBatch,
                sender: L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR,
                key: bytes32(uint256(uint160(_message.sender))),
                value: keccak256(_message.data)
            });
    }

    function getL2LogFromL1ToL2Transaction(
        uint16 _l2TxNumberInBatch,
        bytes32 _l2TxHash,
        TxStatus _status
    ) internal pure returns (L2Log memory l2Log) {
        // Bootloader sends an L2 -> L1 log only after processing the L1 -> L2 transaction.
        // Thus, we can verify that the L1 -> L2 transaction was included in the L2 batch with specified status.
        //
        // The semantics of such L2 -> L1 log is always:
        // - sender = L2_BOOTLOADER_ADDRESS
        // - key = hash(L1ToL2Transaction)
        // - value = status of the processing transaction (1 - success & 0 - fail)
        // - isService = true (just a conventional value)
        // - l2ShardId = 0 (means that L1 -> L2 transaction was processed in a rollup shard, other shards are not available yet anyway)
        // - txNumberInBatch = number of transaction in the batch
        l2Log = L2Log({
            l2ShardId: 0,
            isService: true,
            txNumberInBatch: _l2TxNumberInBatch,
            sender: L2_BOOTLOADER_ADDRESS,
            key: _l2TxHash,
            value: bytes32(uint256(_status))
        });
    }

    function getLeafHashFromLog(L2Log memory _log) internal pure returns (bytes32 hashedLog) {
        hashedLog = keccak256(
            // solhint-disable-next-line func-named-parameters
            abi.encodePacked(_log.l2ShardId, _log.isService, _log.txNumberInBatch, _log.sender, _log.key, _log.value)
        );
    }

    /// @dev Returns the leaf hash for a chain with batch number and batch root.
    /// @param batchRoot The root hash of the batch.
    /// @param batchNumber The number of the batch.
    function batchLeafHash(bytes32 batchRoot, uint256 batchNumber) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(BATCH_LEAF_PADDING, batchRoot, batchNumber));
    }

    /// @dev Returns the leaf hash for a chain with chain root and chain id.
    /// @param chainIdRoot The root hash of the chain.
    /// @param chainId The id of the chain.
    function chainIdLeafHash(bytes32 chainIdRoot, uint256 chainId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(CHAIN_ID_LEAF_PADDING, chainIdRoot, chainId));
    }

    struct ProofMetadata {
        uint256 proofStartIndex;
        uint256 logLeafProofLen;
        uint256 batchLeafProofLen;
        bool finalProofNode;
    }

    /// @notice Parses the proof metadata.
    /// @param _proof The proof.
    /// @return result The proof metadata.
    function parseProofMetadata(bytes32[] calldata _proof) internal pure returns (ProofMetadata memory result) {
        bytes32 proofMetadata = _proof[0];

        // We support two formats of the proofs:
        // 1. The old format, where `_proof` is just a plain Merkle proof.
        // 2. The new format, where the first element of the `_proof` is encoded metadata, which consists of the following:
        // - first byte: metadata version (0x01).
        // - second byte: length of the log leaf proof (the proof that the log belongs to a batch).
        // - third byte: length of the batch leaf proof (the proof that the batch belongs to another settlement layer, if any).
        // - fourth byte: whether the current proof is the last in the links of recursive proofs for settlement layers.
        // - the rest of the bytes are zeroes.
        //
        // In the future the old version will be disabled, and only the new version will be supported.
        // For now, we need to support both for backwards compatibility. We distinguish between those based on whether the last 28 bytes are zeroes.
        // It is safe, since the elements of the proof are hashes and are unlikely to have 28 zero bytes in them.

        // We shift left by 4 bytes = 32 bits to remove the top 32 bits of the metadata.
        uint256 metadataAsUint256 = (uint256(proofMetadata) << 32);

        if (metadataAsUint256 == 0) {
            // It is the new version
            bytes1 metadataVersion = bytes1(proofMetadata);
            if (uint256(uint8(metadataVersion)) != SUPPORTED_PROOF_METADATA_VERSION) {
                revert UnsupportedProofMetadataVersion(uint256(uint8(metadataVersion)));
            }

            result.proofStartIndex = 1;
            result.logLeafProofLen = uint256(uint8(proofMetadata[1]));
            result.batchLeafProofLen = uint256(uint8(proofMetadata[2]));
            result.finalProofNode = uint256(uint8(proofMetadata[3])) != 0;
        } else {
            // It is the old version

            // The entire proof is a merkle path
            result.proofStartIndex = 0;
            result.logLeafProofLen = _proof.length;
            result.batchLeafProofLen = 0;
            result.finalProofNode = true;
        }
        if (result.finalProofNode && result.batchLeafProofLen != 0) {
            revert InvalidProofLengthForFinalNode();
        }
    }

    /// @notice Parses and processes the proof and returns the resulting data.
    /// @param _chainId The chain id of the L2 where the leaf comes from.
    /// @param _batchNumber The batch number.
    /// @param _leafProofMask The leaf proof mask.
    /// @param _leaf The leaf to be proven.
    /// @param _proof The proof.
    /// @return result The proof verification result.
    function _getProofData(
        uint256 _chainId,
        uint256 _batchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof
    ) internal pure returns (ProofData memory result) {
        if (_proof.length == 0) {
            revert MerklePathEmpty();
        }

        // Check that hashed log is not the default one,
        // otherwise it means that the value is out of range of sent L2 -> L1 logs
        if (_leaf == L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH) {
            revert HashedLogIsDefault();
        }

        ProofMetadata memory proofMetadata = MessageHashing.parseProofMetadata(_proof);
        result.ptr = proofMetadata.proofStartIndex;

        {
            bytes32 batchSettlementRoot = Merkle.calculateRootMemory(
                extractSlice(_proof, result.ptr, result.ptr + proofMetadata.logLeafProofLen),
                _leafProofMask,
                _leaf
            );
            result.ptr += proofMetadata.logLeafProofLen;
            result.batchSettlementRoot = batchSettlementRoot;
            result.finalProofNode = proofMetadata.finalProofNode;

            if (proofMetadata.finalProofNode) {
                return result;
            }
            // Now, we'll have to check that the Gateway included the message.
            bytes32 localBatchLeafHash = MessageHashing.batchLeafHash(batchSettlementRoot, _batchNumber);

            uint256 batchLeafProofMask = uint256(bytes32(_proof[result.ptr]));
            ++result.ptr;

            bytes32 chainIdRoot = Merkle.calculateRootMemory(
                extractSlice(_proof, result.ptr, result.ptr + proofMetadata.batchLeafProofLen),
                batchLeafProofMask,
                localBatchLeafHash
            );
            result.ptr += proofMetadata.batchLeafProofLen;

            result.chainIdLeaf = MessageHashing.chainIdLeafHash(chainIdRoot, _chainId);
        }
        uint256 settlementLayerChainId;
        uint256 settlementLayerBatchNumber;
        uint256 settlementLayerBatchRootMask;
        // Preventing stack too deep error
        {
            // Now, we just need to double check whether this chainId leaf was present in the tree.
            uint256 settlementLayerPackedBatchInfo = uint256(_proof[result.ptr]);
            ++result.ptr;
            settlementLayerBatchNumber = uint256(settlementLayerPackedBatchInfo >> 128);
            settlementLayerBatchRootMask = uint256(settlementLayerPackedBatchInfo & ((1 << 128) - 1));

            settlementLayerChainId = uint256(_proof[result.ptr]);
            ++result.ptr;
        }

        result = ProofData({
            settlementLayerChainId: settlementLayerChainId,
            settlementLayerBatchNumber: settlementLayerBatchNumber,
            settlementLayerBatchRootMask: settlementLayerBatchRootMask,
            batchLeafProofLen: proofMetadata.batchLeafProofLen,
            batchSettlementRoot: result.batchSettlementRoot,
            chainIdLeaf: result.chainIdLeaf,
            ptr: result.ptr,
            finalProofNode: proofMetadata.finalProofNode
        });
    }

    /// @notice Extracts slice from the proof.
    /// @param _proof The proof.
    /// @param _left The left index.
    /// @param _right The right index.
    /// @return slice The slice.
    function extractSlice(
        bytes32[] calldata _proof,
        uint256 _left,
        uint256 _right
    ) internal pure returns (bytes32[] memory slice) {
        slice = new bytes32[](_right - _left);
        for (uint256 i = _left; i < _right; ++i) {
            slice[i - _left] = _proof[i];
        }
    }

    /// @notice Extracts slice until the end of the array.
    /// @dev It is used in one place in order to circumvent the stack too deep error.
    function extractSliceUntilEnd(
        bytes32[] calldata _proof,
        uint256 _start
    ) internal pure returns (bytes32[] memory slice) {
        slice = extractSlice(_proof, _start, _proof.length);
    }
}

contracts/common/libraries/UncheckedMath.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

/**
 * @author Matter Labs
 * @custom:security-contact [email protected]
 * @notice The library for unchecked math.
 */
library UncheckedMath {
    function uncheckedInc(uint256 _number) internal pure returns (uint256) {
        unchecked {
            return _number + 1;
        }
    }

    function uncheckedAdd(uint256 _lhs, uint256 _rhs) internal pure returns (uint256) {
        unchecked {
            return _lhs + _rhs;
        }
    }
}

contracts/core/bridgehub/IBridgehubBase.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

import {L2Log, L2Message, TokenBridgingData, TxStatus} from "../../common/Messaging.sol";
import {ICTMDeploymentTracker} from "../ctm-deployment/ICTMDeploymentTracker.sol";
import {IMessageRootBase} from "../message-root/IMessageRoot.sol";
import {IAssetRouterBase} from "../../bridge/asset-router/IAssetRouterBase.sol";

struct L2TransactionRequestDirect {
    uint256 chainId;
    uint256 mintValue;
    address l2Contract;
    uint256 l2Value;
    bytes l2Calldata;
    uint256 l2GasLimit;
    uint256 l2GasPerPubdataByteLimit;
    bytes[] factoryDeps;
    address refundRecipient;
}

struct L2TransactionRequestTwoBridgesOuter {
    uint256 chainId;
    uint256 mintValue;
    uint256 l2Value;
    uint256 l2GasLimit;
    uint256 l2GasPerPubdataByteLimit;
    address refundRecipient;
    address secondBridgeAddress;
    uint256 secondBridgeValue;
    bytes secondBridgeCalldata;
}

struct L2TransactionRequestTwoBridgesInner {
    bytes32 magicValue;
    address l2Contract;
    bytes l2Calldata;
    bytes[] factoryDeps;
    bytes32 txDataHash;
}

struct BridgehubMintCTMAssetData {
    uint256 chainId;
    TokenBridgingData baseTokenBridgingData;
    uint256 batchNumber;
    bytes ctmData;
    bytes chainData;
    uint256 migrationNumber;
}

struct BridgehubBurnCTMAssetData {
    uint256 chainId;
    bytes ctmData;
    bytes chainData;
}

/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IBridgehubBase {
    /// @notice pendingAdmin is changed
    /// @dev Also emitted when new admin is accepted and in this case, `newPendingAdmin` would be zero address
    event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin);

    /// @notice Admin changed
    event NewAdmin(address indexed oldAdmin, address indexed newAdmin);

    /// @notice CTM asset registered
    event AssetRegistered(
        bytes32 indexed assetInfo,
        address indexed _assetAddress,
        bytes32 indexed additionalData,
        address sender
    );

    event SettlementLayerRegistered(uint256 indexed chainId, bool isWhitelisted);

    event NewChain(uint256 indexed chainId, address chainTypeManager, address indexed chainGovernance);

    event ChainTypeManagerAdded(address indexed chainTypeManager);

    event ChainTypeManagerRemoved(address indexed chainTypeManager);

    event BaseTokenAssetIdRegistered(bytes32 indexed assetId);

    /// @notice Starts the transfer of admin rights. Only the current admin or owner can propose a new pending one.
    /// @notice New admin can accept admin rights by calling `acceptAdmin` function.
    /// @param _newPendingAdmin Address of the new admin
    function setPendingAdmin(address _newPendingAdmin) external;

    /// @notice Accepts transfer of admin rights. Only pending admin can accept the role.
    function acceptAdmin() external;

    /// Getters
    function chainTypeManagerIsRegistered(address _chainTypeManager) external view returns (bool);

    function chainTypeManager(uint256 _chainId) external view returns (address);

    function assetIdIsRegistered(bytes32 _baseTokenAssetId) external view returns (bool);

    function baseToken(uint256 _chainId) external view returns (address);

    function baseTokenAssetId(uint256 _chainId) external view returns (bytes32);

    function messageRoot() external view returns (IMessageRootBase);

    function getZKChain(uint256 _chainId) external view returns (address);

    function getAllZKChains() external view returns (address[] memory);

    function getAllZKChainChainIDs() external view returns (uint256[] memory);

    function admin() external view returns (address);

    function assetRouter() external view returns (IAssetRouterBase);

    function chainRegistrationSender() external view returns (address);

    function whitelistedSettlementLayers(uint256 _chainId) external view returns (bool);

    function settlementLayer(uint256 _chainId) external view returns (uint256);

    function ctmAssetIdFromChainId(uint256 _chainId) external view returns (bytes32);

    function ctmAssetIdFromAddress(address _ctmAddress) external view returns (bytes32);

    function l1CtmDeployer() external view returns (ICTMDeploymentTracker);

    function ctmAssetIdToAddress(bytes32 _assetInfo) external view returns (address);

    function chainAssetHandler() external view returns (address);

    /// Mailbox forwarder
    function proveL2MessageInclusion(
        uint256 _chainId,
        uint256 _batchNumber,
        uint256 _index,
        L2Message calldata _message,
        bytes32[] calldata _proof
    ) external view returns (bool);

    function proveL2LogInclusion(
        uint256 _chainId,
        uint256 _batchNumber,
        uint256 _index,
        L2Log memory _log,
        bytes32[] calldata _proof
    ) external view returns (bool);

    function proveL1ToL2TransactionStatus(
        uint256 _chainId,
        bytes32 _l2TxHash,
        uint256 _l2BatchNumber,
        uint256 _l2MessageIndex,
        uint16 _l2TxNumberInBatch,
        bytes32[] calldata _merkleProof,
        TxStatus _status
    ) external view returns (bool);

    function l2TransactionBaseCost(
        uint256 _chainId,
        uint256 _gasPrice,
        uint256 _l2GasLimit,
        uint256 _l2GasPerPubdataByteLimit
    ) external view returns (uint256);

    /// Registry
    function addChainTypeManager(address _chainTypeManager) external;

    function removeChainTypeManager(address _chainTypeManager) external;

    function addTokenAssetId(bytes32 _baseTokenAssetId) external;

    function setCTMAssetAddress(bytes32 _additionalData, address _assetAddress) external;

    /// Asset Handler functions
    function forwardedBridgeBurnSetSettlementLayer(
        uint256 _chainId,
        uint256 _newSettlementLayerChainId
    ) external returns (address zkChain, address ctm);

    function forwardedBridgeMint(
        bytes32 _assetId,
        uint256 _chainId,
        TokenBridgingData calldata _baseTokenBridgingData
    ) external returns (address zkChain, address ctm);

    function registerNewZKChain(uint256 _chainId, address _zkChain, bool _checkMaxNumberOfZKChains) external;

    function forwardedBridgeConfirmTransferResult(
        uint256 _chainId,
        TxStatus _txStatus
    ) external returns (address zkChain, address ctm);
}

contracts/core/bridgehub/L1BridgehubErrors.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.21;

// 0x587df426
error AlreadyCurrentSL(uint256 blockChainId);
// 0xd506f12c
error BaseTokenOriginChainIdNotRegistered();
// 0x178de541
error BaseTokenOriginTokenNotRegistered();
// 0xa695b1ef
error BatchZeroNotAllowed();
// 0xb0b5006f
error ChainAlreadyRegistered();
// 0xbe263463
error ChainBatchRootAlreadyExists(uint256 chainId, uint256 batchNumber);
// 0x655c373c
error ChainBatchRootZero();
// 0x65e8a019
error ChainExists();
// 0xf8d5f418
error ChainNotReadyForMigration(uint256 chainId);
// 0x824e4e26
error ChainsSettlementLayerMismatch(uint256 chainToRegisterSL, uint256 chainRegisteredOnSL);
// 0x1ed6c04f
error ChainsSettlingOnL1();
// 0x5d03f19d
error CurrentBatchNumberAlreadySet();
// 0x68d91b49
error DepthMoreThanOneForRecursiveMerkleProof();
// 0xd9d3fc89
error HistoricalSettlementLayerMismatch(uint256 expectedSettlementLayer, uint256 actualSettlementLayer);
// 0x48857c1d
error IncorrectChainAssetId(bytes32 assetId, bytes32 assetIdFromChainId);
// 0xf5e39c1f
error IncorrectSender(address prevMsgSender, address chainAdmin);
// 0x896555dc
error InvalidSettlementLayerForBatch(uint256 chainId, uint256 batchNumber, uint256 claimedSettlementLayer);
// 0x47d42b1b
error IteratedMigrationsNotSupported();
// 0xc3bd3c65
error LocallyNoChainsAtGenesis();
// 0x913183d8
error MessageRootNotRegistered();
// 0x338fe0e7
error MigrationIntervalInvalid();
// 0x81c5808d
error MigrationIntervalNotSet();
// 0x4010a88d
error MigrationNotToL1();
// 0xde1362a2
error MigrationNumberMismatch(uint256 _expected, uint256 _actual);
// 0x7f4316f3
error NoEthAllowed();
// 0x366c42f8
error NonConsecutiveBatchNumber(uint256 chainId, uint256 batchNumber);
// 0xc97b1a8a
error NotAllChainsOnL1();
// 0x8beee3a3
error NotChainAssetHandler(address sender, address chainAssetHandler);
// 0x88d9dae3
error NotCurrentSettlementLayer(uint256 currentSettlementLayer, uint256 newSettlementLayer);
// 0x472477e2
error NotInGatewayMode();
// 0x23295f0e
error NotOwner(address sender, address owner);
// 0x693cd3dc
error NotOwnerViaRouter(address msgSender, address originalCaller);
// 0xa2ac02a0
error NotRelayedSender(address msgSender, address settlementLayerRelaySender);
// 0xb35a7373
error NotSystemContext(address _sender);
// 0x3db511f4
error OnlyAssetTracker(address, address);
// 0x527b87c7
error OnlyBridgehub(address msgSender, address bridgehub);
// 0x2d396674
error OnlyBridgehubOrChainAssetHandler(address sender, address bridgehub, address chainAssetHandler);
// 0x73fe6c1b
error OnlyChain(address msgSender, address zkChainAddress);
// 0x3e088470
error OnlyChainAssetHandler(address sender, address chainAssetHandler);
// 0xec76af13
error OnlyGateway();
// 0x8d14ca84
error OnlyL1();
// 0x6b75db8c
error OnlyOnSettlementLayer();
// 0xb78dbaa7
error SecondBridgeAddressTooLow(address secondBridgeAddress, address minSecondBridgeAddress);
// 0xefb272e2
error SettlementLayerMustNotBeL1();
// 0x36917565
error SLHasDifferentCTM();
// 0x90c7cbf1
error SLNotWhitelisted();
// 0x17a78622
error TotalBatchesExecutedLessThanV31UpgradeChainBatchNumber();
// 0x70a472bd
error TotalBatchesExecutedZero();
// 0x883fc41b
error V31UpgradeChainBatchNumberAlreadySet();
// 0x92626457
error WrongCounterPart(address addressOnCounterPart, address l2BridgehubAddress);
// 0x7b968d06
error ZKChainNotRegistered();

contracts/core/chain-asset-handler/IChainAssetHandler.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

import {IAssetHandler} from "../../bridge/interfaces/IAssetHandler.sol";

/// @notice Tracks migration batch numbers for a chain that migrated to a settlement layer and back.
/// @param migrateToGWBatchNumber The last batch executed on L1 before migrating TO the settlement layer.
/// @param migrateFromGWBatchNumber The last batch executed on the settlement layer before migrating back to L1.
/// @param settlementLayerBatchLowerBound The lower bound for the settlement layer's batch number at the time the chain
/// migrated TO the settlement layer. The chain's data will only start appearing in settlement layer batches at or after this point.
/// @param settlementLayerBatchUpperBound The upper bound for the settlement layer's batch number at the time the chain
/// migrated FROM the settlement layer. This is not a perfect bound — the exact settlement layer batch number is not
/// trivially available, so we record the settlement layer's current batch number when `bridgeMint` is called on L1 to
/// finalize the return migration. The sooner the migration is finalized, the more precise this value is, since the
/// settlement layer continues producing batches in the meantime. A more precise solution will be introduced in future releases.
/// @param settlementLayerChainId The chain ID of the settlement layer where the chain settled during the time period.
/// @param isActive Whether the chain is actively settling on the settlement layer right now.
struct MigrationInterval {
    uint256 migrateToGWBatchNumber;
    uint256 migrateFromGWBatchNumber;
    uint256 settlementLayerBatchLowerBound;
    uint256 settlementLayerBatchUpperBound;
    uint256 settlementLayerChainId;
    bool isActive;
}

/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IChainAssetHandlerBase is IAssetHandler {
    /// @notice Emitted when the bridging to the chain is started.
    /// @param chainId Chain ID of the ZK chain
    /// @param migrationNumber The migration number for this migration.
    /// @param assetId Asset ID of the token for the zkChain's CTM
    /// @param settlementLayerChainId The chain id of the settlement layer the chain migrates to.
    event MigrationStarted(
        uint256 indexed chainId,
        uint256 migrationNumber,
        bytes32 indexed assetId,
        uint256 indexed settlementLayerChainId
    );

    /// @notice Emitted when the bridging to the chain is complete.
    /// @param chainId Chain ID of the ZK chain
    /// @param migrationNumber The migration number for this migration.
    /// @param assetId Asset ID of the token for the zkChain's CTM
    /// @param zkChain The address of the ZK chain on the chain where it is migrated to.
    event MigrationFinalized(
        uint256 indexed chainId,
        uint256 migrationNumber,
        bytes32 indexed assetId,
        address indexed zkChain
    );

    /// @notice Emitted when migration related fns are paused.
    /// @param pauser Address that triggered the pause
    event PausedMigration(address indexed pauser);

    /// @notice Emitted when migration related fns are unpaused.
    /// @param pauser Address that triggered the unpause
    event UnpausedMigration(address indexed pauser);

    function migrationNumber(uint256 _chainId) external view returns (uint256);

    /// @dev Denotes whether the migrations of chains is paused.
    function migrationPaused() external view returns (bool);

    /// @notice Pauses migration functions.
    function pauseMigration() external;

    /// @notice Unpauses migration functions.
    function unpauseMigration() external;
}

contracts/core/chain-asset-handler/IL1ChainAssetHandler.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

import {MigrationInterval} from "./IChainAssetHandler.sol";

/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IL1ChainAssetHandler {
    function isMigrationInProgress(uint256 _chainId) external view returns (bool);

    function isReadyForMigration(uint256 _chainId) external view returns (bool);

    /// @notice Returns the migration interval for a chain at a specific migration number.
    /// @param _chainId The ID of the chain.
    /// @param _migrationNumber The migration number (0 for legacy GW, 1+ for regular migrations).
    /// @return interval The migration interval data.
    function migrationInterval(
        uint256 _chainId,
        uint256 _migrationNumber
    ) external view returns (MigrationInterval memory interval);

    /// @notice Sets a historical migration interval for a chain.
    /// @dev Only callable by owner. Used to set legacy GW migration data for chains that used the old GW.
    /// @param _chainId The ID of the chain.
    /// @param _migrationNumber The migration number to set.
    /// @param _interval The migration interval data.
    function setHistoricalMigrationInterval(
        uint256 _chainId,
        uint256 _migrationNumber,
        MigrationInterval calldata _interval
    ) external;

    /// @notice Validates if a claimed settlement layer is valid for a given chain and batch number.
    /// @param _chainId The ID of the chain.
    /// @param _batchNumber The batch number to check.
    /// @param _claimedSettlementLayer The settlement layer chain ID claimed in the proof.
    /// @param _claimedSettlementLayerBatchNumber The batch number on the settlement layer claimed in the proof.
    /// @return True if the claimed settlement layer is valid for this chain and batch.
    function isValidSettlementLayer(
        uint256 _chainId,
        uint256 _batchNumber,
        uint256 _claimedSettlementLayer,
        uint256 _claimedSettlementLayerBatchNumber
    ) external view returns (bool);
}

contracts/core/ctm-deployment/ICTMDeploymentTracker.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {IBridgehubBase} from "../bridgehub/IBridgehubBase.sol";
import {IAssetRouterBase} from "../../bridge/asset-router/IAssetRouterBase.sol";
import {IL1AssetDeploymentTracker} from "../../bridge/interfaces/IL1AssetDeploymentTracker.sol";

/// @author Matter Labs
/// @custom:security-contact [email protected]
interface ICTMDeploymentTracker is IL1AssetDeploymentTracker {
    function BRIDGE_HUB() external view returns (IBridgehubBase);

    function L1_ASSET_ROUTER() external view returns (IAssetRouterBase);

    function registerCTMAssetOnL1(address _ctmAddress) external;

    function calculateAssetId(address _l1CTM) external view returns (bytes32);
}

contracts/core/message-root/IL1MessageRoot.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

/**
 * @author Matter Labs
 * @notice MessageRoot contract is responsible for storing and aggregating the roots of the batches from different chains into the MessageRoot.
 * @custom:security-contact [email protected]
 */
interface IL1MessageRoot {
    /// @notice The chain id of the legacy Era-based Gateway chain.
    /// @dev Lives only on the L1 MessageRoot; used by L1ChainAssetHandler to gate legacy GW migration intervals.
    // solhint-disable-next-line func-name-mixedcase
    function ERA_GATEWAY_CHAIN_ID() external view returns (uint256);

    function v31UpgradeChainBatchNumber(uint256 _chainId) external view returns (uint256);

    function saveV31UpgradeChainBatchNumber(uint256 _chainId) external;

    /// @notice Returns whether a chain has not finalized its v31 upgrade marker yet.
    /// @param _chainId The chain id to query.
    function isPreV31(uint256 _chainId) external view returns (bool);
}

contracts/core/message-root/IMessageRoot.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {IMessageVerification} from "../../common/interfaces/IMessageVerification.sol";
import {ProofData} from "../../common/Messaging.sol";

// Chain tree consists of batch commitments as their leaves. We use hash of "new bytes(96)" as the hash of an empty leaf.
bytes32 constant CHAIN_TREE_EMPTY_ENTRY_HASH = bytes32(
    0x46700b4d40ac5c35af2c22dda2787a91eb567b06c924a8fb8ae9a05b20c08c21
);

// The single shared tree consists of the roots of chain trees as its leaves. We use hash of "new bytes(96)" as the hash of an empty leaf.
bytes32 constant SHARED_ROOT_TREE_EMPTY_HASH = bytes32(
    0x46700b4d40ac5c35af2c22dda2787a91eb567b06c924a8fb8ae9a05b20c08c21
);

// The value that is saved in the v31UpgradeChainBatchNumber mapping for all deployed chains until the chain upgrades to v31.
uint256 constant V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE = uint256(
    keccak256(abi.encodePacked("V31_UPGRADE_CHAIN_BATCH_NUMBER_PLACEHOLDER_VALUE"))
);

/**
 * @author Matter Labs
 * @notice MessageRoot contract is responsible for storing and aggregating the roots of the batches from different chains into the MessageRoot.
 * @custom:security-contact [email protected]
 */
interface IMessageRootBase is IMessageVerification {
    /// @notice Emitted when a new chain is added to the MessageRoot.
    /// @param chainId The ID of the chain that is being added to the MessageRoot.
    /// @param chainIndex The index of the chain that is being added. Note, that chain where
    /// the MessageRoot contract was deployed has chainIndex of 0, and this event is being emitted for it.
    event AddedChain(uint256 indexed chainId, uint256 indexed chainIndex);

    /// @notice Emitted when a new chain batch root is appended to the chainTree.
    /// @param chainId The ID of the chain whose chain batch root is being added to the chainTree.
    /// @param batchNumber The number of the batch to which chain batch root belongs.
    /// @param chainBatchRoot The value of chain batch root which is being added.
    event AppendedChainBatchRoot(uint256 indexed chainId, uint256 indexed batchNumber, bytes32 chainBatchRoot);

    /// @notice Emitted when a new chainTree root is produced and its corresponding leaf in sharedTree is updated.
    /// @param chainId The ID of the chain whose chainTree root is being updated.
    /// @param chainRoot The updated Merkle root of the chainTree after appending the latest batch root.
    /// @param chainIdLeafHash The Merkle leaf value computed from `chainRoot` and the chain's ID, used to update the shared tree.
    event NewChainRoot(uint256 indexed chainId, bytes32 chainRoot, bytes32 chainIdLeafHash);

    /// @notice Emitted whenever the sharedTree is updated, and the new InteropRoot (root of the sharedTree) is generated.
    /// @param chainId The ID of the chain where the sharedTree was updated.
    /// @param blockNumber The block number of the block in which the sharedTree was updated.
    /// @param logId The ID of the log emitted when a new InteropRoot.
    /// @param sides The "sides" of the interop root. In this release which uses proof-based interop the sides is an array
    /// of length one, which only include the interop root itself. More on that in `L2InteropRootStorage` contract.
    event NewInteropRoot(uint256 indexed chainId, uint256 indexed blockNumber, uint256 indexed logId, bytes32[] sides);

    function BRIDGE_HUB() external view returns (address);

    function addNewChain(uint256 _chainId, uint256 _startingBatchNumber) external;

    function addChainBatchRoot(uint256 _chainId, uint256 _batchNumber, bytes32 _chainBatchRoot) external;

    function chainBatchRoots(uint256 _chainId, uint256 _batchNumber) external view returns (bytes32);

    function historicalRoot(uint256 _blockNumber) external view returns (bytes32);

    /// @dev Used to parse the merkle proof data, this function calls a library function.
    function getProofData(
        uint256 _chainId,
        uint256 _batchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof
    ) external pure returns (ProofData memory);

    function setMigratingChainBatchNumber(uint256 _chainId, uint256 _batchNumber) external;

    function currentChainBatchNumber(uint256 _chainId) external view returns (uint256);

    function getMerklePathForChain(uint256 _chainId) external view returns (bytes32[] memory);
}

contracts/core/message-root/MessageRootBase.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {Initializable} from "@openzeppelin/contracts-v4/proxy/utils/Initializable.sol";

import {DynamicIncrementalMerkle} from "../../common/libraries/DynamicIncrementalMerkle.sol";

import {CHAIN_TREE_EMPTY_ENTRY_HASH, IMessageRootBase, SHARED_ROOT_TREE_EMPTY_HASH} from "./IMessageRoot.sol";
import {
    BatchZeroNotAllowed,
    ChainBatchRootAlreadyExists,
    ChainBatchRootZero,
    ChainExists,
    DepthMoreThanOneForRecursiveMerkleProof,
    MessageRootNotRegistered,
    NonConsecutiveBatchNumber,
    OnlyAssetTracker,
    OnlyChainAssetHandler,
    OnlyBridgehubOrChainAssetHandler,
    OnlyChain
} from "../bridgehub/L1BridgehubErrors.sol";

import {GW_ASSET_TRACKER_ADDR} from "../../common/l2-helpers/L2ContractAddresses.sol";

import {MessageHashing, ProofData} from "../../common/libraries/MessageHashing.sol";
import {ReentrancyGuard} from "../../common/ReentrancyGuard.sol";
import {IBridgehubBase} from "../bridgehub/IBridgehubBase.sol";
import {FullMerkle} from "../../common/libraries/FullMerkle.sol";

import {MessageVerification} from "../../common/MessageVerification.sol";

/// @author Matter Labs
/// @custom:security-contact [email protected]
/// @dev The MessageRoot contract is responsible for storing the cross message roots of the chains and the aggregated root of all chains.
/// @dev From V31 onwards it is also used for L2->L1 message verification, this allows bypassing the Mailbox of individual chains.
/// This is especially useful for chains settling on Gateway.
abstract contract MessageRootBase is IMessageRootBase, ReentrancyGuard, Initializable, MessageVerification {
    using FullMerkle for FullMerkle.FullTree;
    using DynamicIncrementalMerkle for DynamicIncrementalMerkle.Bytes32PushTree;

    /*//////////////////////////////////////////////////////////////
                            IMMUTABLE GETTERS
    //////////////////////////////////////////////////////////////*/

    function _bridgehub() internal view virtual returns (address);

    function _chainAssetHandler() internal view virtual returns (address);

    // solhint-disable-next-line func-name-mixedcase
    function L1_CHAIN_ID() public view virtual returns (uint256);

    /// @notice The number of chains that are registered.
    uint256 public chainCount;

    /// @notice The mapping from chainId to chainIndex. Note index 0 is maintained for the chain the contract is on.
    mapping(uint256 chainId => uint256 chainIndex) public chainIndex;

    /// @notice The mapping from chainIndex to chainId.
    mapping(uint256 chainIndex => uint256 chainId) public chainIndexToId;

    /// @notice The shared full merkle tree storing the aggregate hash.
    /// @dev Note, that on L1, the chainId leaves are empty.
    FullMerkle.FullTree public sharedTree;

    /// @dev The incremental merkle tree storing the chain message roots.
    /// @dev On L1, these are empty leaves and are populated only during the addition of the chain
    /// are not updated thereafter.
    mapping(uint256 chainId => DynamicIncrementalMerkle.Bytes32PushTree tree) internal chainTree;

    /// @notice The mapping from block number to the global message root.
    /// @dev Each block might have multiple txs that change the historical root. You can safely use the final root in the block,
    /// since each new root cumulatively aggregates all prior changes — so the last root always contains (at minimum) everything
    /// from the earlier ones.
    /// @dev Populated only on L2.
    mapping(uint256 blockNumber => bytes32 globalMessageRoot) public historicalRoot;

    /// @dev Chain ID of L1.
    /// @dev Kept here for storage layout compatibility with previous versions.
    uint256 internal DEPRECATED_l1ChainId;

    /// @notice The mapping from chainId to its current executed batch number.
    /// @dev We store the current batch number for each chain once it upgrades to v31. This value is moved between settlement layers
    /// during migration to ensure consistency.
    mapping(uint256 chainId => uint256 currentChainBatchNumber) public currentChainBatchNumber;

    /// @notice The mapping from chainId to batchNumber to chainBatchRoot.
    /// @dev These are the same values as the leaves of the chainTree.
    /// @dev We store these values for message verification on L1 and Gateway.
    /// @dev We only updated the chainTree on deprecated Era GW as of V31.
    /// @dev An expected invariant is that for all batches starting from currentChainBatchNumber + 1, the `chainBatchRoots` is 0.
    mapping(uint256 chainId => mapping(uint256 batchNumber => bytes32 chainRoot)) public chainBatchRoots;

    /// @notice The current logId value emitted in `NewInteropRoot` events.
    /// @dev Increments at most once per block: all emissions within the same block share the same
    /// logId, and the counter only advances when `block.number` changes.
    /// @dev Note that it counts starting from V31 ONLY.
    uint256 public interopRootLogId;

    /// @notice The block number at which the last interop root was emitted.
    /// @dev Used to ensure logId increments per block: within the same block all NewInteropRoot
    /// events share the same logId value, and the counter only advances when the block changes.
    uint256 public lastEmitBlock;

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[35] private __gap;

    /// @notice Checks that the message sender is the bridgehub or the chain asset handler.
    modifier onlyBridgehubOrChainAssetHandler() {
        if (msg.sender != _bridgehub() && msg.sender != _chainAssetHandler()) {
            revert OnlyBridgehubOrChainAssetHandler(msg.sender, address(_bridgehub()), _chainAssetHandler());
        }
        _;
    }

    /// @notice Checks that the message sender is the chain asset handler.
    modifier onlyChainAssetHandler() {
        if (msg.sender != _chainAssetHandler()) {
            revert OnlyChainAssetHandler(msg.sender, _chainAssetHandler());
        }
        _;
    }

    /// @notice Checks that the message sender is the specified ZK Chain.
    /// @param _chainId The ID of the chain that is required to be the caller.
    modifier onlyChain(uint256 _chainId) {
        if (msg.sender != IBridgehubBase(_bridgehub()).getZKChain(_chainId)) {
            revert OnlyChain(msg.sender, IBridgehubBase(_bridgehub()).getZKChain(_chainId));
        }
        _;
    }

    /// @notice On L1, the chain can add it directly, while on GW, the asset tracker should add it,
    /// @dev Note, that at the moment of the v31 upgrade we no chains to settle on top of the old
    /// Era-based Gateway, and so no special handling is needed for pre-v31 chains.
    modifier addChainBatchRootRestriction(uint256 _chainId) {
        if (block.chainid != L1_CHAIN_ID()) {
            if (msg.sender != GW_ASSET_TRACKER_ADDR) {
                revert OnlyAssetTracker(msg.sender, GW_ASSET_TRACKER_ADDR);
            }
        } else {
            if (msg.sender != IBridgehubBase(_bridgehub()).getZKChain(_chainId)) {
                revert OnlyChain(msg.sender, IBridgehubBase(_bridgehub()).getZKChain(_chainId));
            }
        }
        _;
    }

    function _initialize() internal {
        // slither-disable-next-line unused-return
        sharedTree.setup(SHARED_ROOT_TREE_EMPTY_HASH);
        _addNewChain(block.chainid, 0);
    }

    /// @notice Adds a single chain to the message root.
    /// @param _chainId The ID of the chain that is being added to the message root.
    function addNewChain(uint256 _chainId, uint256 _startingBatchNumber) external onlyBridgehubOrChainAssetHandler {
        if (chainRegistered(_chainId)) {
            revert ChainExists();
        }
        _addNewChain(_chainId, _startingBatchNumber);
    }

    /// @notice During the chain migration, we move the batch number from the old settlement layer to the new one to ensure consistency.
    function setMigratingChainBatchNumber(uint256 _chainId, uint256 _batchNumber) external onlyChainAssetHandler {
        // Note, that it is possible that chain migrates to GW and returns to L1 without
        // committing any batches on GW.
        require(currentChainBatchNumber[_chainId] <= _batchNumber, ChainBatchRootAlreadyExists(_chainId, _batchNumber));
        currentChainBatchNumber[_chainId] = _batchNumber;
    }

    function chainRegistered(uint256 _chainId) public view returns (bool) {
        return (_chainId == block.chainid || chainIndex[_chainId] != 0);
    }

    /// @notice Adds a new chainBatchRoot to the chainTree.
    /// @param _chainId The ID of the chain whose chainBatchRoot is being added to the chainTree.
    /// @param _batchNumber The number of the batch to which _chainBatchRoot belongs.
    /// @param _chainBatchRoot The value of chainBatchRoot which is being added.
    function addChainBatchRoot(
        uint256 _chainId,
        uint256 _batchNumber,
        bytes32 _chainBatchRoot
    ) public virtual addChainBatchRootRestriction(_chainId) {
        // Make sure that chain is registered.
        if (!chainRegistered(_chainId)) {
            revert MessageRootNotRegistered();
        }
        require(_chainBatchRoot != bytes32(0), ChainBatchRootZero());
        require(
            chainBatchRoots[_chainId][_batchNumber] == bytes32(0),
            ChainBatchRootAlreadyExists(_chainId, _batchNumber)
        );
        uint256 expectedNewChainBatchNumber = currentChainBatchNumber[_chainId] + 1;
        require(_batchNumber == expectedNewChainBatchNumber, NonConsecutiveBatchNumber(_chainId, _batchNumber));

        chainBatchRoots[_chainId][_batchNumber] = _chainBatchRoot;
        currentChainBatchNumber[_chainId] = expectedNewChainBatchNumber;
    }

    /// @notice Emits a new interop root event when the shared tree root changes.
    /// @dev The logId (interopRootLogId) increments at most once per block. All emissions
    /// within the same block share the same logId so that the server node can group them by block.
    function _emitRoot(bytes32 _root) internal {
        // What happens here is we query for the current sharedTreeRoot and emit the event stating that new InteropRoot is "created".
        // The reason for the usage of "bytes32[] memory _sides" to store the InteropRoot is explained in L2InteropRootStorage contract.
        bytes32[] memory _sides = new bytes32[](1);
        _sides[0] = _root;

        uint256 currentCount = interopRootLogId;
        if (block.number != lastEmitBlock) {
            ++currentCount;
            interopRootLogId = currentCount;
            lastEmitBlock = block.number;
        }

        emit NewInteropRoot(block.chainid, block.number, currentCount, _sides);
    }

    /// @notice Gets the aggregated root of all chains.
    function getAggregatedRoot() external view returns (bytes32) {
        if (chainCount == 0) {
            return SHARED_ROOT_TREE_EMPTY_HASH;
        }
        return sharedTree.root();
    }

    /// @dev Gets the message root of a single chain.
    /// @param _chainId The ID of the chain whose message root is being queried.
    function getChainRoot(uint256 _chainId) external view returns (bytes32) {
        // Make sure that chain is registered.
        if (!chainRegistered(_chainId)) {
            revert MessageRootNotRegistered();
        }
        return chainTree[_chainId].root();
    }

    /// @dev Adds a single chain to the message root.
    /// @param _chainId The ID of the chain that is being added to the message root.
    function _addNewChain(uint256 _chainId, uint256 _startingBatchNumber) internal {
        uint256 cachedChainCount = chainCount;

        // Since only the bridgehub can add new chains to the message root, it is expected that
        // it will be responsible for ensuring that the number of chains does not exceed the limit.
        ++chainCount;
        chainIndex[_chainId] = cachedChainCount;
        chainIndexToId[cachedChainCount] = _chainId;
        currentChainBatchNumber[_chainId] = _startingBatchNumber;

        // slither-disable-next-line unused-return
        bytes32 initialHash = chainTree[_chainId].setup(CHAIN_TREE_EMPTY_ENTRY_HASH);

        bytes32 sharedTreeRoot = sharedTree.pushNewLeaf(MessageHashing.chainIdLeafHash(initialHash, _chainId));

        emit AddedChain(_chainId, cachedChainCount);

        _emitRoot(sharedTreeRoot);
        historicalRoot[block.number] = sharedTreeRoot;
    }

    //////////////////////////////
    //// IMessageVerification ////
    //////////////////////////////

    function _proveL2LeafInclusionOnSettlementLayer(
        uint256 _chainId,
        uint256 _batchNumber,
        ProofData memory _proofData,
        bytes32[] calldata _proof,
        uint256 _depth
    ) internal view virtual returns (bool);

    function _proveL2LeafInclusionRecursive(
        uint256 _chainId,
        uint256 _batchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof,
        uint256 _depth
    ) internal view virtual override returns (bool) {
        ProofData memory proofData = MessageHashing._getProofData({
            _chainId: _chainId,
            _batchNumber: _batchNumber,
            _leafProofMask: _leafProofMask,
            _leaf: _leaf,
            _proof: _proof
        });
        if (proofData.finalProofNode) {
            // For proof based interop this is the SL InteropRoot at block number _batchNumber
            bytes32 correctBatchRoot = _getChainBatchRoot(_chainId, _batchNumber);
            return correctBatchRoot == proofData.batchSettlementRoot && correctBatchRoot != bytes32(0);
        }
        if (_depth == 1) {
            revert DepthMoreThanOneForRecursiveMerkleProof();
        }

        return
            _proveL2LeafInclusionOnSettlementLayer({
                _chainId: _chainId,
                _batchNumber: _batchNumber,
                _proofData: proofData,
                _proof: _proof,
                _depth: _depth
            });
    }

    /// @notice Internal to get the historical batch root for chains.
    function _getChainBatchRoot(uint256 _chainId, uint256 _batchNumber) internal view returns (bytes32) {
        /// In current server the zeroth batch does not have L2->L1 logs.
        require(_batchNumber > 0, BatchZeroNotAllowed());
        bytes32 savedChainBatchRoot = chainBatchRoots[_chainId][_batchNumber];
        if (savedChainBatchRoot != bytes32(0)) {
            return savedChainBatchRoot;
        }

        return _noBatchFallback(_chainId, _batchNumber);
    }

    /// @notice This function is used to prove the return the expected batch root for batch number that is not stored inside the message root.
    /// @dev On L2, it should always return 0, since on newer GW implementation it is guaranteed that all available batch roots are stored inside the message root.
    /// @dev On L1, if the batch was produced before the v31 upgrade, we must query the chain. Once the ZKsync OS CTM's ownership is transferred to the decentralized
    /// governance, we can trust this value completely. Before it happens, we just assume that no ZKsync OS based Gateway is present,
    /// and so the chain can at most damage itself by providing a wrongful batch root for its own batches, but it cannot affect other chains.
    function _noBatchFallback(uint256 _chainId, uint256 _batchNumber) internal view virtual returns (bytes32);

    /// @notice Extracts and returns proof data for settlement layer verification.
    /// @dev Wrapper function around MessageHashing._getProofData for public access.
    /// @dev The caller should check that the proof has recursion at most depth 1, i.e. only a single intermediate Gateway between the chain and L1.
    /// @dev This check is performed when the MessageRoot verifies the proof, so often it can be skipped.
    /// @param _chainId The chain ID where the proof was generated.
    /// @param _batchNumber The batch number containing the proof.
    /// @param _leafProofMask The leaf proof mask for merkle verification.
    /// @param _leaf The leaf hash to verify.
    /// @param _proof The merkle proof array.
    /// @return The extracted proof data including settlement layer information.
    function getProofData(
        uint256 _chainId,
        uint256 _batchNumber,
        uint256 _leafProofMask,
        bytes32 _leaf,
        bytes32[] calldata _proof
    ) public pure returns (ProofData memory) {
        return
            MessageHashing._getProofData({
                _chainId: _chainId,
                _batchNumber: _batchNumber,
                _leafProofMask: _leafProofMask,
                _leaf: _leaf,
                _proof: _proof
            });
    }

    /// @dev Returns merkle path in `sharedTree` for a certain chain.
    /// @param _chainId Id of the chain to get merkle path for.
    function getMerklePathForChain(uint256 _chainId) external view returns (bytes32[] memory) {
        if (!chainRegistered(_chainId)) {
            revert MessageRootNotRegistered();
        }
        uint256 index = chainIndex[_chainId];
        return sharedTree.merklePath(index);
    }

    /// @dev Returns `chainTree` by chain id.
    /// @param _chainId Id of the chain to get tree for.
    function getChainTree(uint256 _chainId) external view returns (DynamicIncrementalMerkle.Bytes32PushTree memory) {
        return chainTree[_chainId];
    }
}

contracts/state-transition/L1StateTransitionErrors.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.21;

// 0xb325f767
error AdminZero();
// 0xca1c3cbc
error AlreadyMigrated();
// 0xb0bd6aca
error AlreadySigned();
// 0x125d99b0
error BlobHashBlobCommitmentMismatchValue();
// 0xafda12bf
error CommitBasedInteropNotSupported();
// 0xc02d3ee3
error ContractNotDeployed();
// 0xdf2c5fa5
error DependencyRootsRollingHashMismatch(bytes32 _expected, bytes32 _actual);
// 0xacf542ab
error DepositsAlreadyPaused();
// 0xa4d3098c
error DepositsNotPaused();
// 0xdeeb6943
error DepositsPaused();
// 0xedae13f3
error ExecutedIsNotConsistentWithVerified(uint256 batchesExecuted, uint256 batchesVerified);
// 0xc866ff2c
error InitialForceDeploymentMismatch(bytes32 forceDeploymentHash, bytes32 initialForceDeploymentHash);
// 0xeaeeb154
error InitializeNotAvailable();
// 0xfbd630b8
error InvalidBatchesDataLength(uint256 batchesDataLength, uint256 priorityOpsDataLength);
// 0xc06789fa
error InvalidCommitment();
// 0xd2531c15
error InvalidL2DAOutputHash(bytes32 l2DAValidatorOutputHash);
// 0x30043900
error InvalidNextLeafIndex(uint256 treeNextLeafIndex, uint256 commitmentNextLeafIndex);
// 0xfb1a3b59
error InvalidNumberOfBatchHashes(uint256 batchHashesLength, uint256 expected);
// 0xbeb96791
error InvalidNumberOfBlobs(uint256 blobsProvided, uint256 maxBlobsSupported);
// 0x5513177c
error InvalidPubdataHash(bytes32 fullPubdataHash, bytes32 providedPubdataHash);
// 0x5717f940
error InvalidPubdataSource(uint8 pubdataSource);
// 0x90f67ecf
error InvalidStartIndex(uint256 treeStartIndex, uint256 commitmentStartIndex);
// 0x0f67bc0a
error InvalidUnprocessedIndex(uint256 treeUnprocessedIndex, uint256 commitmentUnprocessedIndex);
// 0x2e89f517
error L1DAValidatorAddressIsZero();
// 0x7fbff2dd
error L1DAValidatorInvalidSender(address msgSender);
// 0x7d769244
error MemberAlreadyExists(address member);
// 0x1599dcf8
error MemberDoesNotExist(address member);
// 0x9b5f85eb
error MessageRootIsZero();
// 0xf148c8da
error MigrationInProgress();
// 0x32fff278
error MismatchL2DACommitmentScheme(uint256 operatorProvidedScheme, uint256 expectedScheme);
// 0x2c01a4af
error MismatchNumberOfLayer1Txs(uint256 numberOfLayer1Txs, uint256 expectedLength);
// 0xf9ba09d6
error NotAllBatchesExecuted();
// 0x61d9af9e
error NotAPatchUpgrade(uint256 oldProtocolVersion, uint256 newProtocolVersion);
// 0xf05c64c6
error NotChainAdmin(address prevMsgSender, address admin);
// 0xe246dc63
error NotEnoughSignatures();
// 0x8fd63d21
error NotEraChain();
// 0xa7050bf6
error NotHistoricalRoot(bytes32);
// 0x87470e36
error NotL1(uint256 blockChainId);
// 0xd7b2559b
error NotMigrated();
// 0xd0266e26
error NotSettlementLayer();
// 0xa1b035c8
error NotSigner();
// 0xa43ae064
error NotZKChain();
// 0x1e9f6a9e
error NotZKsyncOS();
// 0x04e05fd1
error OnlyOneBlobWithCalldataAllowed();
// 0x885ae069
error OperatorDAInputTooSmall(uint256 operatorDAInputLength, uint256 minAllowedLength);
// 0x681150be
error OutdatedProtocolVersion(uint256 protocolVersion, uint256 currentProtocolVersion);
// 0x311ca4b0
error PriorityModeAlreadyAllowed();
// 0xfe26193e
error PriorityQueueNotFullyProcessed();
// 0xc59d372c
error ProtocolVersionNotUpToDate(uint256 currentProtocolVersion, uint256 protocolVersion);
// 0x2dc9747d
error PubdataInputTooSmall(uint256 pubdataInputLength, uint256 totalBlobsCommitmentSize);
// 0x9044dff9
error PubdataLengthTooBig(uint256 pubdataLength, uint256 totalBlobSizeBytes);
// 0x89935a14
error SettlementLayerChainIdMismatch();
// 0x97f58c80
error TotalPriorityTxsIsZero();
// 0x0baf1d48
error UnknownVerifierVersion();
// 0x79274f04
error UnsupportedProofMetadataVersion(uint256 metadataVersion);
// 0x52595598
error ValL1DAWrongInputLength(uint256 inputLength, uint256 expectedLength);
// 0x712d02d2
error VerifiedIsNotConsistentWithCommitted(uint256 batchesVerified, uint256 batchesCommitted);

contracts/state-transition/chain-deps/ZKChainStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.8.28;

import {IVerifier, VerifierParams} from "../chain-interfaces/IVerifier.sol";
import {PriorityQueue} from "../../state-transition/libraries/PriorityQueue.sol";
import {PriorityTree} from "../../state-transition/libraries/PriorityTree.sol";
import {L2DACommitmentScheme, PubdataPricingMode} from "../../common/Config.sol";

/// @notice Indicates whether an upgrade is initiated and if yes what type
/// @param None Upgrade is NOT initiated
/// @param Transparent Fully transparent upgrade is initiated, upgrade data is publicly known
/// @param Shadow Shadow upgrade is initiated, upgrade data is hidden
enum UpgradeState {
    None,
    Transparent,
    Shadow
}

/// @dev Logically separated part of the storage structure, which is responsible for everything related to proxy
/// upgrades and diamond cuts
/// @param proposedUpgradeHash The hash of the current upgrade proposal, zero if there is no active proposal
/// @param state Indicates whether an upgrade is initiated and if yes what type
/// @param securityCouncil Address which has the permission to approve instant upgrades (expected to be a Gnosis
/// multisig)
/// @param approvedBySecurityCouncil Indicates whether the security council has approved the upgrade
/// @param proposedUpgradeTimestamp The timestamp when the upgrade was proposed, zero if there are no active proposals
/// @param currentProposalId The serial number of proposed upgrades, increments when proposing a new one
struct UpgradeStorage {
    bytes32 proposedUpgradeHash;
    UpgradeState state;
    address securityCouncil;
    bool approvedBySecurityCouncil;
    uint40 proposedUpgradeTimestamp;
    uint40 currentProposalId;
}

/// @notice The fee params for L1->L2 transactions for the network.
/// @param pubdataPricingMode How the users will charged for pubdata in L1->L2 transactions.
/// @param batchOverheadL1Gas The amount of L1 gas required to process the batch (except for the calldata).
/// @param maxPubdataPerBatch The maximal number of pubdata that can be emitted per batch.
/// @param priorityTxMaxPubdata The maximal amount of pubdata a priority transaction is allowed to publish.
/// It can be slightly less than maxPubdataPerBatch in order to have some margin for the bootloader execution.
/// @param minimalL2GasPrice The minimal L2 gas price to be used by L1->L2 transactions. It should represent
/// the price that a single unit of compute costs.
struct FeeParams {
    PubdataPricingMode pubdataPricingMode;
    uint32 batchOverheadL1Gas;
    uint32 maxPubdataPerBatch;
    uint32 maxL2GasPerBatch;
    uint32 priorityTxMaxPubdata;
    uint64 minimalL2GasPrice;
}

/// @notice Stores the current Priority Mode (escape hatch) configuration.
/// @dev Only when `canBeActivated` is true, it is possible to enter Priority Mode.
/// @dev When `activated` is true, batch settlement is restricted to `permissionlessValidator`.
/// @param permissionlessValidator The only address allowed to call commit/prove/execute when Priority Mode is enabled.
/// @param transactionFilterer The transaction filterer to be used when Priority Mode is activated.
/// Only ZK Governance can change it.
struct PriorityModeInformation {
    bool canBeActivated;
    bool activated;
    address permissionlessValidator;
    address transactionFilterer;
}

/// @dev storing all storage variables for ZK chain diamond facets
/// NOTE: It is used in a proxy, so it is possible to add new variables to the end
/// but NOT to modify already existing variables or change their order.
/// NOTE: variables prefixed with '__DEPRECATED_' are deprecated and shouldn't be used.
/// Their presence is maintained for compatibility and to prevent storage collision.
// solhint-disable-next-line gas-struct-packing
struct ZKChainStorage {
    /// @dev Storage of variables needed for deprecated diamond cut facet
    /// @dev STORAGE SLOT: 0-6
    uint256[7] __DEPRECATED_diamondCutStorage;
    /// @notice Address which will exercise critical changes to the Diamond Proxy (upgrades, freezing & unfreezing). Replaced by CTM
    /// @dev STORAGE SLOT: 7
    address __DEPRECATED_governor;
    /// @notice Address that the governor proposed as one that will replace it
    /// @dev STORAGE SLOT: 8
    address __DEPRECATED_pendingGovernor;
    /// @notice List of permitted validators
    /// @dev STORAGE SLOT: 9
    mapping(address validatorAddress => bool isValidator) validators;
    /// @dev Verifier contract. Used to verify aggregated proof for batches
    /// @dev STORAGE SLOT: 10
    IVerifier verifier;
    /// @notice Total number of executed batches i.e. batches[totalBatchesExecuted] points at the latest executed batch
    /// (batch 0 is genesis)
    /// @dev STORAGE SLOT: 11
    uint256 totalBatchesExecuted;
    /// @notice Total number of proved batches i.e. batches[totalBatchesProved] points at the latest proved batch
    /// @dev STORAGE SLOT: 12
    uint256 totalBatchesVerified;
    /// @notice Total number of committed batches i.e. batches[totalBatchesCommitted] points at the latest committed
    /// batch
    /// @dev STORAGE SLOT: 13
    uint256 totalBatchesCommitted;
    /// @dev Stored hashed StoredBatch for batch number
    /// @dev STORAGE SLOT: 14
    mapping(uint256 batchNumber => bytes32 batchHash) storedBatchHashes;
    /// @dev Stored root hashes of L2 -> L1 logs
    /// @dev STORAGE SLOT: 15
    mapping(uint256 batchNumber => bytes32 l2LogsRootHash) l2LogsRootHashes;
    /// @dev Container that stores transactions requested from L1
    /// @dev STORAGE SLOT: 16-18 (mapping + 2 uint256s)
    PriorityQueue.Queue __DEPRECATED_priorityQueue;
    /// @dev The smart contract that manages the list with permission to call contract functions
    /// @dev STORAGE SLOT: 19
    address __DEPRECATED_allowList;
    /// @dev STORAGE SLOT: 20-22 (3 bytes32 fields)
    VerifierParams __DEPRECATED_verifierParams;
    /// @notice Bytecode hash of bootloader program.
    /// @dev Used as an input to zkp-circuit.
    /// @dev STORAGE SLOT: 23
    bytes32 l2BootloaderBytecodeHash;
    /// @notice Bytecode hash of default account (bytecode for EOA).
    /// @dev Used as an input to zkp-circuit.
    /// @dev STORAGE SLOT: 24
    bytes32 l2DefaultAccountBytecodeHash;
    /// @dev Indicates that the porter may be touched on L2 transactions.
    /// @dev Used as an input to zkp-circuit.
    /// @dev STORAGE SLOT: 25
    bool zkPorterIsAvailable;
    /// @dev The maximum number of the L2 gas that a user can request for L1 -> L2 transactions
    /// @dev This is the maximum number of L2 gas that is available for the "body" of the transaction, i.e.
    /// without overhead for proving the batch.
    /// @dev STORAGE SLOT: 26
    uint256 priorityTxMaxGasLimit;
    /// @dev Storage of variables needed for upgrade facet
    /// @dev STORAGE SLOT: 27-28 (bytes32 + packed fields)
    UpgradeStorage __DEPRECATED_upgrades;
    /// @dev A mapping L2 batch number => message number => flag.
    /// @dev The L2 -> L1 log is sent for every withdrawal, so this mapping is serving as
    /// a flag to indicate that the message was already processed.
    /// @dev Used to indicate that eth withdrawal was already processed
    /// @dev STORAGE SLOT: 29
    mapping(uint256 l2BatchNumber => mapping(uint256 l2ToL1MessageNumber => bool isFinalized)) isEthWithdrawalFinalized;
    /// @dev The most recent withdrawal time and amount reset
    /// @dev STORAGE SLOT: 30
    uint256 __DEPRECATED_lastWithdrawalLimitReset;
    /// @dev The accumulated withdrawn amount during the withdrawal limit window
    /// @dev STORAGE SLOT: 31
    uint256 __DEPRECATED_withdrawnAmountInWindow;
    /// @dev A mapping user address => the total deposited amount by the user
    /// @dev STORAGE SLOT: 32
    mapping(address => uint256) __DEPRECATED_totalDepositedAmountPerUser;
    /// @dev Stores the protocol version. Note, that the protocol version may not only encompass changes to the
    /// smart contracts, but also to the node behavior.
    /// @dev STORAGE SLOT: 33
    uint256 protocolVersion;
    /// @dev Hash of the system contract upgrade transaction. If 0, then no upgrade transaction needs to be done.
    /// @dev STORAGE SLOT: 34
    bytes32 l2SystemContractsUpgradeTxHash;
    /// @dev Batch number where the upgrade transaction has happened. If 0, then no upgrade transaction has happened
    /// yet.
    /// @dev STORAGE SLOT: 35
    uint256 l2SystemContractsUpgradeBatchNumber;
    /// @dev Address which will exercise non-critical changes to the Diamond Proxy (changing validator set & unfreezing)
    /// @dev STORAGE SLOT: 36
    address admin;
    /// @notice Address that the admin proposed as one that will replace admin role
    /// @dev STORAGE SLOT: 37
    address pendingAdmin;
    /// @dev Fee params used to derive gasPrice for the L1->L2 transactions. For L2 transactions,
    /// the bootloader gives enough freedom to the operator.
    /// @dev The value is only for the L1 deployment of the ZK Chain, since payment for all the priority transactions is
    /// charged at that level.
    /// @dev STORAGE SLOT: 38 (packed: uint8 + 4*uint32 + uint64)
    FeeParams feeParams;
    /// @dev Address of the blob versioned hash getter smart contract used for EIP-4844 versioned hashes.
    /// @dev STORAGE SLOT: 39
    address __DEPRECATED_blobVersionedHashRetriever;
    /// @dev The chainId of the chain
    /// @dev STORAGE SLOT: 40
    uint256 chainId;
    /// @dev The address of the bridgehub
    /// @dev STORAGE SLOT: 41
    address bridgehub;
    /// @dev The address of the ChainTypeManager
    /// @dev STORAGE SLOT: 42
    address chainTypeManager;
    /// @dev The address of the baseToken contract. Eth is address(1)
    /// @dev STORAGE SLOT: 43
    address __DEPRECATED_baseToken;
    /// @dev The address of the baseTokenbridge. Eth also uses the shared bridge
    /// @dev STORAGE SLOT: 44
    address __DEPRECATED_baseTokenBridge;
    /// @notice gasPriceMultiplier for each baseToken, so that each L1->L2 transaction pays for its transaction on the destination
    /// we multiply by the nominator, and divide by the denominator
    /// @dev STORAGE SLOT: 45 (packed: 2*uint128)
    uint128 baseTokenGasPriceMultiplierNominator;
    uint128 baseTokenGasPriceMultiplierDenominator;
    /// @dev The optional address of the contract that has to be used for transaction filtering/whitelisting
    /// @dev STORAGE SLOT: 46
    address transactionFilterer;
    /// @dev The address of the l1DAValidator contract.
    /// This contract is responsible for the verification of the correctness of the DA on L1.
    /// @dev STORAGE SLOT: 47
    address l1DAValidator;
    /// @dev The address of the contract on L2 that is responsible for the data availability verification.
    /// This contract sends `l2DAValidatorOutputHash` to L1 via L2->L1 system log and it will routed to the `l1DAValidator` contract.
    /// @dev STORAGE SLOT: 48
    address __DEPRECATED_l2DAValidator;
    /// @dev the Asset Id of the baseToken
    /// @dev STORAGE SLOT: 49
    bytes32 baseTokenAssetId;
    /// @dev If this ZKchain settles on this chain, then this is zero. Otherwise it is the address of the ZKchain that is a
    /// settlement layer for this ZKchain. (think about it as a 'forwarding' address for the chain that migrated away).
    /// @dev Note, that while we cannot trust the operator of the settlement layer, it is assumed that the settlement layer
    /// belongs to the same CTM and has a trusted implementation, i.e., its implementation consists of the expected facets: Mailbox, Executor, etc.
    /// @dev STORAGE SLOT: 50
    address settlementLayer;
    /// @dev Priority tree, the new data structure for priority queue
    /// @dev STORAGE SLOT: 51-56 (2*uint256 + mapping + 3 slots for Bytes32PushTree)
    PriorityTree.Tree priorityTree;
    /// @dev Whether the chain is a permanent rollup. Note, that it only enforces the DA validator pair, but
    /// it does not enforce any other parameters, e.g. `pubdataPricingMode`
    /// @dev STORAGE SLOT: 57
    bool isPermanentRollup;
    /// @notice Bytecode hash of evm emulator.
    /// @dev Used as an input to zkp-circuit.
    /// @dev STORAGE SLOT: 58
    bytes32 l2EvmEmulatorBytecodeHash;
    /// @notice The precommitment for the latest uncommitted batch (i.e. totalBatchesCommitted + 1).
    /// @dev Whenever the `totalBatchesCommitted` changes, this variable is reset to `DEFAULT_PRECOMMITMENT_FOR_THE_LAST_BATCH`
    /// (the value of the constant can be found in Config.sol).
    /// @dev STORAGE SLOT: 59
    bytes32 precommitmentForTheLatestBatch;
    /// @dev ZKsync OS flag, if `true` state transition is done with ZKsync OS, otherwise Era VM
    /// @dev STORAGE SLOT: 60 (packed: bool + enum + address — shares with l2DACommitmentScheme + assetTracker)
    bool zksyncOS;
    /// @dev The scheme of L2 DA commitment. Different L1 validators may use different schemes.
    /// @dev STORAGE SLOT: 60 (packed with zksyncOS + assetTracker)
    L2DACommitmentScheme l2DACommitmentScheme;
    /// @dev The address of the asset tracker
    /// @dev STORAGE SLOT: 60 (packed with zksyncOS + l2DACommitmentScheme)
    address assetTracker;
    /// @dev The address of the native token vault
    /// @dev STORAGE SLOT: 61
    address nativeTokenVault;
    /// @dev Timestamp when deposits were paused for chain migration to/from Gateway. 0 = not paused.
    /// @dev STORAGE SLOT: 62
    uint256 pausedDepositsTimestamp;
    /// @dev Information required in the Priority Mode packed in one storage slot.
    /// @dev STORAGE SLOT: 63-64
    PriorityModeInformation priorityModeInfo;
    /// @dev Timestamp when a priority tx request was made for the specified tx index from priorityTree.
    /// @dev STORAGE SLOT: 65
    mapping(uint256 => uint256) priorityOpsRequestTimestamp;
    /// @dev Timestamp of the last fee params update (changeFeeParams).
    /// @dev STORAGE SLOT: 66
    uint256 lastFeeParamsUpdateTimestamp;
    /// @dev Timestamp of the last base token gas price multiplier update (setTokenMultiplier).
    /// @dev STORAGE SLOT: 67
    uint256 lastTokenMultiplierUpdateTimestamp;
    /// @dev Whether the chain has correct base token total supply tracked. It is the case for all chains,
    /// except for ZKsync OS chains that have existed before the v31 upgrade.
    /// @dev STORAGE SLOT: 68
    bool baseTokenHasTotalSupply;
}

contracts/state-transition/chain-interfaces/IGetters.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

import {VerifierParams} from "../chain-interfaces/IVerifier.sol";
import {PubdataPricingMode} from "../chain-deps/ZKChainStorage.sol";
import {IZKChainBase} from "./IZKChainBase.sol";
import {L2DACommitmentScheme} from "../../common/Config.sol";

/// @title The interface of the Getters Contract that implements functions for getting contract state from outside the blockchain.
/// @author Matter Labs
/// @custom:security-contact [email protected]
/// @dev Most of the methods simply return the values that correspond to the current diamond proxy and possibly
/// not to the ZK Chain as a whole. For example, if the chain is migrated to another settlement layer, the values returned
/// by this facet will correspond to the values stored on this chain and possilbly not the canonical state of the chain.
interface IGetters is IZKChainBase {
    /*//////////////////////////////////////////////////////////////
                            CUSTOM GETTERS
    //////////////////////////////////////////////////////////////*/

    /// @return The address of the verifier smart contract
    function getVerifier() external view returns (address);

    /// @return The address of the current admin
    function getAdmin() external view returns (address);

    /// @return The address of the pending admin
    function getPendingAdmin() external view returns (address);

    /// @return The address of the bridgehub
    function getBridgehub() external view returns (address);

    /// @return The address of the state transition
    function getChainTypeManager() external view returns (address);

    /// @return The chain ID
    function getChainId() external view returns (uint256);

    /// @return The address of the base token
    function getBaseToken() external view returns (address);

    /// @return The address of the base token
    function getBaseTokenAssetId() external view returns (bytes32);

    /// @return Whether the chain's base token exposes total supply in a trusted way.
    function baseTokenSupportsTotalSupply() external view returns (bool);

    /// @return The total number of batches that were committed
    function getTotalBatchesCommitted() external view returns (uint256);

    /// @return The total number of batches that were committed & verified
    function getTotalBatchesVerified() external view returns (uint256);

    /// @return The total number of batches that were committed & verified & executed
    function getTotalBatchesExecuted() external view returns (uint256);

    // @return Address of transaction filterer
    function getTransactionFilterer() external view returns (address);

    /// @return The total number of priority operations that were added to the priority queue, including all processed ones
    function getTotalPriorityTxs() external view returns (uint256);

    /// @return The start index of the priority tree, i.e. the index of the first priority operation that
    /// was included into the priority tree.
    function getPriorityTreeStartIndex() external view returns (uint256);

    /// @return The root hash of the priority tree
    function getPriorityTreeRoot() external view returns (bytes32);

    /// @return Whether the priority queue is active, i.e. whether new priority operations are appended to it.
    /// Once the chain processes all the transactions that were present in the priority queue, all the L1->L2 related
    /// operations will start to get done using the priority tree.
    function isPriorityQueueActive() external view returns (bool);

    /// @notice The function that returns the first unprocessed priority transaction.
    /// @dev Returns zero if and only if no operations were processed from the queue.
    /// @dev If all the transactions were processed, it will return the last processed index, so
    /// in case exactly *unprocessed* transactions are needed, one should check that getPriorityQueueSize() is greater than 0.
    /// @return Index of the oldest priority operation that wasn't processed yet
    function getFirstUnprocessedPriorityTx() external view returns (uint256);

    /// @return The number of priority operations currently in the queue
    function getPriorityQueueSize() external view returns (uint256);

    /// @return Whether the address has a validator access
    function isValidator(address _address) external view returns (bool);

    /// @return merkleRoot Merkle root of the tree with L2 logs for the selected batch
    function l2LogsRootHash(uint256 _batchNumber) external view returns (bytes32 merkleRoot);

    /// @notice For unfinalized (non executed) batches may change
    /// @dev returns zero for non-committed batches
    /// @return The hash of committed L2 batch.
    function storedBatchHash(uint256 _batchNumber) external view returns (bytes32);

    /// @return Bytecode hash of bootloader program.
    function getL2BootloaderBytecodeHash() external view returns (bytes32);

    /// @return Bytecode hash of default account (bytecode for EOA).
    function getL2DefaultAccountBytecodeHash() external view returns (bytes32);

    /// @return Bytecode hash of EVM emulator.
    function getL2EvmEmulatorBytecodeHash() external view returns (bytes32);

    /// @return Verifier parameters.
    /// @dev This function is deprecated and will soon be removed.
    function getVerifierParams() external view returns (VerifierParams memory);

    /// @return Whether the diamond is frozen or not
    function isDiamondStorageFrozen() external view returns (bool);

    /// @return The current packed protocol version. To access human-readable version, use `getSemverProtocolVersion` function.
    function getProtocolVersion() external view returns (uint256);

    /// @return The tuple of (major, minor, patch) protocol version.
    function getSemverProtocolVersion() external view returns (uint32, uint32, uint32);

    /// @return The upgrade system contract transaction hash, 0 if the upgrade is not initialized
    function getL2SystemContractsUpgradeTxHash() external view returns (bytes32);

    /// @return The L2 batch number in which the upgrade transaction was processed.
    /// @dev It is equal to 0 in the following two cases:
    /// - No upgrade transaction has ever been processed.
    /// - The upgrade transaction has been processed and the batch with such transaction has been
    /// executed (i.e. finalized).
    function getL2SystemContractsUpgradeBatchNumber() external view returns (uint256);

    /// @return The maximum number of L2 gas that a user can request for L1 -> L2 transactions
    function getPriorityTxMaxGasLimit() external view returns (uint256);

    /// @return Whether a withdrawal has been finalized.
    /// @param _l2BatchNumber The L2 batch number within which the withdrawal happened.
    /// @param _l2MessageIndex The index of the L2->L1 message denoting the withdrawal.
    function isEthWithdrawalFinalized(uint256 _l2BatchNumber, uint256 _l2MessageIndex) external view returns (bool);

    /// @return The pubdata pricing mode.
    function getPubdataPricingMode() external view returns (PubdataPricingMode);

    /// @return the baseTokenGasPriceMultiplierNominator, used to compare the baseTokenPrice to ether for L1->L2 transactions
    function baseTokenGasPriceMultiplierNominator() external view returns (uint128);

    /// @return the baseTokenGasPriceMultiplierDenominator, used to compare the baseTokenPrice to ether for L1->L2 transactions
    function baseTokenGasPriceMultiplierDenominator() external view returns (uint128);

    /*//////////////////////////////////////////////////////////////
                            DIAMOND LOUPE
    //////////////////////////////////////////////////////////////*/

    /// @notice Faсet structure compatible with the EIP-2535 diamond loupe
    /// @param addr The address of the facet contract
    /// @param selectors The NON-sorted array with selectors associated with facet
    struct Facet {
        address addr;
        bytes4[] selectors;
    }

    /// @return result All facet addresses and their function selectors
    function facets() external view returns (Facet[] memory);

    /// @return NON-sorted array with function selectors supported by a specific facet
    function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory);

    /// @return facets NON-sorted array of facet addresses supported on diamond
    function facetAddresses() external view returns (address[] memory facets);

    /// @return facet The facet address associated with a selector. Zero if the selector is not added to the diamond
    function facetAddress(bytes4 _selector) external view returns (address facet);

    /// @return Whether the selector can be frozen by the admin or always accessible
    function isFunctionFreezable(bytes4 _selector) external view returns (bool);

    /// @return isFreezable Whether the facet can be frozen by the admin or always accessible
    function isFacetFreezable(address _facet) external view returns (bool isFreezable);

    /// @return The address of the current settlement layer.
    function getSettlementLayer() external view returns (address);

    /// @return DA configuration.
    function getDAValidatorPair() external view returns (address, L2DACommitmentScheme);

    /// @return Whether the chain uses ZKsyncOS.
    function getZKsyncOS() external view returns (bool);
}

contracts/state-transition/chain-interfaces/IVerifier.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

/// @notice Part of the configuration parameters of ZKP circuits
struct VerifierParams {
    bytes32 recursionNodeLevelVkHash;
    bytes32 recursionLeafLevelVkHash;
    bytes32 recursionCircuitsSetVksHash;
}

/// @title The interface of the Verifier contract, responsible for the zero knowledge proof verification.
/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IVerifier {
    /// @dev Verifies a zk-SNARK proof.
    /// @return A boolean value indicating whether the zk-SNARK proof is valid.
    /// Note: The function may revert execution instead of returning false in some cases.
    function verify(uint256[] calldata _publicInputs, uint256[] calldata _proof) external view returns (bool);

    /// @notice Calculates a keccak256 hash of the runtime loaded verification keys.
    /// @return vkHash The keccak256 hash of the loaded verification keys.
    function verificationKeyHash() external view returns (bytes32);
}

contracts/state-transition/chain-interfaces/IZKChainBase.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

/// @title The interface of the ZKsync contract, responsible for the main ZKsync logic.
/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IZKChainBase {
    /// @return Returns facet name.
    function getName() external view returns (string memory);
}

contracts/state-transition/libraries/PriorityQueue.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

import {QueueIsEmpty} from "../../common/L1ContractErrors.sol";

/// @notice The structure that contains meta information of the L2 transaction that was requested from L1
/// @dev The weird size of fields was selected specifically to minimize the structure storage size
/// @param canonicalTxHash Hashed L2 transaction data that is needed to process it
/// @param expirationTimestamp Deprecated, always 0.
/// @param layer2Tip Additional payment to the validator as an incentive to perform the operation
struct PriorityOperation {
    bytes32 canonicalTxHash;
    uint64 expirationTimestamp;
    uint192 layer2Tip;
}

/// @author Matter Labs
/// @custom:security-contact [email protected]
/// @dev The library provides the API to interact with the priority queue container
/// @dev Order of processing operations from queue - FIFO (Fist in - first out)
library PriorityQueue {
    using PriorityQueue for Queue;

    /// @notice Container that stores priority operations
    /// @param data The inner mapping that saves priority operation by its index
    /// @param head The pointer to the first unprocessed priority operation, equal to the tail if the queue is empty
    /// @param tail The pointer to the free slot
    struct Queue {
        mapping(uint256 priorityOpId => PriorityOperation priorityOp) data;
        uint256 tail;
        uint256 head;
    }

    /// @notice Returns zero if and only if no operations were processed from the queue
    /// @return Index of the oldest priority operation that wasn't processed yet
    function getFirstUnprocessedPriorityTx(Queue storage _queue) internal view returns (uint256) {
        return _queue.head;
    }

    /// @return The total number of priority operations that were added to the priority queue, including all processed ones
    function getTotalPriorityTxs(Queue storage _queue) internal view returns (uint256) {
        return _queue.tail;
    }

    /// @return The total number of unprocessed priority operations in a priority queue
    function getSize(Queue storage _queue) internal view returns (uint256) {
        return uint256(_queue.tail - _queue.head);
    }

    /// @return Whether the priority queue contains no operations
    function isEmpty(Queue storage _queue) internal view returns (bool) {
        return _queue.tail == _queue.head;
    }

    /// @notice Add the priority operation to the end of the priority queue
    function pushBack(Queue storage _queue, PriorityOperation memory _operation) internal {
        // Save value into the stack to avoid double reading from the storage
        uint256 tail = _queue.tail;

        _queue.data[tail] = _operation;
        _queue.tail = tail + 1;
    }

    /// @return The first unprocessed priority operation from the queue
    function front(Queue storage _queue) internal view returns (PriorityOperation memory) {
        // priority queue is empty
        if (_queue.isEmpty()) {
            revert QueueIsEmpty();
        }

        return _queue.data[_queue.head];
    }

    /// @notice Remove the first unprocessed priority operation from the queue
    /// @return priorityOperation that was popped from the priority queue
    function popFront(Queue storage _queue) internal returns (PriorityOperation memory priorityOperation) {
        // priority queue is empty
        if (_queue.isEmpty()) {
            revert QueueIsEmpty();
        }

        // Save value into the stack to avoid double reading from the storage
        uint256 head = _queue.head;

        priorityOperation = _queue.data[head];
        delete _queue.data[head];
        _queue.head = head + 1;
    }
}

contracts/state-transition/libraries/PriorityTree.sol

// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the zkSync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;

import {DynamicIncrementalMerkle} from "../../common/libraries/DynamicIncrementalMerkle.sol";
import {Merkle} from "../../common/libraries/Merkle.sol";
import {PriorityTreeCommitment} from "../../common/Config.sol";
import {
    InvalidCommitment,
    InvalidNextLeafIndex,
    InvalidStartIndex,
    InvalidUnprocessedIndex,
    NotHistoricalRoot
} from "../L1StateTransitionErrors.sol";

struct PriorityOpsBatchInfo {
    bytes32[] leftPath;
    bytes32[] rightPath;
    bytes32[] itemHashes;
}

bytes32 constant ZERO_LEAF_HASH = keccak256("");

library PriorityTree {
    using PriorityTree for Tree;
    using DynamicIncrementalMerkle for DynamicIncrementalMerkle.Bytes32PushTree;

    struct Tree {
        uint256 startIndex; // priority tree started accepting priority ops from this index
        uint256 unprocessedIndex; // relative to `startIndex`
        mapping(bytes32 => bool) historicalRoots;
        DynamicIncrementalMerkle.Bytes32PushTree tree;
    }

    /// @notice Returns zero if and only if no operations were processed from the tree
    /// @return Index of the oldest priority operation that wasn't processed yet
    function getFirstUnprocessedPriorityTx(Tree storage _tree) internal view returns (uint256) {
        return _tree.startIndex + _tree.unprocessedIndex;
    }

    /// @return The total number of priority operations that were added to the priority queue, including all processed ones
    function getTotalPriorityTxs(Tree storage _tree) internal view returns (uint256) {
        return _tree.startIndex + _tree.tree._nextLeafIndex;
    }

    /// @return The total number of unprocessed priority operations in a priority queue
    function getSize(Tree storage _tree) internal view returns (uint256) {
        return _tree.tree._nextLeafIndex - _tree.unprocessedIndex;
    }

    /// @notice Add the priority operation to the end of the priority queue
    function push(Tree storage _tree, bytes32 _hash) internal {
        // slither-disable-next-line unused-return
        (, bytes32 newRoot) = _tree.tree.push(_hash);
        _tree.historicalRoots[newRoot] = true;
    }

    /// @notice Set up the tree
    function setup(Tree storage _tree, uint256 _startIndex) internal {
        bytes32 initialRoot = _tree.tree.setup(ZERO_LEAF_HASH);
        _tree.historicalRoots[initialRoot] = true;
        _tree.startIndex = _startIndex;
    }

    /// @return Returns the tree root.
    function getRoot(Tree storage _tree) internal view returns (bytes32) {
        return _tree.tree.root();
    }

    /// @param _root The root to check.
    /// @return Returns true if the root is a historical root.
    function isHistoricalRoot(Tree storage _tree, bytes32 _root) internal view returns (bool) {
        return _tree.historicalRoots[_root];
    }

    /// @notice Process the priority operations of a batch.
    /// @dev Note, that the function below only checks that a certain segment of items is present in the tree.
    /// It does not check that e.g. there are no zero items inside the provided `itemHashes`, so in theory proofs
    /// that include non-existing priority operations could be created. This function relies on the fact
    /// that the `itemHashes` of `_priorityOpsData` are hashes of valid priority transactions.
    /// This fact is ensured by the fact the rolling hash of those is sent to the Executor by the bootloader
    /// and so assuming that zero knowledge proofs are correct, so is the structure of the `itemHashes`.
    function processBatch(Tree storage _tree, PriorityOpsBatchInfo memory _priorityOpsData) internal {
        if (_priorityOpsData.itemHashes.length > 0) {
            bytes32 expectedRoot = Merkle.calculateRootPaths(
                _priorityOpsData.leftPath,
                _priorityOpsData.rightPath,
                _tree.unprocessedIndex,
                _priorityOpsData.itemHashes
            );
            if (!_tree.historicalRoots[expectedRoot]) {
                revert NotHistoricalRoot(expectedRoot);
            }
            _tree.unprocessedIndex += _priorityOpsData.itemHashes.length;
        }
    }

    /// @notice Allows to skip a certain number of operations.
    /// @param _lastUnprocessed The new expected id of the unprocessed transaction.
    /// @dev It is used when the corresponding transactions have been processed by priority queue.
    function skipUntil(Tree storage _tree, uint256 _lastUnprocessed) internal {
        if (_tree.startIndex > _lastUnprocessed) {
            // Nothing to do, return
            return;
        }
        uint256 newUnprocessedIndex = _lastUnprocessed - _tree.startIndex;
        if (newUnprocessedIndex <= _tree.unprocessedIndex) {
            // These transactions were already processed, skip.
            return;
        }

        _tree.unprocessedIndex = newUnprocessedIndex;
    }

    /// @notice Initialize a chain from a commitment.
    function initFromCommitment(Tree storage _tree, PriorityTreeCommitment memory _commitment) internal {
        uint256 height = _commitment.sides.length; // Height, including the root node.
        if (height == 0) {
            revert InvalidCommitment();
        }
        _tree.startIndex = _commitment.startIndex;
        _tree.unprocessedIndex = _commitment.unprocessedIndex;
        _tree.tree._nextLeafIndex = _commitment.nextLeafIndex;
        _tree.tree._sides = _commitment.sides;
        bytes32 zero = ZERO_LEAF_HASH;
        _tree.tree._zeros = new bytes32[](height);
        for (uint256 i; i < height; ++i) {
            _tree.tree._zeros[i] = zero;
            zero = Merkle.efficientHash(zero, zero);
        }
        _tree.historicalRoots[_tree.tree.root()] = true;
    }

    /// @notice Reinitialize the tree from a commitment on L1.
    function l1Reinit(Tree storage _tree, PriorityTreeCommitment memory _commitment) internal {
        if (_tree.startIndex != _commitment.startIndex) {
            revert InvalidStartIndex(_tree.startIndex, _commitment.startIndex);
        }
        if (_tree.unprocessedIndex > _commitment.unprocessedIndex) {
            revert InvalidUnprocessedIndex(_tree.unprocessedIndex, _commitment.unprocessedIndex);
        }
        if (_tree.tree._nextLeafIndex < _commitment.nextLeafIndex) {
            revert InvalidNextLeafIndex(_tree.tree._nextLeafIndex, _commitment.nextLeafIndex);
        }

        _tree.unprocessedIndex = _commitment.unprocessedIndex;
    }

    /// @notice Reinitialize the tree from a commitment on GW.
    function checkGWReinit(Tree storage _tree, PriorityTreeCommitment memory _commitment) internal view {
        if (_tree.startIndex != _commitment.startIndex) {
            revert InvalidStartIndex(_tree.startIndex, _commitment.startIndex);
        }
        if (_tree.unprocessedIndex > _commitment.unprocessedIndex) {
            revert InvalidUnprocessedIndex(_tree.unprocessedIndex, _commitment.unprocessedIndex);
        }
        if (_tree.tree._nextLeafIndex > _commitment.nextLeafIndex) {
            revert InvalidNextLeafIndex(_tree.tree._nextLeafIndex, _commitment.nextLeafIndex);
        }
    }

    /// @notice Returns the commitment to the priority tree.
    function getCommitment(Tree storage _tree) internal view returns (PriorityTreeCommitment memory commitment) {
        commitment.nextLeafIndex = _tree.tree._nextLeafIndex;
        commitment.startIndex = _tree.startIndex;
        commitment.unprocessedIndex = _tree.unprocessedIndex;
        commitment.sides = _tree.tree._sides;
    }
}

lib/openzeppelin-contracts-v4/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/Address.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

lib/openzeppelin-contracts-v4/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

lib/openzeppelin-contracts-v4/contracts/utils/Arrays.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Arrays.sol)

pragma solidity ^0.8.0;

import "./StorageSlot.sol";
import "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using StorageSlot for bytes32;

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * `array` is expected to be sorted in ascending order, and to contain no
     * repeated elements.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        if (array.length == 0) {
            return 0;
        }

        uint256 low = 0;
        uint256 high = array.length;

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds down (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
        // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays.

        /// @solidity memory-safe-assembly
        assembly {
            mstore(0, arr.slot)
            slot := add(keccak256(0, 0x20), pos)
        }
        return slot.getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
        // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays.

        /// @solidity memory-safe-assembly
        assembly {
            mstore(0, arr.slot)
            slot := add(keccak256(0, 0x20), pos)
        }
        return slot.getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
        // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays.

        /// @solidity memory-safe-assembly
        assembly {
            mstore(0, arr.slot)
            slot := add(keccak256(0, 0x20), pos)
        }
        return slot.getUint256Slot();
    }
}

lib/openzeppelin-contracts-v4/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts-v4/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 9999999,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@ensdomains/=node_modules/@ensdomains/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "eth-gas-reporter/=node_modules/eth-gas-reporter/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=node_modules/hardhat/",
    "murky/=lib/murky/src/",
    "foundry-test/=test/foundry/",
    "l2-contracts/=../l2-contracts/contracts/",
    "system-contracts/=../system-contracts/",
    "@openzeppelin/contracts-v4/=lib/openzeppelin-contracts-v4/contracts/",
    "@openzeppelin/contracts-upgradeable-v4/=lib/openzeppelin-contracts-upgradeable-v4/contracts/",
    "test-utils/=test/foundry/l1/integration/utils/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable-v4/lib/erc4626-tests/",
    "openzeppelin-contracts-upgradeable-v4/=lib/openzeppelin-contracts-upgradeable-v4/",
    "openzeppelin-contracts-v4/=lib/openzeppelin-contracts-v4/",
    "openzeppelin-contracts/=lib/murky/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.