{
  "language": "Solidity",
  "sources": {
    "contracts/optimistic-ethereum/iOVM/bridge/messaging/iOVM_CrossDomainMessenger.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/**\n * @title iOVM_CrossDomainMessenger\n */\ninterface iOVM_CrossDomainMessenger {\n\n    /**********\n     * Events *\n     **********/\n\n    event SentMessage(bytes message);\n    event RelayedMessage(bytes32 msgHash);\n    event FailedRelayedMessage(bytes32 msgHash);\n\n\n    /*************\n     * Variables *\n     *************/\n\n    function xDomainMessageSender() external view returns (address);\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Sends a cross domain message to the target messenger.\n     * @param _target Target contract address.\n     * @param _message Message to send to the target.\n     * @param _gasLimit Gas limit for the provided message.\n     */\n    function sendMessage(\n        address _target,\n        bytes calldata _message,\n        uint32 _gasLimit\n    ) external;\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/bridge/OVM_CrossDomainEnabled.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Interface Imports */\nimport { iOVM_CrossDomainMessenger } from \"../../iOVM/bridge/messaging/iOVM_CrossDomainMessenger.sol\";\n\n/**\n * @title OVM_CrossDomainEnabled\n * @dev Helper contract for contracts performing cross-domain communications\n *\n * Compiler used: defined by inheriting contract\n * Runtime target: defined by inheriting contract\n */\ncontract OVM_CrossDomainEnabled {\n\n    /*************\n     * Variables *\n     *************/\n\n    // Messenger contract used to send and recieve messages from the other domain.\n    address public messenger;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _messenger Address of the CrossDomainMessenger on the current layer.\n     */\n    constructor(\n        address _messenger\n    ) {\n        messenger = _messenger;\n    }\n\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    /**\n     * Enforces that the modified function is only callable by a specific cross-domain account.\n     * @param _sourceDomainAccount The only account on the originating domain which is\n     *  authenticated to call this function.\n     */\n    modifier onlyFromCrossDomainAccount(\n        address _sourceDomainAccount\n    ) {\n        require(\n            msg.sender == address(getCrossDomainMessenger()),\n            \"OVM_XCHAIN: messenger contract unauthenticated\"\n        );\n\n        require(\n            getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount,\n            \"OVM_XCHAIN: wrong sender of cross-domain message\"\n        );\n\n        _;\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Gets the messenger, usually from storage. This function is exposed in case a child contract\n     * needs to override.\n     * @return The address of the cross-domain messenger contract which should be used.\n     */\n    function getCrossDomainMessenger()\n        internal\n        virtual\n        returns (\n            iOVM_CrossDomainMessenger\n        )\n    {\n        return iOVM_CrossDomainMessenger(messenger);\n    }\n\n    /**\n     * Sends a message to an account on another domain\n     * @param _crossDomainTarget The intended recipient on the destination domain\n     * @param _message The data to send to the target (usually calldata to a function with\n     *  `onlyFromCrossDomainAccount()`)\n     * @param _gasLimit The gasLimit for the receipt of the message on the target domain.\n     */\n    function sendCrossDomainMessage(\n        address _crossDomainTarget,\n        uint32 _gasLimit,\n        bytes memory _message\n    )\n        internal\n    {\n        getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L2StandardBridge.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Interface Imports */\nimport { iOVM_L1StandardBridge } from \"../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol\";\nimport { iOVM_L1ERC20Bridge } from \"../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol\";\nimport { iOVM_L2ERC20Bridge } from \"../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol\";\n\n/* Library Imports */\nimport { ERC165Checker } from \"@openzeppelin/contracts/introspection/ERC165Checker.sol\";\nimport { OVM_CrossDomainEnabled } from \"../../../libraries/bridge/OVM_CrossDomainEnabled.sol\";\nimport { Lib_PredeployAddresses } from \"../../../libraries/constants/Lib_PredeployAddresses.sol\";\n\n/* Contract Imports */\nimport { IL2StandardERC20 } from \"../../../libraries/standards/IL2StandardERC20.sol\";\n\n/**\n * @title OVM_L2StandardBridge\n * @dev The L2 Standard bridge is a contract which works together with the L1 Standard bridge to enable\n * ETH and ERC20 transitions between L1 and L2.\n * This contract acts as a minter for new tokens when it hears about deposits into the L1 Standard bridge.\n * This contract also acts as a burner of the tokens intended for withdrawal, informing the L1 bridge to release L1 funds.\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_L2StandardBridge is iOVM_L2ERC20Bridge, OVM_CrossDomainEnabled {\n\n    /********************************\n     * External Contract References *\n     ********************************/\n\n    address public l1TokenBridge;\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _l2CrossDomainMessenger Cross-domain messenger used by this contract.\n     * @param _l1TokenBridge Address of the L1 bridge deployed to the main chain.\n     */\n    constructor(\n        address _l2CrossDomainMessenger,\n        address _l1TokenBridge\n    )\n        OVM_CrossDomainEnabled(_l2CrossDomainMessenger)\n    {\n        l1TokenBridge = _l1TokenBridge;\n    }\n\n    /***************\n     * Withdrawing *\n     ***************/\n\n    /**\n     * @inheritdoc iOVM_L2ERC20Bridge\n     */\n    function withdraw(\n        address _l2Token,\n        uint256 _amount,\n        uint32 _l1Gas,\n        bytes calldata _data\n    )\n        external\n        override\n        virtual\n    {\n        _initiateWithdrawal(\n            _l2Token,\n            msg.sender,\n            msg.sender,\n            _amount,\n            _l1Gas,\n            _data\n        );\n    }\n\n    /**\n     * @inheritdoc iOVM_L2ERC20Bridge\n     */\n    function withdrawTo(\n        address _l2Token,\n        address _to,\n        uint256 _amount,\n        uint32 _l1Gas,\n        bytes calldata _data\n    )\n        external\n        override\n        virtual\n    {\n        _initiateWithdrawal(\n            _l2Token,\n            msg.sender,\n            _to,\n            _amount,\n            _l1Gas,\n            _data\n        );\n    }\n\n    /**\n     * @dev Performs the logic for deposits by storing the token and informing the L2 token Gateway of the deposit.\n     * @param _l2Token Address of L2 token where withdrawal was initiated.\n     * @param _from Account to pull the deposit from on L2.\n     * @param _to Account to give the withdrawal to on L1.\n     * @param _amount Amount of the token to withdraw.\n     * param _l1Gas Unused, but included for potential forward compatibility considerations.\n     * @param _data Optional data to forward to L1. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function _initiateWithdrawal(\n        address _l2Token,\n        address _from,\n        address _to,\n        uint256 _amount,\n        uint32 _l1Gas,\n        bytes calldata _data\n    )\n        internal\n    {\n        // When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 usage\n        IL2StandardERC20(_l2Token).burn(msg.sender, _amount);\n\n        // Construct calldata for l1TokenBridge.finalizeERC20Withdrawal(_to, _amount)\n        address l1Token = IL2StandardERC20(_l2Token).l1Token();\n        bytes memory message;\n\n        if (_l2Token == Lib_PredeployAddresses.OVM_ETH) {\n            message = abi.encodeWithSelector(\n                        iOVM_L1StandardBridge.finalizeETHWithdrawal.selector,\n                        _from,\n                        _to,\n                        _amount,\n                        _data\n                    );\n        } else {\n            message = abi.encodeWithSelector(\n                        iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector,\n                        l1Token,\n                        _l2Token,\n                        _from,\n                        _to,\n                        _amount,\n                        _data\n                    );\n        }\n\n        // Send message up to L1 bridge\n        sendCrossDomainMessage(\n            l1TokenBridge,\n            _l1Gas,\n            message\n        );\n\n        emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data);\n    }\n\n    /************************************\n     * Cross-chain Function: Depositing *\n     ************************************/\n\n    /**\n     * @inheritdoc iOVM_L2ERC20Bridge\n     */\n    function finalizeDeposit(\n        address _l1Token,\n        address _l2Token,\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _data\n    )\n        external\n        override\n        virtual\n        onlyFromCrossDomainAccount(l1TokenBridge)\n    {\n        // Check the target token is compliant and\n        // verify the deposited token on L1 matches the L2 deposited token representation here\n        if (\n            ERC165Checker.supportsInterface(_l2Token, 0x1d1d8b63) &&\n            _l1Token == IL2StandardERC20(_l2Token).l1Token()\n        ) {\n            // When a deposit is finalized, we credit the account on L2 with the same amount of tokens.\n            IL2StandardERC20(_l2Token).mint(_to, _amount);\n            emit DepositFinalized(_l1Token, _l2Token, _from, _to, _amount, _data);\n        } else {\n            // Either the L2 token which is being deposited-into disagrees about the correct address\n            // of its L1 token, or does not support the correct interface.\n            // This should only happen if there is a  malicious L2 token, or if a user somehow\n            // specified the wrong L2 token address to deposit into.\n            // In either case, we stop the process here and construct a withdrawal\n            // message so that users can get their funds out in some cases.\n            // There is no way to prevent malicious token contracts altogether, but this does limit\n            // user error and mitigate some forms of malicious contract behavior.\n            bytes memory message = abi.encodeWithSelector(\n                iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector,\n                _l1Token,\n                _l2Token,\n                _to,   // switched the _to and _from here to bounce back the deposit to the sender\n                _from,\n                _amount,\n                _data\n            );\n\n            // Send message up to L1 bridge\n            sendCrossDomainMessage(\n                l1TokenBridge,\n                0,\n                message\n            );\n            emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data);\n        }\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/bridge/tokens/iOVM_L1StandardBridge.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0;\npragma experimental ABIEncoderV2;\n\nimport './iOVM_L1ERC20Bridge.sol';\n\n/**\n * @title iOVM_L1StandardBridge\n */\ninterface iOVM_L1StandardBridge is iOVM_L1ERC20Bridge {\n\n    /**********\n     * Events *\n     **********/\n    event ETHDepositInitiated (\n        address indexed _from,\n        address indexed _to,\n        uint256 _amount,\n        bytes _data\n    );\n\n    event ETHWithdrawalFinalized (\n        address indexed _from,\n        address indexed _to,\n        uint256 _amount,\n        bytes _data\n    );\n\n    /********************\n     * Public Functions *\n     ********************/\n     \n    /**\n     * @dev Deposit an amount of the ETH to the caller's balance on L2.\n     * @param _l2Gas Gas limit required to complete the deposit on L2.\n     * @param _data Optional data to forward to L2. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function depositETH (\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external\n        payable;\n\n    /**\n     * @dev Deposit an amount of ETH to a recipient's balance on L2.\n     * @param _to L2 address to credit the withdrawal to.\n     * @param _l2Gas Gas limit required to complete the deposit on L2.\n     * @param _data Optional data to forward to L2. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function depositETHTo (\n        address _to,\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external\n        payable;\n\n    /*************************\n     * Cross-chain Functions *\n     *************************/\n\n    /**\n     * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the\n     * L1 ETH token.\n     * Since only the xDomainMessenger can call this function, it will never be called before the withdrawal is finalized.\n     * @param _from L2 address initiating the transfer.\n     * @param _to L1 address to credit the withdrawal to.\n     * @param _amount Amount of the ERC20 to deposit.\n     * @param _data Optional data to forward to L2. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function finalizeETHWithdrawal (\n        address _from,\n        address _to,\n        uint _amount,\n        bytes calldata _data\n    )\n        external;\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0;\npragma experimental ABIEncoderV2;\n\n/**\n * @title iOVM_L1ERC20Bridge\n */\ninterface iOVM_L1ERC20Bridge {\n\n    /**********\n     * Events *\n     **********/\n\n    event ERC20DepositInitiated (\n        address indexed _l1Token,\n        address indexed _l2Token,\n        address indexed _from,\n        address _to,\n        uint256 _amount,\n        bytes _data\n    );\n\n    event ERC20WithdrawalFinalized (\n        address indexed _l1Token,\n        address indexed _l2Token,\n        address indexed _from,\n        address _to,\n        uint256 _amount,\n        bytes _data\n    );\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * @dev deposit an amount of the ERC20 to the caller's balance on L2.\n     * @param _l1Token Address of the L1 ERC20 we are depositing\n     * @param _l2Token Address of the L1 respective L2 ERC20\n     * @param _amount Amount of the ERC20 to deposit\n     * @param _l2Gas Gas limit required to complete the deposit on L2.\n     * @param _data Optional data to forward to L2. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function depositERC20 (\n        address _l1Token,\n        address _l2Token,\n        uint _amount,\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external;\n\n    /**\n     * @dev deposit an amount of ERC20 to a recipient's balance on L2.\n     * @param _l1Token Address of the L1 ERC20 we are depositing\n     * @param _l2Token Address of the L1 respective L2 ERC20\n     * @param _to L2 address to credit the withdrawal to.\n     * @param _amount Amount of the ERC20 to deposit.\n     * @param _l2Gas Gas limit required to complete the deposit on L2.\n     * @param _data Optional data to forward to L2. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function depositERC20To (\n        address _l1Token,\n        address _l2Token,\n        address _to,\n        uint _amount,\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external;\n\n\n    /*************************\n     * Cross-chain Functions *\n     *************************/\n\n    /**\n     * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the\n     * L1 ERC20 token.\n     * This call will fail if the initialized withdrawal from L2 has not been finalized.\n     *\n     * @param _l1Token Address of L1 token to finalizeWithdrawal for.\n     * @param _l2Token Address of L2 token where withdrawal was initiated.\n     * @param _from L2 address initiating the transfer.\n     * @param _to L1 address to credit the withdrawal to.\n     * @param _amount Amount of the ERC20 to deposit.\n     * @param _data Data provided by the sender on L2. This data is provided\n     *   solely as a convenience for external contracts. Aside from enforcing a maximum\n     *   length, these contracts provide no guarantees about its content.\n     */\n    function finalizeERC20Withdrawal (\n        address _l1Token,\n        address _l2Token,\n        address _from,\n        address _to,\n        uint _amount,\n        bytes calldata _data\n    )\n        external;\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0;\npragma experimental ABIEncoderV2;\n\n/**\n * @title iOVM_L2ERC20Bridge\n */\ninterface iOVM_L2ERC20Bridge {\n\n    /**********\n     * Events *\n     **********/\n\n    event WithdrawalInitiated (\n        address indexed _l1Token,\n        address indexed _l2Token,\n        address indexed _from,\n        address _to,\n        uint256 _amount,\n        bytes _data\n    );\n\n    event DepositFinalized (\n        address indexed _l1Token,\n        address indexed _l2Token,\n        address indexed _from,\n        address _to,\n        uint256 _amount,\n        bytes _data\n    );\n\n    event DepositFailed (\n        address indexed _l1Token,\n        address indexed _l2Token,\n        address indexed _from,\n        address _to,\n        uint256 _amount,\n        bytes _data\n    );\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * @dev initiate a withdraw of some tokens to the caller's account on L1\n     * @param _l2Token Address of L2 token where withdrawal was initiated.\n     * @param _amount Amount of the token to withdraw.\n     * param _l1Gas Unused, but included for potential forward compatibility considerations.\n     * @param _data Optional data to forward to L1. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function withdraw (\n        address _l2Token,\n        uint _amount,\n        uint32 _l1Gas,\n        bytes calldata _data\n    )\n        external;\n\n    /**\n     * @dev initiate a withdraw of some token to a recipient's account on L1.\n     * @param _l2Token Address of L2 token where withdrawal is initiated.\n     * @param _to L1 adress to credit the withdrawal to.\n     * @param _amount Amount of the token to withdraw.\n     * param _l1Gas Unused, but included for potential forward compatibility considerations.\n     * @param _data Optional data to forward to L1. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function withdrawTo (\n        address _l2Token,\n        address _to,\n        uint _amount,\n        uint32 _l1Gas,\n        bytes calldata _data\n    )\n        external;\n\n    /*************************\n     * Cross-chain Functions *\n     *************************/\n\n    /**\n     * @dev Complete a deposit from L1 to L2, and credits funds to the recipient's balance of this\n     * L2 token.\n     * This call will fail if it did not originate from a corresponding deposit in OVM_l1TokenGateway.\n     * @param _l1Token Address for the l1 token this is called with\n     * @param _l2Token Address for the l2 token this is called with\n     * @param _from Account to pull the deposit from on L2.\n     * @param _to Address to receive the withdrawal at\n     * @param _amount Amount of the token to withdraw\n     * @param _data Data provider by the sender on L1. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function finalizeDeposit (\n        address _l1Token,\n        address _l2Token,\n        address _from,\n        address _to,\n        uint _amount,\n        bytes calldata _data\n    )\n        external;\n\n}\n"
    },
    "@openzeppelin/contracts/introspection/ERC165Checker.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Library used to query support of an interface declared via {IERC165}.\n *\n * Note that these functions return the actual result of the query: they do not\n * `revert` if an interface is not supported. It is up to the caller to decide\n * what to do in these cases.\n */\nlibrary ERC165Checker {\n    // As per the EIP-165 spec, no interface should ever match 0xffffffff\n    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;\n\n    /*\n     * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7\n     */\n    bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;\n\n    /**\n     * @dev Returns true if `account` supports the {IERC165} interface,\n     */\n    function supportsERC165(address account) internal view returns (bool) {\n        // Any contract that implements ERC165 must explicitly indicate support of\n        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid\n        return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&\n            !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);\n    }\n\n    /**\n     * @dev Returns true if `account` supports the interface defined by\n     * `interfaceId`. Support for {IERC165} itself is queried automatically.\n     *\n     * See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {\n        // query support of both ERC165 as per the spec and support of _interfaceId\n        return supportsERC165(account) &&\n            _supportsERC165Interface(account, interfaceId);\n    }\n\n    /**\n     * @dev Returns a boolean array where each value corresponds to the\n     * interfaces passed in and whether they're supported or not. This allows\n     * you to batch check interfaces for a contract where your expectation\n     * is that some interfaces may not be supported.\n     *\n     * See {IERC165-supportsInterface}.\n     *\n     * _Available since v3.4._\n     */\n    function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {\n        // an array of booleans corresponding to interfaceIds and whether they're supported or not\n        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);\n\n        // query support of ERC165 itself\n        if (supportsERC165(account)) {\n            // query support of each interface in interfaceIds\n            for (uint256 i = 0; i < interfaceIds.length; i++) {\n                interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);\n            }\n        }\n\n        return interfaceIdsSupported;\n    }\n\n    /**\n     * @dev Returns true if `account` supports all the interfaces defined in\n     * `interfaceIds`. Support for {IERC165} itself is queried automatically.\n     *\n     * Batch-querying can lead to gas savings by skipping repeated checks for\n     * {IERC165} support.\n     *\n     * See {IERC165-supportsInterface}.\n     */\n    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {\n        // query support of ERC165 itself\n        if (!supportsERC165(account)) {\n            return false;\n        }\n\n        // query support of each interface in _interfaceIds\n        for (uint256 i = 0; i < interfaceIds.length; i++) {\n            if (!_supportsERC165Interface(account, interfaceIds[i])) {\n                return false;\n            }\n        }\n\n        // all interfaces supported\n        return true;\n    }\n\n    /**\n     * @notice Query if a contract implements an interface, does not check ERC165 support\n     * @param account The address of the contract to query for support of an interface\n     * @param interfaceId The interface identifier, as specified in ERC-165\n     * @return true if the contract at account indicates support of the interface with\n     * identifier interfaceId, false otherwise\n     * @dev Assumes that account contains a contract that supports ERC165, otherwise\n     * the behavior of this method is undefined. This precondition can be checked\n     * with {supportsERC165}.\n     * Interface identification is specified in ERC-165.\n     */\n    function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {\n        // success determines whether the staticcall succeeded and result determines\n        // whether the contract at account indicates support of _interfaceId\n        (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);\n\n        return (success && result);\n    }\n\n    /**\n     * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw\n     * @param account The address of the contract to query for support of an interface\n     * @param interfaceId The interface identifier, as specified in ERC-165\n     * @return success true if the STATICCALL succeeded, false otherwise\n     * @return result true if the STATICCALL succeeded and the contract at account\n     * indicates support of the interface with identifier interfaceId, false otherwise\n     */\n    function _callERC165SupportsInterface(address account, bytes4 interfaceId)\n        private\n        view\n        returns (bool, bool)\n    {\n        bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);\n        (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);\n        if (result.length < 32) return (false, false);\n        return (success, abi.decode(result, (bool)));\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/constants/Lib_PredeployAddresses.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title Lib_PredeployAddresses\n */\nlibrary Lib_PredeployAddresses {\n    address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000;\n    address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001;\n    address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002;\n    address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003;\n    address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005;\n    address payable internal constant OVM_ETH = 0x4200000000000000000000000000000000000006;\n    address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007;\n    address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008;\n    address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009;\n    address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B;\n    address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;\n    address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24;\n    address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/standards/IL2StandardERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.16 <0.8.0;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { IERC165 } from \"@openzeppelin/contracts/introspection/IERC165.sol\";\n\ninterface IL2StandardERC20 is IERC20, IERC165 {\n    function l1Token() external returns (address);\n\n    function mint(address _to, uint256 _amount) external;\n\n    function burn(address _from, uint256 _amount) external;\n\n    event Mint(address indexed _account, uint256 _amount);\n    event Burn(address indexed _account, uint256 _amount);\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
    },
    "@openzeppelin/contracts/introspection/IERC165.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_SequencerFeeVault.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_PredeployAddresses } from \"../../libraries/constants/Lib_PredeployAddresses.sol\";\n\n/* Contract Imports */\nimport { OVM_ETH } from \"../predeploys/OVM_ETH.sol\";\nimport { OVM_L2StandardBridge } from \"../bridge/tokens/OVM_L2StandardBridge.sol\";\n\n/**\n * @title OVM_SequencerFeeVault\n * @dev Simple holding contract for fees paid to the Sequencer. Likely to be replaced in the future\n * but \"good enough for now\".\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_SequencerFeeVault {\n\n    /*************\n     * Constants *\n     *************/\n\n    // Minimum ETH balance that can be withdrawn in a single withdrawal.\n    uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether;\n\n\n    /*************\n     * Variables *\n     *************/\n\n    // Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth.\n    address public l1FeeWallet;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _l1FeeWallet Initial address for the L1 wallet that will hold fees once withdrawn.\n     * Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during\n     * the genesis block. This is ONLY for testing purposes.\n     */\n    constructor(\n        address _l1FeeWallet\n    ) {\n        l1FeeWallet = _l1FeeWallet;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function withdraw()\n        public\n    {\n        uint256 balance = OVM_ETH(Lib_PredeployAddresses.OVM_ETH).balanceOf(address(this));\n\n        require(\n            balance >= MIN_WITHDRAWAL_AMOUNT,\n            \"OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount\"\n        );\n\n        OVM_L2StandardBridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo(\n            Lib_PredeployAddresses.OVM_ETH,\n            l1FeeWallet,\n            balance,\n            0,\n            bytes(\"\")\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_ETH.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_PredeployAddresses } from \"../../libraries/constants/Lib_PredeployAddresses.sol\";\n\n/* Contract Imports */\nimport { L2StandardERC20 } from \"../../libraries/standards/L2StandardERC20.sol\";\nimport { IWETH9 } from \"../../libraries/standards/IWETH9.sol\";\n\n/**\n * @title OVM_ETH\n * @dev The ETH predeploy provides an ERC20 interface for ETH deposited to Layer 2. Note that\n * unlike on Layer 1, Layer 2 accounts do not have a balance field.\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_ETH is L2StandardERC20, IWETH9 {\n\n    /***************\n     * Constructor *\n     ***************/\n\n    constructor()\n        L2StandardERC20(\n            Lib_PredeployAddresses.L2_STANDARD_BRIDGE,\n            address(0),\n            \"Ether\",\n            \"ETH\"\n        )\n    {}\n\n\n    /******************************\n     * Custom WETH9 Functionality *\n     ******************************/\n    fallback() external payable {\n        deposit();\n    }\n\n    /**\n     * Implements the WETH9 deposit() function as a no-op.\n     * WARNING: this function does NOT have to do with cross-chain asset bridging. The\n     * relevant deposit and withdraw functions for that use case can be found at L2StandardBridge.sol.\n     * This function allows developers to treat OVM_ETH as WETH without any modifications to their code.\n     */\n    function deposit()\n        public\n        payable\n        override\n    {\n        // Calling deposit() with nonzero value will send the ETH to this contract address.  Once recieved here,\n        // We transfer it back by sending to the msg.sender.\n        _transfer(address(this), msg.sender, msg.value);\n\n        emit Deposit(msg.sender, msg.value);\n    }\n\n    /**\n     * Implements the WETH9 withdraw() function as a no-op.\n     * WARNING: this function does NOT have to do with cross-chain asset bridging. The\n     * relevant deposit and withdraw functions for that use case can be found at L2StandardBridge.sol.\n     * This function allows developers to treat OVM_ETH as WETH without any modifications to their code.\n     * @param _wad Amount being withdrawn\n     */\n    function withdraw(\n        uint256 _wad\n    )\n        external\n        override\n    {\n        // Calling withdraw() with value exceeding the withdrawer's ovmBALANCE should revert, as in WETH9.\n        require(balanceOf(msg.sender) >= _wad);\n\n        // Other than emitting an event, OVM_ETH already is native ETH, so we don't need to do anything else.\n        emit Withdrawal(msg.sender, _wad);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/standards/L2StandardERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.16 <0.8.0;\n\nimport { ERC20 } from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\nimport './IL2StandardERC20.sol';\n\ncontract L2StandardERC20 is IL2StandardERC20, ERC20 {\n    address public override l1Token;\n    address public l2Bridge;\n\n    /**\n     * @param _l1Token Address of the corresponding L1 token.\n     * @param _name ERC20 name.\n     * @param _symbol ERC20 symbol.\n     */\n    constructor(\n        address _l2Bridge,\n        address _l1Token,\n        string memory _name,\n        string memory _symbol\n    )\n        ERC20(_name, _symbol) {\n        l1Token = _l1Token;\n        l2Bridge = _l2Bridge;\n    }\n\n    modifier onlyL2Bridge {\n        require(msg.sender == l2Bridge, \"Only L2 Bridge can mint and burn\");\n        _;\n    }\n\n    function supportsInterface(bytes4 _interfaceId) public override pure returns (bool) {\n        bytes4 firstSupportedInterface = bytes4(keccak256(\"supportsInterface(bytes4)\")); // ERC165\n        bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector\n            ^ IL2StandardERC20.mint.selector\n            ^ IL2StandardERC20.burn.selector;\n        return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface;\n    }\n\n    function mint(address _to, uint256 _amount) public override onlyL2Bridge {\n        _mint(_to, _amount);\n\n        emit Mint(_to, _amount);\n    }\n\n    function burn(address _from, uint256 _amount) public override onlyL2Bridge {\n        _burn(_from, _amount);\n\n        emit Burn(_from, _amount);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/standards/IWETH9.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity =0.7.6;\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title Interface for WETH9. Also contains the non-ERC20 events normally present in the WETH9 implementation.\ninterface IWETH9 is IERC20 {\n    event Deposit(address indexed dst, uint256 wad);\n    event Withdrawal(address indexed src, uint256 wad);\n\n    /// @notice Deposit ether to get wrapped ether\n    function deposit() external payable;\n\n    /// @notice Withdraw wrapped ether to get ether\n    function withdraw(uint256) external;\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/ERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../../utils/Context.sol\";\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n    using SafeMath for uint256;\n\n    mapping (address => uint256) private _balances;\n\n    mapping (address => mapping (address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n    uint8 private _decimals;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n     * a default value of 18.\n     *\n     * To select a different value for {decimals}, use {_setupDecimals}.\n     *\n     * All three of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor (string memory name_, string memory symbol_) public {\n        _name = name_;\n        _symbol = symbol_;\n        _decimals = 18;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n     * called.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return _decimals;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `recipient` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(_msgSender(), recipient, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        _approve(_msgSender(), spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * Requirements:\n     *\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``sender``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n        return true;\n    }\n\n    /**\n     * @dev Moves tokens `amount` from `sender` to `recipient`.\n     *\n     * This is internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `sender` cannot be the zero address.\n     * - `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `amount`.\n     */\n    function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(sender, recipient, amount);\n\n        _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n        _balances[recipient] = _balances[recipient].add(amount);\n        emit Transfer(sender, recipient, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply = _totalSupply.add(amount);\n        _balances[account] = _balances[account].add(amount);\n        emit Transfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n        _totalSupply = _totalSupply.sub(amount);\n        emit Transfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Sets {decimals} to a value other than the default one of 18.\n     *\n     * WARNING: This function should only be called from the constructor. Most\n     * applications that interact with token contracts will not expect\n     * {decimals} to ever change, and may work incorrectly if it does.\n     */\n    function _setupDecimals(uint8 decimals_) internal virtual {\n        _decimals = decimals_;\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be to transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address payable) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes memory) {\n        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n        return msg.data;\n    }\n}\n"
    },
    "@openzeppelin/contracts/math/SafeMath.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        uint256 c = a + b;\n        if (c < a) return (false, 0);\n        return (true, c);\n    }\n\n    /**\n     * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b > a) return (false, 0);\n        return (true, a - b);\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n        // benefit is lost if 'b' is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n        if (a == 0) return (true, 0);\n        uint256 c = a * b;\n        if (c / a != b) return (false, 0);\n        return (true, c);\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b == 0) return (false, 0);\n        return (true, a / b);\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b == 0) return (false, 0);\n        return (true, a % b);\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c >= a, \"SafeMath: addition overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b <= a, \"SafeMath: subtraction overflow\");\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (a == 0) return 0;\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b > 0, \"SafeMath: division by zero\");\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b > 0, \"SafeMath: modulo by zero\");\n        return a % b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {trySub}.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b <= a, errorMessage);\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryDiv}.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b > 0, errorMessage);\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting with custom message when dividing by zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryMod}.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b > 0, errorMessage);\n        return a % b;\n    }\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using SafeMath for uint256;\n    using Address for address;\n\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        // solhint-disable-next-line max-line-length\n        require((value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).add(value);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length > 0) { // Return data is optional\n            // solhint-disable-next-line max-line-length\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n        (bool success, ) = recipient.call{ value: amount }(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain`call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n      return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.call{ value: value }(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/bridge/tokens/OVM_L1StandardBridge.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Interface Imports */\nimport { iOVM_L1StandardBridge } from \"../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol\";\nimport { iOVM_L1ERC20Bridge } from \"../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol\";\nimport { iOVM_L2ERC20Bridge } from \"../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/* Library Imports */\nimport { OVM_CrossDomainEnabled } from \"../../../libraries/bridge/OVM_CrossDomainEnabled.sol\";\nimport { Lib_PredeployAddresses } from \"../../../libraries/constants/Lib_PredeployAddresses.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport { Address } from \"@openzeppelin/contracts/utils/Address.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\n\n/**\n * @title OVM_L1StandardBridge\n * @dev The L1 ETH and ERC20 Bridge is a contract which stores deposited L1 funds and standard tokens that are in use on L2.\n * It synchronizes a corresponding L2 Bridge, informing it of deposits, and listening to it for newly finalized withdrawals.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_L1StandardBridge is iOVM_L1StandardBridge, OVM_CrossDomainEnabled {\n    using SafeMath for uint;\n    using SafeERC20 for IERC20;\n\n    /********************************\n     * External Contract References *\n     ********************************/\n\n    address public l2TokenBridge;\n\n    // Maps L1 token to L2 token to balance of the L1 token deposited\n    mapping(address => mapping (address => uint256)) public deposits;\n\n    /***************\n     * Constructor *\n     ***************/\n\n    // This contract lives behind a proxy, so the constructor parameters will go unused.\n    constructor()\n        OVM_CrossDomainEnabled(address(0))\n    {}\n\n    /******************\n     * Initialization *\n     ******************/\n\n    /**\n     * @param _l1messenger L1 Messenger address being used for cross-chain communications.\n     * @param _l2TokenBridge L2 standard bridge address.\n     */\n    function initialize(\n        address _l1messenger,\n        address _l2TokenBridge\n    )\n        public\n    {\n        require(messenger == address(0), \"Contract has already been initialized.\");\n        messenger = _l1messenger;\n        l2TokenBridge = _l2TokenBridge;\n    }\n\n    /**************\n     * Depositing *\n     **************/\n\n    /// @dev Modifier requiring sender to be EOA.  This check could be bypassed by a malicious contract via initcode, but it takes care of the user error we want to avoid.\n    modifier onlyEOA() {\n        // Used to stop deposits from contracts (avoid accidentally lost tokens)\n        require(!Address.isContract(msg.sender), \"Account not EOA\");\n        _;\n    }\n\n    /**\n     * @dev This function can be called with no data\n     * to deposit an amount of ETH to the caller's balance on L2.\n     * Since the receive function doesn't take data, a conservative\n     * default amount is forwarded to L2.\n     */\n    receive()\n        external\n        payable\n        onlyEOA()\n    {\n        _initiateETHDeposit(\n            msg.sender,\n            msg.sender,\n            1_300_000,\n            bytes(\"\")\n        );\n    }\n\n    /**\n     * @inheritdoc iOVM_L1StandardBridge\n     */\n    function depositETH(\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external\n        override\n        payable\n        onlyEOA()\n    {\n        _initiateETHDeposit(\n            msg.sender,\n            msg.sender,\n            _l2Gas,\n            _data\n        );\n    }\n\n    /**\n     * @inheritdoc iOVM_L1StandardBridge\n     */\n    function depositETHTo(\n        address _to,\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external\n        override\n        payable\n    {\n        _initiateETHDeposit(\n            msg.sender,\n            _to,\n            _l2Gas,\n            _data\n        );\n    }\n\n    /**\n     * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of the deposit.\n     * @param _from Account to pull the deposit from on L1.\n     * @param _to Account to give the deposit to on L2.\n     * @param _l2Gas Gas limit required to complete the deposit on L2.\n     * @param _data Optional data to forward to L2. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function _initiateETHDeposit(\n        address _from,\n        address _to,\n        uint32 _l2Gas,\n        bytes memory _data\n    )\n        internal\n    {\n        // Construct calldata for finalizeDeposit call\n        bytes memory message =\n            abi.encodeWithSelector(\n                iOVM_L2ERC20Bridge.finalizeDeposit.selector,\n                address(0),\n                Lib_PredeployAddresses.OVM_ETH,\n                _from,\n                _to,\n                msg.value,\n                _data\n            );\n\n        // Send calldata into L2\n        sendCrossDomainMessage(\n            l2TokenBridge,\n            _l2Gas,\n            message\n        );\n\n        emit ETHDepositInitiated(_from, _to, msg.value, _data);\n    }\n\n    /**\n     * @inheritdoc iOVM_L1ERC20Bridge\n     */\n    function depositERC20(\n        address _l1Token,\n        address _l2Token,\n        uint256 _amount,\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external\n        override\n        virtual\n        onlyEOA()\n    {\n        _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data);\n    }\n\n     /**\n     * @inheritdoc iOVM_L1ERC20Bridge\n     */\n    function depositERC20To(\n        address _l1Token,\n        address _l2Token,\n        address _to,\n        uint256 _amount,\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        external\n        override\n        virtual\n    {\n        _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data);\n    }\n\n    /**\n     * @dev Performs the logic for deposits by informing the L2 Deposited Token\n     * contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom)\n     *\n     * @param _l1Token Address of the L1 ERC20 we are depositing\n     * @param _l2Token Address of the L1 respective L2 ERC20\n     * @param _from Account to pull the deposit from on L1\n     * @param _to Account to give the deposit to on L2\n     * @param _amount Amount of the ERC20 to deposit.\n     * @param _l2Gas Gas limit required to complete the deposit on L2.\n     * @param _data Optional data to forward to L2. This data is provided\n     *        solely as a convenience for external contracts. Aside from enforcing a maximum\n     *        length, these contracts provide no guarantees about its content.\n     */\n    function _initiateERC20Deposit(\n        address _l1Token,\n        address _l2Token,\n        address _from,\n        address _to,\n        uint256 _amount,\n        uint32 _l2Gas,\n        bytes calldata _data\n    )\n        internal\n    {\n        // When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future withdrawals.\n        // safeTransferFrom also checks if the contract has code, so this will fail if _from is an EOA or address(0).\n        IERC20(_l1Token).safeTransferFrom(\n            _from,\n            address(this),\n            _amount\n        );\n\n        // Construct calldata for _l2Token.finalizeDeposit(_to, _amount)\n        bytes memory message = abi.encodeWithSelector(\n            iOVM_L2ERC20Bridge.finalizeDeposit.selector,\n            _l1Token,\n            _l2Token,\n            _from,\n            _to,\n            _amount,\n            _data\n        );\n\n        // Send calldata into L2\n        sendCrossDomainMessage(\n            l2TokenBridge,\n            _l2Gas,\n            message\n        );\n\n        deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].add(_amount);\n\n        emit ERC20DepositInitiated(_l1Token, _l2Token, _from, _to, _amount, _data);\n    }\n\n    /*************************\n     * Cross-chain Functions *\n     *************************/\n\n     /**\n     * @inheritdoc iOVM_L1StandardBridge\n     */\n    function finalizeETHWithdrawal(\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _data\n    )\n        external\n        override\n        onlyFromCrossDomainAccount(l2TokenBridge)\n    {\n        (bool success, ) = _to.call{value: _amount}(new bytes(0));\n        require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');\n\n        emit ETHWithdrawalFinalized(_from, _to, _amount, _data);\n    }\n\n    /**\n     * @inheritdoc iOVM_L1ERC20Bridge\n     */\n    function finalizeERC20Withdrawal(\n        address _l1Token,\n        address _l2Token,\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _data\n    )\n        external\n        override\n        onlyFromCrossDomainAccount(l2TokenBridge)\n    {\n        deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].sub(_amount);\n\n        // When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer.\n        IERC20(_l1Token).safeTransfer(_to, _amount);\n\n        emit ERC20WithdrawalFinalized(_l1Token, _l2Token, _from, _to, _amount, _data);\n    }\n\n    /*****************************\n     * Temporary - Migrating ETH *\n     *****************************/\n\n    /**\n     * @dev Adds ETH balance to the account. This is meant to allow for ETH\n     * to be migrated from an old gateway to a new gateway.\n     * NOTE: This is left for one upgrade only so we are able to receive the migrated ETH from the old contract\n     */\n    function donateETH() external payable {}\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_ECDSAContractAccount.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Interface Imports */\nimport { iOVM_ECDSAContractAccount } from \"../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol\";\n\n/* Library Imports */\nimport { Lib_EIP155Tx } from \"../../libraries/codec/Lib_EIP155Tx.sol\";\nimport { Lib_ExecutionManagerWrapper } from \"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol\";\nimport { Lib_PredeployAddresses } from \"../../libraries/constants/Lib_PredeployAddresses.sol\";\n\n/* Contract Imports */\nimport { OVM_ETH } from \"../predeploys/OVM_ETH.sol\";\n\n/* External Imports */\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport { ECDSA } from \"@openzeppelin/contracts/cryptography/ECDSA.sol\";\n\n/**\n * @title OVM_ECDSAContractAccount\n * @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the\n * ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by\n * providing EIP155 formatted transaction encodings.\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount {\n\n    /*************\n     * Libraries *\n     *************/\n\n    using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx;\n\n\n    /*************\n     * Constants *\n     *************/\n\n    // TODO: should be the amount sufficient to cover the gas costs of all of the transactions up\n    // to and including the CALL/CREATE which forms the entrypoint of the transaction.\n    uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000;\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * No-op fallback mirrors behavior of calling an EOA on L1.\n     */\n    fallback()\n        external\n        payable\n    {\n        return;\n    }\n\n   /**\n    * @dev Should return whether the signature provided is valid for the provided data\n    * @param hash      Hash of the data to be signed\n    * @param signature Signature byte array associated with _data\n    */\n    function isValidSignature(\n        bytes32 hash,\n        bytes memory signature\n    )\n        public\n        view\n        returns (\n            bytes4 magicValue\n        )\n    {\n        return ECDSA.recover(hash, signature) == address(this) ?\n            this.isValidSignature.selector :\n            bytes4(0);\n    }\n\n    /**\n     * Executes a signed transaction.\n     * @param _transaction Signed EIP155 transaction.\n     * @return Whether or not the call returned (rather than reverted).\n     * @return Data returned by the call.\n     */\n    function execute(\n        Lib_EIP155Tx.EIP155Tx memory _transaction\n    )\n        override\n        public\n        returns (\n            bool,\n            bytes memory\n        )\n    {\n        // Address of this contract within the ovm (ovmADDRESS) should be the same as the\n        // recovered address of the user who signed this message. This is how we manage to shim\n        // account abstraction even though the user isn't a contract.\n        require(\n            _transaction.sender() == Lib_ExecutionManagerWrapper.ovmADDRESS(),\n            \"Signature provided for EOA transaction execution is invalid.\"\n        );\n\n        require(\n            _transaction.chainId == Lib_ExecutionManagerWrapper.ovmCHAINID(),\n            \"Transaction signed with wrong chain ID\"\n        );\n\n        // Need to make sure that the transaction nonce is right.\n        require(\n            _transaction.nonce == Lib_ExecutionManagerWrapper.ovmGETNONCE(),\n            \"Transaction nonce does not match the expected nonce.\"\n        );\n\n        // TEMPORARY: Disable gas checks for mainnet.\n        // // Need to make sure that the gas is sufficient to execute the transaction.\n        // require(\n        //    gasleft() >= SafeMath.add(transaction.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD),\n        //    \"Gas is not sufficient to execute the transaction.\"\n        // );\n\n        // Transfer fee to relayer.\n        require(\n            OVM_ETH(Lib_PredeployAddresses.OVM_ETH).transfer(\n                Lib_PredeployAddresses.SEQUENCER_FEE_WALLET,\n                SafeMath.mul(_transaction.gasLimit, _transaction.gasPrice)\n            ),\n            \"Fee was not transferred to relayer.\"\n        );\n\n        if (_transaction.isCreate) {\n            // TEMPORARY: Disable value transfer for contract creations.\n            require(\n                _transaction.value == 0,\n                \"Value transfer in contract creation not supported.\"\n            );\n\n            (address created, bytes memory revertdata) = Lib_ExecutionManagerWrapper.ovmCREATE(\n                _transaction.data\n            );\n\n            // Return true if the contract creation succeeded, false w/ revertdata otherwise.\n            if (created != address(0)) {\n                return (true, abi.encode(created));\n            } else {\n                return (false, revertdata);\n            }\n        } else {\n            // We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps\n            // the nonce of the calling account. Normally an EOA would bump the nonce for both\n            // cases, but since this is a contract we'd end up bumping the nonce twice.\n            Lib_ExecutionManagerWrapper.ovmINCREMENTNONCE();\n\n            // NOTE: Upgrades are temporarily disabled because users can, in theory, modify their EOA\n            // so that they don't have to pay any fees to the sequencer. Function will remain disabled\n            // until a robust solution is in place.\n            require(\n                _transaction.to != Lib_ExecutionManagerWrapper.ovmADDRESS(),\n                \"Calls to self are disabled until upgradability is re-enabled.\"\n            );\n\n            return _transaction.to.call{value: _transaction.value}(_transaction.data);\n        }\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/predeploys/iOVM_ECDSAContractAccount.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_EIP155Tx } from \"../../libraries/codec/Lib_EIP155Tx.sol\";\n\n/**\n * @title iOVM_ECDSAContractAccount\n */\ninterface iOVM_ECDSAContractAccount {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function execute(\n        Lib_EIP155Tx.EIP155Tx memory _transaction\n    )\n        external\n        returns (\n            bool,\n            bytes memory\n        );\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/codec/Lib_EIP155Tx.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_RLPReader } from \"../rlp/Lib_RLPReader.sol\";\nimport { Lib_RLPWriter } from \"../rlp/Lib_RLPWriter.sol\";\n\n/**\n * @title Lib_EIP155Tx\n * @dev A simple library for dealing with the transaction type defined by EIP155:\n *      https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md\n */\nlibrary Lib_EIP155Tx {\n\n    /***********\n     * Structs *\n     ***********/\n\n    // Struct representing an EIP155 transaction. See EIP link above for more information.\n    struct EIP155Tx {\n        // These fields correspond to the actual RLP-encoded fields specified by EIP155.\n        uint256 nonce;\n        uint256 gasPrice;\n        uint256 gasLimit;\n        address to;\n        uint256 value;\n        bytes data;\n        uint8 v;\n        bytes32 r;\n        bytes32 s;\n\n        // Chain ID to associate this transaction with. Used all over the place, seemed easier to\n        // set this once when we create the transaction rather than providing it as an input to\n        // each function. I don't see a strong need to have a transaction with a mutable chain ID.\n        uint256 chainId;\n\n        // The ECDSA \"recovery parameter,\" should always be 0 or 1. EIP155 specifies that:\n        // `v = {0,1} + CHAIN_ID * 2 + 35`\n        // Where `{0,1}` is a stand in for our `recovery_parameter`. Now computing our formula for\n        // the recovery parameter:\n        // 1. `v = {0,1} + CHAIN_ID * 2 + 35`\n        // 2. `v = recovery_parameter + CHAIN_ID * 2 + 35`\n        // 3. `v - CHAIN_ID * 2 - 35 = recovery_parameter`\n        // So we're left with the final formula:\n        // `recovery_parameter = v - CHAIN_ID * 2 - 35`\n        // NOTE: This variable is a uint8 because `v` is inherently limited to a uint8. If we\n        // didn't use a uint8, then recovery_parameter would always be a negative number for chain\n        // IDs greater than 110 (`255 - 110 * 2 - 35 = 0`). So we need to wrap around to support\n        // anything larger.\n        uint8 recoveryParam;\n\n        // Whether or not the transaction is a creation. Necessary because we can't make an address\n        // \"nil\". Using the zero address creates a potential conflict if the user did actually\n        // intend to send a transaction to the zero address.\n        bool isCreate;\n    }\n\n    // Lets us use nicer syntax.\n    using Lib_EIP155Tx for EIP155Tx;\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Decodes an EIP155 transaction and attaches a given Chain ID.\n     * Transaction *must* be RLP-encoded.\n     * @param _encoded RLP-encoded EIP155 transaction.\n     * @param _chainId Chain ID to assocaite with this transaction.\n     * @return Parsed transaction.\n     */\n    function decode(\n        bytes memory _encoded,\n        uint256 _chainId\n    )\n        internal\n        pure\n        returns (\n            EIP155Tx memory\n        )\n    {\n        Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_encoded);\n\n        // Note formula above about how recoveryParam is computed.\n        uint8 v = uint8(Lib_RLPReader.readUint256(decoded[6]));\n        uint8 recoveryParam = uint8(v - 2 * _chainId - 35);\n\n        // Recovery param being anything other than 0 or 1 indicates that we have the wrong chain\n        // ID.\n        require(\n            recoveryParam < 2,\n            \"Lib_EIP155Tx: Transaction signed with wrong chain ID\"\n        );\n\n        // Creations can be detected by looking at the byte length here.\n        bool isCreate = Lib_RLPReader.readBytes(decoded[3]).length == 0;\n\n        return EIP155Tx({\n            nonce: Lib_RLPReader.readUint256(decoded[0]),\n            gasPrice: Lib_RLPReader.readUint256(decoded[1]),\n            gasLimit: Lib_RLPReader.readUint256(decoded[2]),\n            to: Lib_RLPReader.readAddress(decoded[3]),\n            value: Lib_RLPReader.readUint256(decoded[4]),\n            data: Lib_RLPReader.readBytes(decoded[5]),\n            v: v,\n            r: Lib_RLPReader.readBytes32(decoded[7]),\n            s: Lib_RLPReader.readBytes32(decoded[8]),\n            chainId: _chainId,\n            recoveryParam: recoveryParam,\n            isCreate: isCreate\n        });\n    }\n\n    /**\n     * Encodes an EIP155 transaction into RLP.\n     * @param _transaction EIP155 transaction to encode.\n     * @param _includeSignature Whether or not to encode the signature.\n     * @return RLP-encoded transaction.\n     */\n    function encode(\n        EIP155Tx memory _transaction,\n        bool _includeSignature\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes[] memory raw = new bytes[](9);\n\n        raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce);\n        raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice);\n        raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit);\n\n        // We write the encoding of empty bytes when the transaction is a creation, *not* the zero\n        // address as one might assume.\n        if (_transaction.isCreate) {\n            raw[3] = Lib_RLPWriter.writeBytes('');\n        } else {\n            raw[3] = Lib_RLPWriter.writeAddress(_transaction.to);\n        }\n\n        raw[4] = Lib_RLPWriter.writeUint(_transaction.value);\n        raw[5] = Lib_RLPWriter.writeBytes(_transaction.data);\n\n        if (_includeSignature) {\n            raw[6] = Lib_RLPWriter.writeUint(_transaction.v);\n            raw[7] = Lib_RLPWriter.writeBytes32(_transaction.r);\n            raw[8] = Lib_RLPWriter.writeBytes32(_transaction.s);\n        } else {\n            // Chain ID *is* included in the unsigned transaction.\n            raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId);\n            raw[7] = Lib_RLPWriter.writeBytes('');\n            raw[8] = Lib_RLPWriter.writeBytes('');\n        }\n\n        return Lib_RLPWriter.writeList(raw);\n    }\n\n    /**\n     * Computes the hash of an EIP155 transaction. Assumes that you don't want to include the\n     * signature in this hash because that's a very uncommon usecase. If you really want to include\n     * the signature, just encode with the signature and take the hash yourself.\n     */\n    function hash(\n        EIP155Tx memory _transaction\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return keccak256(\n            _transaction.encode(false)\n        );\n    }\n\n    /**\n     * Computes the sender of an EIP155 transaction.\n     * @param _transaction EIP155 transaction to get a sender for.\n     * @return Address corresponding to the private key that signed this transaction.\n     */\n    function sender(\n        EIP155Tx memory _transaction\n    )\n        internal\n        pure\n        returns (\n            address\n        )\n    {\n        return ecrecover(\n            _transaction.hash(),\n            _transaction.recoveryParam + 27,\n            _transaction.r,\n            _transaction.s\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/wrappers/Lib_ExecutionManagerWrapper.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_ErrorUtils } from \"../utils/Lib_ErrorUtils.sol\";\nimport { Lib_PredeployAddresses } from \"../constants/Lib_PredeployAddresses.sol\";\n\n/**\n * @title Lib_ExecutionManagerWrapper\n * @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the\n *  predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the\n *  user to trigger OVM opcodes by directly calling the OVM_ExecutionManger.\n *\n * Compiler used: solc\n * Runtime target: OVM\n */\nlibrary Lib_ExecutionManagerWrapper {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Performs a safe ovmCREATE call.\n     * @param _bytecode Code for the new contract.\n     * @return Address of the created contract.\n     */\n    function ovmCREATE(\n        bytes memory _bytecode\n    )\n        internal\n        returns (\n            address,\n            bytes memory\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmCREATE(bytes)\",\n                _bytecode\n            )\n        );\n\n        return abi.decode(returndata, (address, bytes));\n    }\n\n    /**\n     * Performs a safe ovmGETNONCE call.\n     * @return Result of calling ovmGETNONCE.\n     */\n    function ovmGETNONCE()\n        internal\n        returns (\n            uint256\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmGETNONCE()\"\n            )\n        );\n\n        return abi.decode(returndata, (uint256));\n    }\n\n    /**\n     * Performs a safe ovmINCREMENTNONCE call.\n     */\n    function ovmINCREMENTNONCE()\n        internal\n    {\n        _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmINCREMENTNONCE()\"\n            )\n        );\n    }\n\n    /**\n     * Performs a safe ovmCREATEEOA call.\n     * @param _messageHash Message hash which was signed by EOA\n     * @param _v v value of signature (0 or 1)\n     * @param _r r value of signature\n     * @param _s s value of signature\n     */\n    function ovmCREATEEOA(\n        bytes32 _messageHash,\n        uint8 _v,\n        bytes32 _r,\n        bytes32 _s\n    )\n        internal\n    {\n        _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)\",\n                _messageHash,\n                _v,\n                _r,\n                _s\n            )\n        );\n    }\n\n    /**\n     * Calls the ovmL1TXORIGIN opcode.\n     * @return Address that sent this message from L1.\n     */\n    function ovmL1TXORIGIN()\n        internal\n        returns (\n            address\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmL1TXORIGIN()\"\n            )\n        );\n\n        return abi.decode(returndata, (address));\n    }\n\n    /**\n     * Calls the ovmCHAINID opcode.\n     * @return Chain ID of the current network.\n     */\n    function ovmCHAINID()\n        internal\n        returns (\n            uint256\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmCHAINID()\"\n            )\n        );\n\n        return abi.decode(returndata, (uint256));\n    }\n\n    /**\n     * Performs a safe ovmADDRESS call.\n     * @return Result of calling ovmADDRESS.\n     */\n    function ovmADDRESS()\n        internal\n        returns (\n            address\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmADDRESS()\"\n            )\n        );\n\n        return abi.decode(returndata, (address));\n    }\n\n    /**\n     * Calls the value-enabled ovmCALL opcode.\n     * @param _gasLimit Amount of gas to be passed into this call.\n     * @param _address Address of the contract to call.\n     * @param _value ETH value to pass with the call.\n     * @param _calldata Data to send along with the call.\n     * @return _success Whether or not the call returned (rather than reverted).\n     * @return _returndata Data returned by the call.\n     */\n    function ovmCALL(\n        uint256 _gasLimit,\n        address _address,\n        uint256 _value,\n        bytes memory _calldata\n    )\n        internal\n        returns (\n            bool,\n            bytes memory\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmCALL(uint256,address,uint256,bytes)\",\n                _gasLimit,\n                _address,\n                _value,\n                _calldata\n            )\n        );\n\n        return abi.decode(returndata, (bool, bytes));\n    }\n\n    /**\n     * Calls the ovmBALANCE opcode.\n     * @param _address OVM account to query the balance of.\n     * @return Balance of the account.\n     */\n    function ovmBALANCE(\n        address _address\n    )\n        internal\n        returns (\n            uint256\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmBALANCE(address)\",\n                _address\n            )\n        );\n\n        return abi.decode(returndata, (uint256));\n    }\n\n    /**\n     * Calls the ovmCALLVALUE opcode.\n     * @return Value of the current call frame.\n     */\n    function ovmCALLVALUE()\n        internal\n        returns (\n            uint256\n        )\n    {\n        bytes memory returndata = _callWrapperContract(\n            abi.encodeWithSignature(\n                \"ovmCALLVALUE()\"\n            )\n        );\n\n        return abi.decode(returndata, (uint256));\n    }\n\n\n    /*********************\n     * Private Functions *\n     *********************/\n\n    /**\n     * Performs an ovm interaction and the necessary safety checks.\n     * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash).\n     * @return Data sent back by the OVM_ExecutionManager.\n     */\n    function _callWrapperContract(\n        bytes memory _calldata\n    )\n        private\n        returns (\n            bytes memory\n        )\n    {\n        (bool success, bytes memory returndata) = Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata);\n\n        if (success == true) {\n            return returndata;\n        } else {\n            assembly {\n                revert(add(returndata, 0x20), mload(returndata))\n            }\n        }\n    }\n}\n"
    },
    "@openzeppelin/contracts/cryptography/ECDSA.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        // Check the signature length\n        if (signature.length != 65) {\n            revert(\"ECDSA: invalid signature length\");\n        }\n\n        // Divide the signature in r, s and v variables\n        bytes32 r;\n        bytes32 s;\n        uint8 v;\n\n        // ecrecover takes the signature parameters, and the only way to get them\n        // currently is to use assembly.\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            r := mload(add(signature, 0x20))\n            s := mload(add(signature, 0x40))\n            v := byte(0, mload(add(signature, 0x60)))\n        }\n\n        return recover(hash, v, r, s);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, \"ECDSA: invalid signature 's' value\");\n        require(v == 27 || v == 28, \"ECDSA: invalid signature 'v' value\");\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        require(signer != address(0), \"ECDSA: invalid signature\");\n\n        return signer;\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n     * replicates the behavior of the\n     * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]\n     * JSON-RPC method.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n        // 32 is the length in bytes of hash,\n        // enforced by the type signature above\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/rlp/Lib_RLPReader.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title Lib_RLPReader\n * @dev Adapted from \"RLPReader\" by Hamdi Allam (hamdi.allam97@gmail.com).\n */\nlibrary Lib_RLPReader {\n\n    /*************\n     * Constants *\n     *************/\n\n    uint256 constant internal MAX_LIST_LENGTH = 32;\n\n\n    /*********\n     * Enums *\n     *********/\n\n    enum RLPItemType {\n        DATA_ITEM,\n        LIST_ITEM\n    }\n\n\n    /***********\n     * Structs *\n     ***********/\n\n    struct RLPItem {\n        uint256 length;\n        uint256 ptr;\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Converts bytes to a reference to memory position and length.\n     * @param _in Input bytes to convert.\n     * @return Output memory reference.\n     */\n    function toRLPItem(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            RLPItem memory\n        )\n    {\n        uint256 ptr;\n        assembly {\n            ptr := add(_in, 32)\n        }\n\n        return RLPItem({\n            length: _in.length,\n            ptr: ptr\n        });\n    }\n\n    /**\n     * Reads an RLP list value into a list of RLP items.\n     * @param _in RLP list value.\n     * @return Decoded RLP list items.\n     */\n    function readList(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            RLPItem[] memory\n        )\n    {\n        (\n            uint256 listOffset,\n            ,\n            RLPItemType itemType\n        ) = _decodeLength(_in);\n\n        require(\n            itemType == RLPItemType.LIST_ITEM,\n            \"Invalid RLP list value.\"\n        );\n\n        // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by\n        // writing to the length. Since we can't know the number of RLP items without looping over\n        // the entire input, we'd have to loop twice to accurately size this array. It's easier to\n        // simply set a reasonable maximum list length and decrease the size before we finish.\n        RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);\n\n        uint256 itemCount = 0;\n        uint256 offset = listOffset;\n        while (offset < _in.length) {\n            require(\n                itemCount < MAX_LIST_LENGTH,\n                \"Provided RLP list exceeds max list length.\"\n            );\n\n            (\n                uint256 itemOffset,\n                uint256 itemLength,\n            ) = _decodeLength(RLPItem({\n                length: _in.length - offset,\n                ptr: _in.ptr + offset\n            }));\n\n            out[itemCount] = RLPItem({\n                length: itemLength + itemOffset,\n                ptr: _in.ptr + offset\n            });\n\n            itemCount += 1;\n            offset += itemOffset + itemLength;\n        }\n\n        // Decrease the array size to match the actual item count.\n        assembly {\n            mstore(out, itemCount)\n        }\n\n        return out;\n    }\n\n    /**\n     * Reads an RLP list value into a list of RLP items.\n     * @param _in RLP list value.\n     * @return Decoded RLP list items.\n     */\n    function readList(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            RLPItem[] memory\n        )\n    {\n        return readList(\n            toRLPItem(_in)\n        );\n    }\n\n    /**\n     * Reads an RLP bytes value into bytes.\n     * @param _in RLP bytes value.\n     * @return Decoded bytes.\n     */\n    function readBytes(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        (\n            uint256 itemOffset,\n            uint256 itemLength,\n            RLPItemType itemType\n        ) = _decodeLength(_in);\n\n        require(\n            itemType == RLPItemType.DATA_ITEM,\n            \"Invalid RLP bytes value.\"\n        );\n\n        return _copy(_in.ptr, itemOffset, itemLength);\n    }\n\n    /**\n     * Reads an RLP bytes value into bytes.\n     * @param _in RLP bytes value.\n     * @return Decoded bytes.\n     */\n    function readBytes(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return readBytes(\n            toRLPItem(_in)\n        );\n    }\n\n    /**\n     * Reads an RLP string value into a string.\n     * @param _in RLP string value.\n     * @return Decoded string.\n     */\n    function readString(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            string memory\n        )\n    {\n        return string(readBytes(_in));\n    }\n\n    /**\n     * Reads an RLP string value into a string.\n     * @param _in RLP string value.\n     * @return Decoded string.\n     */\n    function readString(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            string memory\n        )\n    {\n        return readString(\n            toRLPItem(_in)\n        );\n    }\n\n    /**\n     * Reads an RLP bytes32 value into a bytes32.\n     * @param _in RLP bytes32 value.\n     * @return Decoded bytes32.\n     */\n    function readBytes32(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        require(\n            _in.length <= 33,\n            \"Invalid RLP bytes32 value.\"\n        );\n\n        (\n            uint256 itemOffset,\n            uint256 itemLength,\n            RLPItemType itemType\n        ) = _decodeLength(_in);\n\n        require(\n            itemType == RLPItemType.DATA_ITEM,\n            \"Invalid RLP bytes32 value.\"\n        );\n\n        uint256 ptr = _in.ptr + itemOffset;\n        bytes32 out;\n        assembly {\n            out := mload(ptr)\n\n            // Shift the bytes over to match the item size.\n            if lt(itemLength, 32) {\n                out := div(out, exp(256, sub(32, itemLength)))\n            }\n        }\n\n        return out;\n    }\n\n    /**\n     * Reads an RLP bytes32 value into a bytes32.\n     * @param _in RLP bytes32 value.\n     * @return Decoded bytes32.\n     */\n    function readBytes32(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return readBytes32(\n            toRLPItem(_in)\n        );\n    }\n\n    /**\n     * Reads an RLP uint256 value into a uint256.\n     * @param _in RLP uint256 value.\n     * @return Decoded uint256.\n     */\n    function readUint256(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            uint256\n        )\n    {\n        return uint256(readBytes32(_in));\n    }\n\n    /**\n     * Reads an RLP uint256 value into a uint256.\n     * @param _in RLP uint256 value.\n     * @return Decoded uint256.\n     */\n    function readUint256(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            uint256\n        )\n    {\n        return readUint256(\n            toRLPItem(_in)\n        );\n    }\n\n    /**\n     * Reads an RLP bool value into a bool.\n     * @param _in RLP bool value.\n     * @return Decoded bool.\n     */\n    function readBool(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            bool\n        )\n    {\n        require(\n            _in.length == 1,\n            \"Invalid RLP boolean value.\"\n        );\n\n        uint256 ptr = _in.ptr;\n        uint256 out;\n        assembly {\n            out := byte(0, mload(ptr))\n        }\n\n        require(\n            out == 0 || out == 1,\n            \"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1\"\n        );\n\n        return out != 0;\n    }\n\n    /**\n     * Reads an RLP bool value into a bool.\n     * @param _in RLP bool value.\n     * @return Decoded bool.\n     */\n    function readBool(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            bool\n        )\n    {\n        return readBool(\n            toRLPItem(_in)\n        );\n    }\n\n    /**\n     * Reads an RLP address value into a address.\n     * @param _in RLP address value.\n     * @return Decoded address.\n     */\n    function readAddress(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            address\n        )\n    {\n        if (_in.length == 1) {\n            return address(0);\n        }\n\n        require(\n            _in.length == 21,\n            \"Invalid RLP address value.\"\n        );\n\n        return address(readUint256(_in));\n    }\n\n    /**\n     * Reads an RLP address value into a address.\n     * @param _in RLP address value.\n     * @return Decoded address.\n     */\n    function readAddress(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            address\n        )\n    {\n        return readAddress(\n            toRLPItem(_in)\n        );\n    }\n\n    /**\n     * Reads the raw bytes of an RLP item.\n     * @param _in RLP item to read.\n     * @return Raw RLP bytes.\n     */\n    function readRawBytes(\n        RLPItem memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return _copy(_in);\n    }\n\n\n    /*********************\n     * Private Functions *\n     *********************/\n\n    /**\n     * Decodes the length of an RLP item.\n     * @param _in RLP item to decode.\n     * @return Offset of the encoded data.\n     * @return Length of the encoded data.\n     * @return RLP item type (LIST_ITEM or DATA_ITEM).\n     */\n    function _decodeLength(\n        RLPItem memory _in\n    )\n        private\n        pure\n        returns (\n            uint256,\n            uint256,\n            RLPItemType\n        )\n    {\n        require(\n            _in.length > 0,\n            \"RLP item cannot be null.\"\n        );\n\n        uint256 ptr = _in.ptr;\n        uint256 prefix;\n        assembly {\n            prefix := byte(0, mload(ptr))\n        }\n\n        if (prefix <= 0x7f) {\n            // Single byte.\n\n            return (0, 1, RLPItemType.DATA_ITEM);\n        } else if (prefix <= 0xb7) {\n            // Short string.\n\n            uint256 strLen = prefix - 0x80;\n\n            require(\n                _in.length > strLen,\n                \"Invalid RLP short string.\"\n            );\n\n            return (1, strLen, RLPItemType.DATA_ITEM);\n        } else if (prefix <= 0xbf) {\n            // Long string.\n            uint256 lenOfStrLen = prefix - 0xb7;\n\n            require(\n                _in.length > lenOfStrLen,\n                \"Invalid RLP long string length.\"\n            );\n\n            uint256 strLen;\n            assembly {\n                // Pick out the string length.\n                strLen := div(\n                    mload(add(ptr, 1)),\n                    exp(256, sub(32, lenOfStrLen))\n                )\n            }\n\n            require(\n                _in.length > lenOfStrLen + strLen,\n                \"Invalid RLP long string.\"\n            );\n\n            return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);\n        } else if (prefix <= 0xf7) {\n            // Short list.\n            uint256 listLen = prefix - 0xc0;\n\n            require(\n                _in.length > listLen,\n                \"Invalid RLP short list.\"\n            );\n\n            return (1, listLen, RLPItemType.LIST_ITEM);\n        } else {\n            // Long list.\n            uint256 lenOfListLen = prefix - 0xf7;\n\n            require(\n                _in.length > lenOfListLen,\n                \"Invalid RLP long list length.\"\n            );\n\n            uint256 listLen;\n            assembly {\n                // Pick out the list length.\n                listLen := div(\n                    mload(add(ptr, 1)),\n                    exp(256, sub(32, lenOfListLen))\n                )\n            }\n\n            require(\n                _in.length > lenOfListLen + listLen,\n                \"Invalid RLP long list.\"\n            );\n\n            return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);\n        }\n    }\n\n    /**\n     * Copies the bytes from a memory location.\n     * @param _src Pointer to the location to read from.\n     * @param _offset Offset to start reading from.\n     * @param _length Number of bytes to read.\n     * @return Copied bytes.\n     */\n    function _copy(\n        uint256 _src,\n        uint256 _offset,\n        uint256 _length\n    )\n        private\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory out = new bytes(_length);\n        if (out.length == 0) {\n            return out;\n        }\n\n        uint256 src = _src + _offset;\n        uint256 dest;\n        assembly {\n            dest := add(out, 32)\n        }\n\n        // Copy over as many complete words as we can.\n        for (uint256 i = 0; i < _length / 32; i++) {\n            assembly {\n                mstore(dest, mload(src))\n            }\n\n            src += 32;\n            dest += 32;\n        }\n\n        // Pick out the remaining bytes.\n        uint256 mask = 256 ** (32 - (_length % 32)) - 1;\n        assembly {\n            mstore(\n                dest,\n                or(\n                    and(mload(src), not(mask)),\n                    and(mload(dest), mask)\n                )\n            )\n        }\n\n        return out;\n    }\n\n    /**\n     * Copies an RLP item into bytes.\n     * @param _in RLP item to copy.\n     * @return Copied bytes.\n     */\n    function _copy(\n        RLPItem memory _in\n    )\n        private\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return _copy(_in.ptr, 0, _in.length);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/**\n * @title Lib_RLPWriter\n * @author Bakaoh (with modifications)\n */\nlibrary Lib_RLPWriter {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * RLP encodes a byte string.\n     * @param _in The byte string to encode.\n     * @return The RLP encoded string in bytes.\n     */\n    function writeBytes(\n        bytes memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory encoded;\n\n        if (_in.length == 1 && uint8(_in[0]) < 128) {\n            encoded = _in;\n        } else {\n            encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);\n        }\n\n        return encoded;\n    }\n\n    /**\n     * RLP encodes a list of RLP encoded byte byte strings.\n     * @param _in The list of RLP encoded byte strings.\n     * @return The RLP encoded list of items in bytes.\n     */\n    function writeList(\n        bytes[] memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory list = _flatten(_in);\n        return abi.encodePacked(_writeLength(list.length, 192), list);\n    }\n\n    /**\n     * RLP encodes a string.\n     * @param _in The string to encode.\n     * @return The RLP encoded string in bytes.\n     */\n    function writeString(\n        string memory _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return writeBytes(bytes(_in));\n    }\n\n    /**\n     * RLP encodes an address.\n     * @param _in The address to encode.\n     * @return The RLP encoded address in bytes.\n     */\n    function writeAddress(\n        address _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return writeBytes(abi.encodePacked(_in));\n    }\n\n    /**\n     * RLP encodes a bytes32 value.\n     * @param _in The bytes32 to encode.\n     * @return _out The RLP encoded bytes32 in bytes.\n     */\n    function writeBytes32(\n        bytes32 _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory _out\n        )\n    {\n        return writeBytes(abi.encodePacked(_in));\n    }\n\n    /**\n     * RLP encodes a uint.\n     * @param _in The uint256 to encode.\n     * @return The RLP encoded uint256 in bytes.\n     */\n    function writeUint(\n        uint256 _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return writeBytes(_toBinary(_in));\n    }\n\n    /**\n     * RLP encodes a bool.\n     * @param _in The bool to encode.\n     * @return The RLP encoded bool in bytes.\n     */\n    function writeBool(\n        bool _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory encoded = new bytes(1);\n        encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));\n        return encoded;\n    }\n\n\n    /*********************\n     * Private Functions *\n     *********************/\n\n    /**\n     * Encode the first byte, followed by the `len` in binary form if `length` is more than 55.\n     * @param _len The length of the string or the payload.\n     * @param _offset 128 if item is string, 192 if item is list.\n     * @return RLP encoded bytes.\n     */\n    function _writeLength(\n        uint256 _len,\n        uint256 _offset\n    )\n        private\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory encoded;\n\n        if (_len < 56) {\n            encoded = new bytes(1);\n            encoded[0] = byte(uint8(_len) + uint8(_offset));\n        } else {\n            uint256 lenLen;\n            uint256 i = 1;\n            while (_len / i != 0) {\n                lenLen++;\n                i *= 256;\n            }\n\n            encoded = new bytes(lenLen + 1);\n            encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);\n            for(i = 1; i <= lenLen; i++) {\n                encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));\n            }\n        }\n\n        return encoded;\n    }\n\n    /**\n     * Encode integer in big endian binary form with no leading zeroes.\n     * @notice TODO: This should be optimized with assembly to save gas costs.\n     * @param _x The integer to encode.\n     * @return RLP encoded bytes.\n     */\n    function _toBinary(\n        uint256 _x\n    )\n        private\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory b = abi.encodePacked(_x);\n\n        uint256 i = 0;\n        for (; i < 32; i++) {\n            if (b[i] != 0) {\n                break;\n            }\n        }\n\n        bytes memory res = new bytes(32 - i);\n        for (uint256 j = 0; j < res.length; j++) {\n            res[j] = b[i++];\n        }\n\n        return res;\n    }\n\n    /**\n     * Copies a piece of memory to another location.\n     * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.\n     * @param _dest Destination location.\n     * @param _src Source location.\n     * @param _len Length of memory to copy.\n     */\n    function _memcpy(\n        uint256 _dest,\n        uint256 _src,\n        uint256 _len\n    )\n        private\n        pure\n    {\n        uint256 dest = _dest;\n        uint256 src = _src;\n        uint256 len = _len;\n\n        for(; len >= 32; len -= 32) {\n            assembly {\n                mstore(dest, mload(src))\n            }\n            dest += 32;\n            src += 32;\n        }\n\n        uint256 mask = 256 ** (32 - len) - 1;\n        assembly {\n            let srcpart := and(mload(src), not(mask))\n            let destpart := and(mload(dest), mask)\n            mstore(dest, or(destpart, srcpart))\n        }\n    }\n\n    /**\n     * Flattens a list of byte strings into one byte string.\n     * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.\n     * @param _list List of byte strings to flatten.\n     * @return The flattened byte string.\n     */\n    function _flatten(\n        bytes[] memory _list\n    )\n        private\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        if (_list.length == 0) {\n            return new bytes(0);\n        }\n\n        uint256 len;\n        uint256 i = 0;\n        for (; i < _list.length; i++) {\n            len += _list[i].length;\n        }\n\n        bytes memory flattened = new bytes(len);\n        uint256 flattenedPtr;\n        assembly { flattenedPtr := add(flattened, 0x20) }\n\n        for(i = 0; i < _list.length; i++) {\n            bytes memory item = _list[i];\n\n            uint256 listPtr;\n            assembly { listPtr := add(item, 0x20)}\n\n            _memcpy(flattenedPtr, listPtr, item.length);\n            flattenedPtr += _list[i].length;\n        }\n\n        return flattened;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/utils/Lib_ErrorUtils.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/**\n * @title Lib_ErrorUtils\n */\nlibrary Lib_ErrorUtils {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Encodes an error string into raw solidity-style revert data.\n     * (i.e. ascii bytes, prefixed with bytes4(keccak(\"Error(string))\"))\n     * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)#panic-via-assert-and-error-via-require\n     * @param _reason Reason for the reversion.\n     * @return Standard solidity revert data for the given reason.\n     */\n    function encodeRevertString(\n        string memory _reason\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return abi.encodeWithSignature(\n            \"Error(string)\",\n            _reason\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_ProxyEOA.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_Bytes32Utils } from \"../../libraries/utils/Lib_Bytes32Utils.sol\";\nimport { Lib_PredeployAddresses } from \"../../libraries/constants/Lib_PredeployAddresses.sol\";\nimport { Lib_ExecutionManagerWrapper } from \"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol\";\n\n/**\n * @title OVM_ProxyEOA\n * @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation contract.\n * In combination with the logic implemented in the ECDSA Contract Account, this enables a form of upgradable\n * 'account abstraction' on layer 2.\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_ProxyEOA {\n\n    /**********\n     * Events *\n     **********/\n\n    event Upgraded(\n        address indexed implementation\n    );\n\n\n    /*************\n     * Constants *\n     *************/\n\n    bytes32 constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; //bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1);\n\n\n    /*********************\n     * Fallback Function *\n     *********************/\n\n    fallback()\n        external\n        payable\n    {\n        (bool success, bytes memory returndata) = getImplementation().delegatecall(msg.data);\n\n        if (success) {\n            assembly {\n                return(add(returndata, 0x20), mload(returndata))\n            }\n        } else {\n            assembly {\n                revert(add(returndata, 0x20), mload(returndata))\n            }\n        }\n    }\n\n    // WARNING: We use the deployed bytecode of this contract as a template to create ProxyEOA\n    // contracts. As a result, we must *not* perform any constructor logic. Use initialization\n    // functions if necessary.\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Changes the implementation address.\n     * @param _implementation New implementation address.\n     */\n    function upgrade(\n        address _implementation\n    )\n        external\n    {\n        require(\n            msg.sender == Lib_ExecutionManagerWrapper.ovmADDRESS(),\n            \"EOAs can only upgrade their own EOA implementation.\"\n        );\n\n        _setImplementation(_implementation);\n        emit Upgraded(_implementation);\n    }\n\n    /**\n     * Gets the address of the current implementation.\n     * @return Current implementation address.\n     */\n    function getImplementation()\n        public\n        view\n        returns (\n            address\n        )\n    {\n        bytes32 addr32;\n        assembly {\n            addr32 := sload(IMPLEMENTATION_KEY)\n        }\n\n        address implementation = Lib_Bytes32Utils.toAddress(addr32);\n        if (implementation == address(0)) {\n            return Lib_PredeployAddresses.ECDSA_CONTRACT_ACCOUNT;\n        } else {\n            return implementation;\n        }\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    function _setImplementation(\n        address _implementation\n    )\n        internal\n    {\n        bytes32 addr32 = Lib_Bytes32Utils.fromAddress(_implementation);\n        assembly {\n            sstore(IMPLEMENTATION_KEY, addr32)\n        }\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/utils/Lib_Bytes32Utils.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title Lib_Byte32Utils\n */\nlibrary Lib_Bytes32Utils {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Converts a bytes32 value to a boolean. Anything non-zero will be converted to \"true.\"\n     * @param _in Input bytes32 value.\n     * @return Bytes32 as a boolean.\n     */\n    function toBool(\n        bytes32 _in\n    )\n        internal\n        pure\n        returns (\n            bool\n        )\n    {\n        return _in != 0;\n    }\n\n    /**\n     * Converts a boolean to a bytes32 value.\n     * @param _in Input boolean value.\n     * @return Boolean as a bytes32.\n     */\n    function fromBool(\n        bool _in\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return bytes32(uint256(_in ? 1 : 0));\n    }\n\n    /**\n     * Converts a bytes32 value to an address. Takes the *last* 20 bytes.\n     * @param _in Input bytes32 value.\n     * @return Bytes32 as an address.\n     */\n    function toAddress(\n        bytes32 _in\n    )\n        internal\n        pure\n        returns (\n            address\n        )\n    {\n        return address(uint160(uint256(_in)));\n    }\n\n    /**\n     * Converts an address to a bytes32.\n     * @param _in Input address value.\n     * @return Address as a bytes32.\n     */\n    function fromAddress(\n        address _in\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return bytes32(uint256(_in));\n    }\n\n    /**\n     * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.\n     * @param _in Input bytes32 value.\n     * @return Bytes32 without any leading zeros.\n     */\n    function removeLeadingZeros(\n        bytes32 _in\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory out;\n\n        assembly {\n            // Figure out how many leading zero bytes to remove.\n            let shift := 0\n            for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {\n                shift := add(shift, 1)\n            }\n\n            // Reserve some space for our output and fix the free memory pointer.\n            out := mload(0x40)\n            mstore(0x40, add(out, 0x40))\n\n            // Shift the value and store it into the output bytes.\n            mstore(add(out, 0x20), shl(mul(shift, 8), _in))\n\n            // Store the new size (with leading zero bytes removed) in the output byte size.\n            mstore(out, sub(32, shift))\n        }\n\n        return out;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_SequencerEntrypoint.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_EIP155Tx } from \"../../libraries/codec/Lib_EIP155Tx.sol\";\nimport { Lib_ExecutionManagerWrapper } from \"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol\";\nimport { iOVM_ECDSAContractAccount } from \"../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol\";\n\n/**\n * @title OVM_SequencerEntrypoint\n * @dev The Sequencer Entrypoint is a predeploy which, despite its name, can in fact be called by\n * any account. It accepts a more efficient compressed calldata format, which it decompresses and\n * encodes to the standard EIP155 transaction format.\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_SequencerEntrypoint {\n\n    /*************\n     * Libraries *\n     *************/\n\n    using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx;\n\n\n    /*********************\n     * Fallback Function *\n     *********************/\n\n    /**\n     * Expects an RLP-encoded EIP155 transaction as input. See the EIP for a more detailed\n     * description of this transaction format:\n     * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md\n     */\n    fallback()\n        external\n    {\n        // We use this twice, so it's more gas efficient to store a copy of it (barely).\n        bytes memory encodedTx = msg.data;\n\n        // Decode the tx with the correct chain ID.\n        Lib_EIP155Tx.EIP155Tx memory transaction = Lib_EIP155Tx.decode(\n            encodedTx,\n            Lib_ExecutionManagerWrapper.ovmCHAINID()\n        );\n\n        // Value is computed on the fly. Keep it in the stack to save some gas.\n        address target = transaction.sender();\n\n        bool isEmptyContract;\n        assembly {\n            isEmptyContract := iszero(extcodesize(target))\n        }\n\n        // If the account is empty, deploy the default EOA to that address.\n        if (isEmptyContract) {\n            Lib_ExecutionManagerWrapper.ovmCREATEEOA(\n                transaction.hash(),\n                transaction.recoveryParam,\n                transaction.r,\n                transaction.s\n            );\n        }\n\n        // Forward the transaction over to the EOA.\n        (bool success, bytes memory returndata) = target.call(\n            abi.encodeWithSelector(iOVM_ECDSAContractAccount.execute.selector, transaction)\n        );\n\n        if (success) {\n            assembly {\n                return(add(returndata, 0x20), mload(returndata))\n            }\n        } else {\n            assembly {\n                revert(add(returndata, 0x20), mload(returndata))\n            }\n        }\n    }\n}\n"
    },
    "contracts/test-libraries/codec/TestLib_EIP155Tx.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_EIP155Tx } from \"../../optimistic-ethereum/libraries/codec/Lib_EIP155Tx.sol\";\n\n/**\n * @title TestLib_EIP155Tx\n */\ncontract TestLib_EIP155Tx {\n    function decode(\n        bytes memory _encoded,\n        uint256 _chainId\n    )\n        public\n        pure\n        returns (\n            Lib_EIP155Tx.EIP155Tx memory\n        )\n    {\n        return Lib_EIP155Tx.decode(\n            _encoded,\n            _chainId\n        );\n    }\n\n    function encode(\n        Lib_EIP155Tx.EIP155Tx memory _transaction,\n        bool _includeSignature\n    )\n        public\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return Lib_EIP155Tx.encode(\n            _transaction,\n            _includeSignature\n        );\n    }\n\n    function hash(\n        Lib_EIP155Tx.EIP155Tx memory _transaction\n    )\n        public\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return Lib_EIP155Tx.hash(\n            _transaction\n        );\n    }\n\n    function sender(\n        Lib_EIP155Tx.EIP155Tx memory _transaction\n    )\n        public\n        pure\n        returns (\n            address\n        )\n    {\n        return Lib_EIP155Tx.sender(\n            _transaction\n        );\n    }\n}\n"
    },
    "contracts/test-libraries/rlp/TestLib_RLPWriter.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_RLPWriter } from \"../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol\";\nimport { TestERC20 } from \"../../test-helpers/TestERC20.sol\";\n\n/**\n * @title TestLib_RLPWriter\n */\ncontract TestLib_RLPWriter {\n\n    function writeBytes(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            bytes memory _out\n        )\n    {\n        return Lib_RLPWriter.writeBytes(_in);\n    }\n\n    function writeList(\n        bytes[] memory _in\n    )\n        public\n        pure\n        returns (\n            bytes memory _out\n        )\n    {\n        return Lib_RLPWriter.writeList(_in);\n    }\n\n    function writeString(\n        string memory _in\n    )\n        public\n        pure\n        returns (\n            bytes memory _out\n        )\n    {\n        return Lib_RLPWriter.writeString(_in);\n    }\n\n    function writeAddress(\n        address _in\n    )\n        public\n        pure\n        returns (\n            bytes memory _out\n        )\n    {\n        return Lib_RLPWriter.writeAddress(_in);\n    }\n\n    function writeUint(\n        uint256 _in\n    )\n        public\n        pure\n        returns (\n            bytes memory _out\n        )\n    {\n        return Lib_RLPWriter.writeUint(_in);\n    }\n\n    function writeBool(\n        bool _in\n    )\n        public\n        pure\n        returns (\n            bytes memory _out\n        )\n    {\n        return Lib_RLPWriter.writeBool(_in);\n    }\n\n    function writeAddressWithTaintedMemory(\n        address _in\n    )\n        public\n        returns (\n            bytes memory _out\n        )\n    {\n        new TestERC20();\n        return Lib_RLPWriter.writeAddress(_in);\n    }\n}\n"
    },
    "contracts/test-helpers/TestERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n// a test ERC20 token with an open mint function\ncontract TestERC20 {\n    using SafeMath for uint;\n\n    string public constant name = 'Test';\n    string public constant symbol = 'TST';\n    uint8 public constant decimals = 18;\n    uint256  public totalSupply;\n    mapping(address => uint) public balanceOf;\n    mapping(address => mapping(address => uint)) public allowance;\n\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    constructor() {}\n\n    function mint(address to, uint256 value) public {\n        totalSupply = totalSupply.add(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(address(0), to, value);\n    }\n\n    function _approve(address owner, address spender, uint256 value) private {\n        allowance[owner][spender] = value;\n        emit Approval(owner, spender, value);\n    }\n\n    function _transfer(address from, address to, uint256 value) private {\n        balanceOf[from] = balanceOf[from].sub(value);\n        balanceOf[to] = balanceOf[to].add(value);\n        emit Transfer(from, to, value);\n    }\n\n    function approve(address spender, uint256 value) external returns (bool) {\n        _approve(msg.sender, spender, value);\n        return true;\n    }\n\n    function transfer(address to, uint256 value) external returns (bool) {\n        _transfer(msg.sender, to, value);\n        return true;\n    }\n\n    function transferFrom(address from, address to, uint256 value) external returns (bool) {\n        if (allowance[from][msg.sender] != uint(-1)) {\n            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\n        }\n        _transfer(from, to, value);\n        return true;\n    }\n}\n\nlibrary SafeMath {\n    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require((z = x + y) >= x, 'ds-math-add-overflow');\n    }\n\n    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require((z = x - y) <= x, 'ds-math-sub-underflow');\n    }\n\n    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');\n    }\n}\n"
    },
    "contracts/test-libraries/utils/TestLib_BytesUtils.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_BytesUtils } from \"../../optimistic-ethereum/libraries/utils/Lib_BytesUtils.sol\";\nimport { TestERC20 } from \"../../test-helpers/TestERC20.sol\";\n\n/**\n * @title TestLib_BytesUtils\n */\ncontract TestLib_BytesUtils {\n\n    function concat(\n        bytes memory _preBytes,\n        bytes memory _postBytes\n    )\n        public\n        pure\n        returns (bytes memory)\n    {\n        return abi.encodePacked(\n            _preBytes,\n            _postBytes\n        );\n    }\n\n    function slice(\n        bytes memory _bytes,\n        uint256 _start,\n        uint256 _length\n    )\n        public\n        pure\n        returns (bytes memory)\n    {\n        return Lib_BytesUtils.slice(\n            _bytes,\n            _start,\n            _length\n        );\n    }\n\n    function toBytes32(\n        bytes memory _bytes\n    )\n        public\n        pure\n        returns (bytes32)\n    {\n        return Lib_BytesUtils.toBytes32(\n            _bytes\n        );\n    }\n\n    function toUint256(\n        bytes memory _bytes\n    )\n        public\n        pure\n        returns (uint256)\n    {\n        return Lib_BytesUtils.toUint256(\n            _bytes\n        );\n    }\n\n    function toNibbles(\n        bytes memory _bytes\n    )\n        public\n        pure\n        returns (bytes memory)\n    {\n        return Lib_BytesUtils.toNibbles(\n            _bytes\n        );\n    }\n\n    function fromNibbles(\n        bytes memory _bytes\n    )\n        public\n        pure\n        returns (bytes memory)\n    {\n        return Lib_BytesUtils.fromNibbles(\n            _bytes\n        );\n    }\n\n    function equal(\n        bytes memory _bytes,\n        bytes memory _other\n    )\n        public\n        pure\n        returns (bool)\n    {\n        return Lib_BytesUtils.equal(\n            _bytes,\n            _other\n        );\n    }\n\n    function sliceWithTaintedMemory(\n        bytes memory _bytes,\n        uint256 _start,\n        uint256 _length\n    )\n        public\n        returns (bytes memory)\n    {\n        new TestERC20();\n        return Lib_BytesUtils.slice(\n            _bytes,\n            _start,\n            _length\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/utils/Lib_BytesUtils.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title Lib_BytesUtils\n */\nlibrary Lib_BytesUtils {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    function slice(\n        bytes memory _bytes,\n        uint256 _start,\n        uint256 _length\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        require(_length + 31 >= _length, \"slice_overflow\");\n        require(_start + _length >= _start, \"slice_overflow\");\n        require(_bytes.length >= _start + _length, \"slice_outOfBounds\");\n\n        bytes memory tempBytes;\n\n        assembly {\n            switch iszero(_length)\n            case 0 {\n                // Get a location of some free memory and store it in tempBytes as\n                // Solidity does for memory variables.\n                tempBytes := mload(0x40)\n\n                // The first word of the slice result is potentially a partial\n                // word read from the original array. To read it, we calculate\n                // the length of that partial word and start copying that many\n                // bytes into the array. The first word we copy will start with\n                // data we don't care about, but the last `lengthmod` bytes will\n                // land at the beginning of the contents of the new array. When\n                // we're done copying, we overwrite the full first word with\n                // the actual length of the slice.\n                let lengthmod := and(_length, 31)\n\n                // The multiplication in the next line is necessary\n                // because when slicing multiples of 32 bytes (lengthmod == 0)\n                // the following copy loop was copying the origin's length\n                // and then ending prematurely not copying everything it should.\n                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n                let end := add(mc, _length)\n\n                for {\n                    // The multiplication in the next line has the same exact purpose\n                    // as the one above.\n                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n                } lt(mc, end) {\n                    mc := add(mc, 0x20)\n                    cc := add(cc, 0x20)\n                } {\n                    mstore(mc, mload(cc))\n                }\n\n                mstore(tempBytes, _length)\n\n                //update free-memory pointer\n                //allocating the array padded to 32 bytes like the compiler does now\n                mstore(0x40, and(add(mc, 31), not(31)))\n            }\n            //if we want a zero-length slice let's just return a zero-length array\n            default {\n                tempBytes := mload(0x40)\n\n                //zero out the 32 bytes slice we are about to return\n                //we need to do it because Solidity does not garbage collect\n                mstore(tempBytes, 0)\n\n                mstore(0x40, add(tempBytes, 0x20))\n            }\n        }\n\n        return tempBytes;\n    }\n\n    function slice(\n        bytes memory _bytes,\n        uint256 _start\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        if (_start >= _bytes.length) {\n            return bytes('');\n        }\n\n        return slice(_bytes, _start, _bytes.length - _start);\n    }\n\n    function toBytes32PadLeft(\n        bytes memory _bytes\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        bytes32 ret;\n        uint256 len = _bytes.length <= 32 ? _bytes.length : 32;\n        assembly {\n            ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))\n        }\n        return ret;\n    }\n\n    function toBytes32(\n        bytes memory _bytes\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        if (_bytes.length < 32) {\n            bytes32 ret;\n            assembly {\n                ret := mload(add(_bytes, 32))\n            }\n            return ret;\n        }\n\n        return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes\n    }\n\n    function toUint256(\n        bytes memory _bytes\n    )\n        internal\n        pure\n        returns (\n            uint256\n        )\n    {\n        return uint256(toBytes32(_bytes));\n    }\n\n    function toUint24(\n        bytes memory _bytes,\n        uint256 _start\n    )\n        internal\n        pure\n        returns (\n            uint24\n        )\n    {\n        require(_start + 3 >= _start, \"toUint24_overflow\");\n        require(_bytes.length >= _start + 3 , \"toUint24_outOfBounds\");\n        uint24 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x3), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toUint8(\n        bytes memory _bytes,\n        uint256 _start\n    )\n        internal\n        pure\n        returns (\n            uint8\n        )\n    {\n        require(_start + 1 >= _start, \"toUint8_overflow\");\n        require(_bytes.length >= _start + 1 , \"toUint8_outOfBounds\");\n        uint8 tempUint;\n\n        assembly {\n            tempUint := mload(add(add(_bytes, 0x1), _start))\n        }\n\n        return tempUint;\n    }\n\n    function toAddress(\n        bytes memory _bytes,\n        uint256 _start\n    )\n        internal\n        pure\n        returns (\n            address\n        )\n    {\n        require(_start + 20 >= _start, \"toAddress_overflow\");\n        require(_bytes.length >= _start + 20, \"toAddress_outOfBounds\");\n        address tempAddress;\n\n        assembly {\n            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n        }\n\n        return tempAddress;\n    }\n\n    function toNibbles(\n        bytes memory _bytes\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory nibbles = new bytes(_bytes.length * 2);\n\n        for (uint256 i = 0; i < _bytes.length; i++) {\n            nibbles[i * 2] = _bytes[i] >> 4;\n            nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);\n        }\n\n        return nibbles;\n    }\n\n    function fromNibbles(\n        bytes memory _bytes\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory ret = new bytes(_bytes.length / 2);\n\n        for (uint256 i = 0; i < ret.length; i++) {\n            ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);\n        }\n\n        return ret;\n    }\n\n    function equal(\n        bytes memory _bytes,\n        bytes memory _other\n    )\n        internal\n        pure\n        returns (\n            bool\n        )\n    {\n        return keccak256(_bytes) == keccak256(_other);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/verification/OVM_StateTransitioner.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\nimport { Lib_EthUtils } from \"../../libraries/utils/Lib_EthUtils.sol\";\nimport { Lib_Bytes32Utils } from \"../../libraries/utils/Lib_Bytes32Utils.sol\";\nimport { Lib_BytesUtils } from \"../../libraries/utils/Lib_BytesUtils.sol\";\nimport { Lib_SecureMerkleTrie } from \"../../libraries/trie/Lib_SecureMerkleTrie.sol\";\nimport { Lib_RLPWriter } from \"../../libraries/rlp/Lib_RLPWriter.sol\";\nimport { Lib_RLPReader } from \"../../libraries/rlp/Lib_RLPReader.sol\";\n\n/* Interface Imports */\nimport { iOVM_StateTransitioner } from \"../../iOVM/verification/iOVM_StateTransitioner.sol\";\nimport { iOVM_BondManager } from \"../../iOVM/verification/iOVM_BondManager.sol\";\nimport { iOVM_ExecutionManager } from \"../../iOVM/execution/iOVM_ExecutionManager.sol\";\nimport { iOVM_StateManager } from \"../../iOVM/execution/iOVM_StateManager.sol\";\nimport { iOVM_StateManagerFactory } from \"../../iOVM/execution/iOVM_StateManagerFactory.sol\";\n\n/* Contract Imports */\nimport { Abs_FraudContributor } from \"./Abs_FraudContributor.sol\";\n\n/**\n * @title OVM_StateTransitioner\n * @dev The State Transitioner coordinates the execution of a state transition during the evaluation of a\n * fraud proof. It feeds verified input to the Execution Manager's run(), and controls a State Manager (which is\n * uniquely created for each fraud proof).\n * Once a fraud proof has been initialized, this contract is provided with the pre-state root and verifies\n * that the OVM storage slots committed to the State Mangager are contained in that state\n * This contract controls the State Manager and Execution Manager, and uses them to calculate the\n * post-state root by applying the transaction. The Fraud Verifier can then check for fraud by comparing\n * the calculated post-state root with the proposed post-state root.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner {\n\n    /*******************\n     * Data Structures *\n     *******************/\n\n    enum TransitionPhase {\n        PRE_EXECUTION,\n        POST_EXECUTION,\n        COMPLETE\n    }\n\n\n    /*******************************************\n     * Contract Variables: Contract References *\n     *******************************************/\n\n    iOVM_StateManager public ovmStateManager;\n\n\n    /*******************************************\n     * Contract Variables: Internal Accounting *\n     *******************************************/\n\n    bytes32 internal preStateRoot;\n    bytes32 internal postStateRoot;\n    TransitionPhase public phase;\n    uint256 internal stateTransitionIndex;\n    bytes32 internal transactionHash;\n\n\n    /*************\n     * Constants *\n     *************/\n\n    bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n    bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     * @param _stateTransitionIndex Index of the state transition being verified.\n     * @param _preStateRoot State root before the transition was executed.\n     * @param _transactionHash Hash of the executed transaction.\n     */\n    constructor(\n        address _libAddressManager,\n        uint256 _stateTransitionIndex,\n        bytes32 _preStateRoot,\n        bytes32 _transactionHash\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {\n        stateTransitionIndex = _stateTransitionIndex;\n        preStateRoot = _preStateRoot;\n        postStateRoot = _preStateRoot;\n        transactionHash = _transactionHash;\n\n        ovmStateManager = iOVM_StateManagerFactory(resolve(\"OVM_StateManagerFactory\")).create(address(this));\n    }\n\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    /**\n     * Checks that a function is only run during a specific phase.\n     * @param _phase Phase the function must run within.\n     */\n    modifier onlyDuringPhase(\n        TransitionPhase _phase\n    ) {\n        require(\n            phase == _phase,\n            \"Function must be called during the correct phase.\"\n        );\n        _;\n    }\n\n\n    /**********************************\n     * Public Functions: State Access *\n     **********************************/\n\n    /**\n     * Retrieves the state root before execution.\n     * @return _preStateRoot State root before execution.\n     */\n    function getPreStateRoot()\n        override\n        external\n        view\n        returns (\n            bytes32 _preStateRoot\n        )\n    {\n        return preStateRoot;\n    }\n\n    /**\n     * Retrieves the state root after execution.\n     * @return _postStateRoot State root after execution.\n     */\n    function getPostStateRoot()\n        override\n        external\n        view\n        returns (\n            bytes32 _postStateRoot\n        )\n    {\n        return postStateRoot;\n    }\n\n    /**\n     * Checks whether the transitioner is complete.\n     * @return _complete Whether or not the transition process is finished.\n     */\n    function isComplete()\n        override\n        external\n        view\n        returns (\n            bool _complete\n        )\n    {\n        return phase == TransitionPhase.COMPLETE;\n    }\n\n\n    /***********************************\n     * Public Functions: Pre-Execution *\n     ***********************************/\n\n    /**\n     * Allows a user to prove the initial state of a contract.\n     * @param _ovmContractAddress Address of the contract on the OVM.\n     * @param _ethContractAddress Address of the corresponding contract on L1.\n     * @param _stateTrieWitness Proof of the account state.\n     */\n    function proveContractState(\n        address _ovmContractAddress,\n        address _ethContractAddress,\n        bytes memory _stateTrieWitness\n    )\n        override\n        external\n        onlyDuringPhase(TransitionPhase.PRE_EXECUTION)\n        contributesToFraudProof(preStateRoot, transactionHash)\n    {\n        // Exit quickly to avoid unnecessary work.\n        require(\n            (\n                ovmStateManager.hasAccount(_ovmContractAddress) == false\n                && ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false\n            ),\n            \"Account state has already been proven.\"\n        );\n\n        // Function will fail if the proof is not a valid inclusion or exclusion proof.\n        (\n            bool exists,\n            bytes memory encodedAccount\n        ) = Lib_SecureMerkleTrie.get(\n            abi.encodePacked(_ovmContractAddress),\n            _stateTrieWitness,\n            preStateRoot\n        );\n\n        if (exists == true) {\n            // Account exists, this was an inclusion proof.\n            Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(\n                encodedAccount\n            );\n\n            address ethContractAddress = _ethContractAddress;\n            if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) {\n                // Use a known empty contract to prevent an attack in which a user provides a\n                // contract address here and then later deploys code to it.\n                ethContractAddress = 0x0000000000000000000000000000000000000000;\n            } else {\n                // Otherwise, make sure that the code at the provided eth address matches the hash\n                // of the code stored on L2.\n                require(\n                    Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash,\n                    \"OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash.\"\n                );\n            }\n\n            ovmStateManager.putAccount(\n                _ovmContractAddress,\n                Lib_OVMCodec.Account({\n                    nonce: account.nonce,\n                    balance: account.balance,\n                    storageRoot: account.storageRoot,\n                    codeHash: account.codeHash,\n                    ethAddress: ethContractAddress,\n                    isFresh: false\n                })\n            );\n        } else {\n            // Account does not exist, this was an exclusion proof.\n            ovmStateManager.putEmptyAccount(_ovmContractAddress);\n        }\n    }\n\n    /**\n     * Allows a user to prove the initial state of a contract storage slot.\n     * @param _ovmContractAddress Address of the contract on the OVM.\n     * @param _key Claimed account slot key.\n     * @param _storageTrieWitness Proof of the storage slot.\n     */\n    function proveStorageSlot(\n        address _ovmContractAddress,\n        bytes32 _key,\n        bytes memory _storageTrieWitness\n    )\n        override\n        external\n        onlyDuringPhase(TransitionPhase.PRE_EXECUTION)\n        contributesToFraudProof(preStateRoot, transactionHash)\n    {\n        // Exit quickly to avoid unnecessary work.\n        require(\n            ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false,\n            \"Storage slot has already been proven.\"\n        );\n\n        require(\n            ovmStateManager.hasAccount(_ovmContractAddress) == true,\n            \"Contract must be verified before proving a storage slot.\"\n        );\n\n        bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress);\n        bytes32 value;\n\n        if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) {\n            // Storage trie was empty, so the user is always allowed to insert zero-byte values.\n            value = bytes32(0);\n        } else {\n            // Function will fail if the proof is not a valid inclusion or exclusion proof.\n            (\n                bool exists,\n                bytes memory encodedValue\n            ) = Lib_SecureMerkleTrie.get(\n                abi.encodePacked(_key),\n                _storageTrieWitness,\n                storageRoot\n            );\n\n            if (exists == true) {\n                // Inclusion proof.\n                // Stored values are RLP encoded, with leading zeros removed.\n                value = Lib_BytesUtils.toBytes32PadLeft(\n                    Lib_RLPReader.readBytes(encodedValue)\n                );\n            } else {\n                // Exclusion proof, can only be zero bytes.\n                value = bytes32(0);\n            }\n        }\n\n        ovmStateManager.putContractStorage(\n            _ovmContractAddress,\n            _key,\n            value\n        );\n    }\n\n\n    /*******************************\n     * Public Functions: Execution *\n     *******************************/\n\n    /**\n     * Executes the state transition.\n     * @param _transaction OVM transaction to execute.\n     */\n    function applyTransaction(\n        Lib_OVMCodec.Transaction memory _transaction\n    )\n        override\n        external\n        onlyDuringPhase(TransitionPhase.PRE_EXECUTION)\n        contributesToFraudProof(preStateRoot, transactionHash)\n    {\n        require(\n            Lib_OVMCodec.hashTransaction(_transaction) == transactionHash,\n            \"Invalid transaction provided.\"\n        );\n\n        // We require gas to complete the logic here in run() before/after execution,\n        // But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism)\n        // This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first\n        // going into EM, then going into the code contract).\n        require(\n            gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, // 1032/1000 = 1.032 = (64/63)^2 rounded up\n            \"Not enough gas to execute transaction deterministically.\"\n        );\n\n        iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve(\"OVM_ExecutionManager\"));\n\n        // We call `setExecutionManager` right before `run` (and not earlier) just in case the\n        // OVM_ExecutionManager address was updated between the time when this contract was created\n        // and when `applyTransaction` was called.\n        ovmStateManager.setExecutionManager(address(ovmExecutionManager));\n\n        // `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction`\n        // or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line\n        // if that's the case.\n        ovmExecutionManager.run(_transaction, address(ovmStateManager));\n\n        // Prevent the Execution Manager from calling this SM again.\n        ovmStateManager.setExecutionManager(address(0));\n        phase = TransitionPhase.POST_EXECUTION;\n    }\n\n\n    /************************************\n     * Public Functions: Post-Execution *\n     ************************************/\n\n    /**\n     * Allows a user to commit the final state of a contract.\n     * @param _ovmContractAddress Address of the contract on the OVM.\n     * @param _stateTrieWitness Proof of the account state.\n     */\n    function commitContractState(\n        address _ovmContractAddress,\n        bytes memory _stateTrieWitness\n    )\n        override\n        external\n        onlyDuringPhase(TransitionPhase.POST_EXECUTION)\n        contributesToFraudProof(preStateRoot, transactionHash)\n    {\n        require(\n            ovmStateManager.getTotalUncommittedContractStorage() == 0,\n            \"All storage must be committed before committing account states.\"\n        );\n\n        require (\n            ovmStateManager.commitAccount(_ovmContractAddress) == true,\n            \"Account state wasn't changed or has already been committed.\"\n        );\n\n        Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);\n\n        postStateRoot = Lib_SecureMerkleTrie.update(\n            abi.encodePacked(_ovmContractAddress),\n            Lib_OVMCodec.encodeEVMAccount(\n                Lib_OVMCodec.toEVMAccount(account)\n            ),\n            _stateTrieWitness,\n            postStateRoot\n        );\n\n        // Emit an event to help clients figure out the proof ordering.\n        emit AccountCommitted(\n            _ovmContractAddress\n        );\n    }\n\n    /**\n     * Allows a user to commit the final state of a contract storage slot.\n     * @param _ovmContractAddress Address of the contract on the OVM.\n     * @param _key Claimed account slot key.\n     * @param _storageTrieWitness Proof of the storage slot.\n     */\n    function commitStorageSlot(\n        address _ovmContractAddress,\n        bytes32 _key,\n        bytes memory _storageTrieWitness\n    )\n        override\n        external\n        onlyDuringPhase(TransitionPhase.POST_EXECUTION)\n        contributesToFraudProof(preStateRoot, transactionHash)\n    {\n        require(\n            ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true,\n            \"Storage slot value wasn't changed or has already been committed.\"\n        );\n\n        Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);\n        bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key);\n\n        account.storageRoot = Lib_SecureMerkleTrie.update(\n            abi.encodePacked(_key),\n            Lib_RLPWriter.writeBytes(\n                Lib_Bytes32Utils.removeLeadingZeros(value)\n            ),\n            _storageTrieWitness,\n            account.storageRoot\n        );\n\n        ovmStateManager.putAccount(_ovmContractAddress, account);\n\n        // Emit an event to help clients figure out the proof ordering.\n        emit ContractStorageCommitted(\n            _ovmContractAddress,\n            _key\n        );\n    }\n\n\n    /**********************************\n     * Public Functions: Finalization *\n     **********************************/\n\n    /**\n     * Finalizes the transition process.\n     */\n    function completeTransition()\n        override\n        external\n        onlyDuringPhase(TransitionPhase.POST_EXECUTION)\n    {\n        require(\n            ovmStateManager.getTotalUncommittedAccounts() == 0,\n            \"All accounts must be committed before completing a transition.\"\n        );\n\n        require(\n            ovmStateManager.getTotalUncommittedContractStorage() == 0,\n            \"All storage must be committed before completing a transition.\"\n        );\n\n        phase = TransitionPhase.COMPLETE;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/codec/Lib_OVMCodec.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_RLPReader } from \"../rlp/Lib_RLPReader.sol\";\nimport { Lib_RLPWriter } from \"../rlp/Lib_RLPWriter.sol\";\nimport { Lib_BytesUtils } from \"../utils/Lib_BytesUtils.sol\";\nimport { Lib_Bytes32Utils } from \"../utils/Lib_Bytes32Utils.sol\";\n\n/**\n * @title Lib_OVMCodec\n */\nlibrary Lib_OVMCodec {\n\n    /*********\n     * Enums *\n     *********/\n\n    enum QueueOrigin {\n        SEQUENCER_QUEUE,\n        L1TOL2_QUEUE\n    }\n\n\n    /***********\n     * Structs *\n     ***********/\n\n    struct Account {\n        uint256 nonce;\n        uint256 balance;\n        bytes32 storageRoot;\n        bytes32 codeHash;\n        address ethAddress;\n        bool isFresh;\n    }\n\n    struct EVMAccount {\n        uint256 nonce;\n        uint256 balance;\n        bytes32 storageRoot;\n        bytes32 codeHash;\n    }\n\n    struct ChainBatchHeader {\n        uint256 batchIndex;\n        bytes32 batchRoot;\n        uint256 batchSize;\n        uint256 prevTotalElements;\n        bytes extraData;\n    }\n\n    struct ChainInclusionProof {\n        uint256 index;\n        bytes32[] siblings;\n    }\n\n    struct Transaction {\n        uint256 timestamp;\n        uint256 blockNumber;\n        QueueOrigin l1QueueOrigin;\n        address l1TxOrigin;\n        address entrypoint;\n        uint256 gasLimit;\n        bytes data;\n    }\n\n    struct TransactionChainElement {\n        bool isSequenced;\n        uint256 queueIndex;  // QUEUED TX ONLY\n        uint256 timestamp;   // SEQUENCER TX ONLY\n        uint256 blockNumber; // SEQUENCER TX ONLY\n        bytes txData;        // SEQUENCER TX ONLY\n    }\n\n    struct QueueElement {\n        bytes32 transactionHash;\n        uint40 timestamp;\n        uint40 blockNumber;\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Encodes a standard OVM transaction.\n     * @param _transaction OVM transaction to encode.\n     * @return Encoded transaction bytes.\n     */\n    function encodeTransaction(\n        Transaction memory _transaction\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return abi.encodePacked(\n            _transaction.timestamp,\n            _transaction.blockNumber,\n            _transaction.l1QueueOrigin,\n            _transaction.l1TxOrigin,\n            _transaction.entrypoint,\n            _transaction.gasLimit,\n            _transaction.data\n        );\n    }\n\n    /**\n     * Hashes a standard OVM transaction.\n     * @param _transaction OVM transaction to encode.\n     * @return Hashed transaction\n     */\n    function hashTransaction(\n        Transaction memory _transaction\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return keccak256(encodeTransaction(_transaction));\n    }\n\n    /**\n     * Converts an OVM account to an EVM account.\n     * @param _in OVM account to convert.\n     * @return Converted EVM account.\n     */\n    function toEVMAccount(\n        Account memory _in\n    )\n        internal\n        pure\n        returns (\n            EVMAccount memory\n        )\n    {\n        return EVMAccount({\n            nonce: _in.nonce,\n            balance: _in.balance,\n            storageRoot: _in.storageRoot,\n            codeHash: _in.codeHash\n        });\n    }\n\n    /**\n     * @notice RLP-encodes an account state struct.\n     * @param _account Account state struct.\n     * @return RLP-encoded account state.\n     */\n    function encodeEVMAccount(\n        EVMAccount memory _account\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        bytes[] memory raw = new bytes[](4);\n\n        // Unfortunately we can't create this array outright because\n        // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning\n        // index-by-index circumvents this issue.\n        raw[0] = Lib_RLPWriter.writeBytes(\n            Lib_Bytes32Utils.removeLeadingZeros(\n                bytes32(_account.nonce)\n            )\n        );\n        raw[1] = Lib_RLPWriter.writeBytes(\n            Lib_Bytes32Utils.removeLeadingZeros(\n                bytes32(_account.balance)\n            )\n        );\n        raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));\n        raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));\n\n        return Lib_RLPWriter.writeList(raw);\n    }\n\n    /**\n     * @notice Decodes an RLP-encoded account state into a useful struct.\n     * @param _encoded RLP-encoded account state.\n     * @return Account state struct.\n     */\n    function decodeEVMAccount(\n        bytes memory _encoded\n    )\n        internal\n        pure\n        returns (\n            EVMAccount memory\n        )\n    {\n        Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);\n\n        return EVMAccount({\n            nonce: Lib_RLPReader.readUint256(accountState[0]),\n            balance: Lib_RLPReader.readUint256(accountState[1]),\n            storageRoot: Lib_RLPReader.readBytes32(accountState[2]),\n            codeHash: Lib_RLPReader.readBytes32(accountState[3])\n        });\n    }\n\n    /**\n     * Calculates a hash for a given batch header.\n     * @param _batchHeader Header to hash.\n     * @return Hash of the header.\n     */\n    function hashBatchHeader(\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return keccak256(\n            abi.encode(\n                _batchHeader.batchRoot,\n                _batchHeader.batchSize,\n                _batchHeader.prevTotalElements,\n                _batchHeader.extraData\n            )\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/resolver/Lib_AddressResolver.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_AddressManager } from \"./Lib_AddressManager.sol\";\n\n/**\n * @title Lib_AddressResolver\n */\nabstract contract Lib_AddressResolver {\n\n    /*************\n     * Variables *\n     *************/\n\n    Lib_AddressManager public libAddressManager;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Lib_AddressManager.\n     */\n    constructor(\n        address _libAddressManager\n    ) {\n        libAddressManager = Lib_AddressManager(_libAddressManager);\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Resolves the address associated with a given name.\n     * @param _name Name to resolve an address for.\n     * @return Address associated with the given name.\n     */\n    function resolve(\n        string memory _name\n    )\n        public\n        view\n        returns (\n            address\n        )\n    {\n        return libAddressManager.getAddress(_name);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/utils/Lib_EthUtils.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_RLPWriter } from \"../rlp/Lib_RLPWriter.sol\";\nimport { Lib_Bytes32Utils } from \"./Lib_Bytes32Utils.sol\";\n\n/**\n * @title Lib_EthUtils\n */\nlibrary Lib_EthUtils {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Gets the code for a given address.\n     * @param _address Address to get code for.\n     * @param _offset Offset to start reading from.\n     * @param _length Number of bytes to read.\n     * @return Code read from the contract.\n     */\n    function getCode(\n        address _address,\n        uint256 _offset,\n        uint256 _length\n    )\n        internal\n        view\n        returns (\n            bytes memory\n        )\n    {\n        bytes memory code;\n        assembly {\n            code := mload(0x40)\n            mstore(0x40, add(code, add(_length, 0x20)))\n            mstore(code, _length)\n            extcodecopy(_address, add(code, 0x20), _offset, _length)\n        }\n\n        return code;\n    }\n\n    /**\n     * Gets the full code for a given address.\n     * @param _address Address to get code for.\n     * @return Full code of the contract.\n     */\n    function getCode(\n        address _address\n    )\n        internal\n        view\n        returns (\n            bytes memory\n        )\n    {\n        return getCode(\n            _address,\n            0,\n            getCodeSize(_address)\n        );\n    }\n\n    /**\n     * Gets the size of a contract's code in bytes.\n     * @param _address Address to get code size for.\n     * @return Size of the contract's code in bytes.\n     */\n    function getCodeSize(\n        address _address\n    )\n        internal\n        view\n        returns (\n            uint256\n        )\n    {\n        uint256 codeSize;\n        assembly {\n            codeSize := extcodesize(_address)\n        }\n\n        return codeSize;\n    }\n\n    /**\n     * Gets the hash of a contract's code.\n     * @param _address Address to get a code hash for.\n     * @return Hash of the contract's code.\n     */\n    function getCodeHash(\n        address _address\n    )\n        internal\n        view\n        returns (\n            bytes32\n        )\n    {\n        bytes32 codeHash;\n        assembly {\n            codeHash := extcodehash(_address)\n        }\n\n        return codeHash;\n    }\n\n    /**\n     * Creates a contract with some given initialization code.\n     * @param _code Contract initialization code.\n     * @return Address of the created contract.\n     */\n    function createContract(\n        bytes memory _code\n    )\n        internal\n        returns (\n            address\n        )\n    {\n        address created;\n        assembly {\n            created := create(\n                0,\n                add(_code, 0x20),\n                mload(_code)\n            )\n        }\n\n        return created;\n    }\n\n    /**\n     * Computes the address that would be generated by CREATE.\n     * @param _creator Address creating the contract.\n     * @param _nonce Creator's nonce.\n     * @return Address to be generated by CREATE.\n     */\n    function getAddressForCREATE(\n        address _creator,\n        uint256 _nonce\n    )\n        internal\n        pure\n        returns (\n            address\n        )\n    {\n        bytes[] memory encoded = new bytes[](2);\n        encoded[0] = Lib_RLPWriter.writeAddress(_creator);\n        encoded[1] = Lib_RLPWriter.writeUint(_nonce);\n\n        bytes memory encodedList = Lib_RLPWriter.writeList(encoded);\n        return Lib_Bytes32Utils.toAddress(keccak256(encodedList));\n    }\n\n    /**\n     * Computes the address that would be generated by CREATE2.\n     * @param _creator Address creating the contract.\n     * @param _bytecode Bytecode of the contract to be created.\n     * @param _salt 32 byte salt value mixed into the hash.\n     * @return Address to be generated by CREATE2.\n     */\n    function getAddressForCREATE2(\n        address _creator,\n        bytes memory _bytecode,\n        bytes32 _salt\n    )\n        internal\n        pure\n        returns (\n            address\n        )\n    {\n        bytes32 hashedData = keccak256(abi.encodePacked(\n            byte(0xff),\n            _creator,\n            _salt,\n            keccak256(_bytecode)\n        ));\n\n        return Lib_Bytes32Utils.toAddress(hashedData);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/trie/Lib_SecureMerkleTrie.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_MerkleTrie } from \"./Lib_MerkleTrie.sol\";\n\n/**\n * @title Lib_SecureMerkleTrie\n */\nlibrary Lib_SecureMerkleTrie {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * @notice Verifies a proof that a given key/value pair is present in the\n     * Merkle trie.\n     * @param _key Key of the node to search for, as a hex string.\n     * @param _value Value of the node to search for, as a hex string.\n     * @param _proof Merkle trie inclusion proof for the desired node. Unlike\n     * traditional Merkle trees, this proof is executed top-down and consists\n     * of a list of RLP-encoded nodes that make a path down to the target node.\n     * @param _root Known root of the Merkle trie. Used to verify that the\n     * included proof is correctly constructed.\n     * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.\n     */\n    function verifyInclusionProof(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (\n            bool _verified\n        )\n    {\n        bytes memory key = _getSecureKey(_key);\n        return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);\n    }\n\n    /**\n     * @notice Updates a Merkle trie and returns a new root hash.\n     * @param _key Key of the node to update, as a hex string.\n     * @param _value Value of the node to update, as a hex string.\n     * @param _proof Merkle trie inclusion proof for the node *nearest* the\n     * target node. If the key exists, we can simply update the value.\n     * Otherwise, we need to modify the trie to handle the new k/v pair.\n     * @param _root Known root of the Merkle trie. Used to verify that the\n     * included proof is correctly constructed.\n     * @return _updatedRoot Root hash of the newly constructed trie.\n     */\n    function update(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (\n            bytes32 _updatedRoot\n        )\n    {\n        bytes memory key = _getSecureKey(_key);\n        return Lib_MerkleTrie.update(key, _value, _proof, _root);\n    }\n\n    /**\n     * @notice Retrieves the value associated with a given key.\n     * @param _key Key to search for, as hex bytes.\n     * @param _proof Merkle trie inclusion proof for the key.\n     * @param _root Known root of the Merkle trie.\n     * @return _exists Whether or not the key exists.\n     * @return _value Value of the key if it exists.\n     */\n    function get(\n        bytes memory _key,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (\n            bool _exists,\n            bytes memory _value\n        )\n    {\n        bytes memory key = _getSecureKey(_key);\n        return Lib_MerkleTrie.get(key, _proof, _root);\n    }\n\n    /**\n     * Computes the root hash for a trie with a single node.\n     * @param _key Key for the single node.\n     * @param _value Value for the single node.\n     * @return _updatedRoot Hash of the trie.\n     */\n    function getSingleNodeRootHash(\n        bytes memory _key,\n        bytes memory _value\n    )\n        internal\n        pure\n        returns (\n            bytes32 _updatedRoot\n        )\n    {\n        bytes memory key = _getSecureKey(_key);\n        return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);\n    }\n\n\n    /*********************\n     * Private Functions *\n     *********************/\n\n    /**\n     * Computes the secure counterpart to a key.\n     * @param _key Key to get a secure key from.\n     * @return _secureKey Secure version of the key.\n     */\n    function _getSecureKey(\n        bytes memory _key\n    )\n        private\n        pure\n        returns (\n            bytes memory _secureKey\n        )\n    {\n        return abi.encodePacked(keccak256(_key));\n    }\n}"
    },
    "contracts/optimistic-ethereum/iOVM/verification/iOVM_StateTransitioner.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\n\n/**\n * @title iOVM_StateTransitioner\n */\ninterface iOVM_StateTransitioner {\n\n    /**********\n     * Events *\n     **********/\n\n    event AccountCommitted(\n        address _address\n    );\n\n    event ContractStorageCommitted(\n        address _address,\n        bytes32 _key\n    );\n\n\n    /**********************************\n     * Public Functions: State Access *\n     **********************************/\n\n    function getPreStateRoot() external view returns (bytes32 _preStateRoot);\n    function getPostStateRoot() external view returns (bytes32 _postStateRoot);\n    function isComplete() external view returns (bool _complete);\n\n\n    /***********************************\n     * Public Functions: Pre-Execution *\n     ***********************************/\n\n    function proveContractState(\n        address _ovmContractAddress,\n        address _ethContractAddress,\n        bytes calldata _stateTrieWitness\n    ) external;\n\n    function proveStorageSlot(\n        address _ovmContractAddress,\n        bytes32 _key,\n        bytes calldata _storageTrieWitness\n    ) external;\n\n\n    /*******************************\n     * Public Functions: Execution *\n     *******************************/\n\n    function applyTransaction(\n        Lib_OVMCodec.Transaction calldata _transaction\n    ) external;\n\n\n    /************************************\n     * Public Functions: Post-Execution *\n     ************************************/\n\n    function commitContractState(\n        address _ovmContractAddress,\n        bytes calldata _stateTrieWitness\n    ) external;\n\n    function commitStorageSlot(\n        address _ovmContractAddress,\n        bytes32 _key,\n        bytes calldata _storageTrieWitness\n    ) external;\n\n\n    /**********************************\n     * Public Functions: Finalization *\n     **********************************/\n\n    function completeTransition() external;\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/verification/iOVM_BondManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\ninterface ERC20 {\n    function transfer(address, uint256) external returns (bool);\n    function transferFrom(address, address, uint256) external returns (bool);\n}\n\n/// All the errors which may be encountered on the bond manager\nlibrary Errors {\n    string constant ERC20_ERR = \"BondManager: Could not post bond\";\n    string constant ALREADY_FINALIZED = \"BondManager: Fraud proof for this pre-state root has already been finalized\";\n    string constant SLASHED = \"BondManager: Cannot finalize withdrawal, you probably got slashed\";\n    string constant WRONG_STATE = \"BondManager: Wrong bond state for proposer\";\n    string constant CANNOT_CLAIM = \"BondManager: Cannot claim yet. Dispute must be finalized first\";\n\n    string constant WITHDRAWAL_PENDING = \"BondManager: Withdrawal already pending\";\n    string constant TOO_EARLY = \"BondManager: Too early to finalize your withdrawal\";\n\n    string constant ONLY_TRANSITIONER = \"BondManager: Only the transitioner for this pre-state root may call this function\";\n    string constant ONLY_FRAUD_VERIFIER = \"BondManager: Only the fraud verifier may call this function\";\n    string constant ONLY_STATE_COMMITMENT_CHAIN = \"BondManager: Only the state commitment chain may call this function\";\n    string constant WAIT_FOR_DISPUTES = \"BondManager: Wait for other potential disputes\";\n}\n\n/**\n * @title iOVM_BondManager\n */\ninterface iOVM_BondManager {\n\n    /*******************\n     * Data Structures *\n     *******************/\n\n    /// The lifecycle of a proposer's bond\n    enum State {\n        // Before depositing or after getting slashed, a user is uncollateralized\n        NOT_COLLATERALIZED,\n        // After depositing, a user is collateralized\n        COLLATERALIZED,\n        // After a user has initiated a withdrawal\n        WITHDRAWING\n    }\n\n    /// A bond posted by a proposer\n    struct Bond {\n        // The user's state\n        State state;\n        // The timestamp at which a proposer issued their withdrawal request\n        uint32 withdrawalTimestamp;\n        // The time when the first disputed was initiated for this bond\n        uint256 firstDisputeAt;\n        // The earliest observed state root for this bond which has had fraud\n        bytes32 earliestDisputedStateRoot;\n        // The state root's timestamp\n        uint256 earliestTimestamp;\n    }\n\n    // Per pre-state root, store the number of state provisions that were made\n    // and how many of these calls were made by each user. Payouts will then be\n    // claimed by users proportionally for that dispute.\n    struct Rewards {\n        // Flag to check if rewards for a fraud proof are claimable\n        bool canClaim;\n        // Total number of `recordGasSpent` calls made\n        uint256 total;\n        // The gas spent by each user to provide witness data. The sum of all\n        // values inside this map MUST be equal to the value of `total`\n        mapping(address => uint256) gasSpent;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function recordGasSpent(\n        bytes32 _preStateRoot,\n        bytes32 _txHash,\n        address _who,\n        uint256 _gasSpent\n    ) external;\n\n    function finalize(\n        bytes32 _preStateRoot,\n        address _publisher,\n        uint256 _timestamp\n    ) external;\n\n    function deposit() external;\n\n    function startWithdrawal() external;\n\n    function finalizeWithdrawal() external;\n\n    function claim(\n        address _who\n    ) external;\n\n    function isCollateralized(\n        address _who\n    ) external view returns (bool);\n\n    function getGasSpent(\n        bytes32 _preStateRoot,\n        address _who\n    ) external view returns (uint256);\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/execution/iOVM_ExecutionManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\n\ninterface iOVM_ExecutionManager {\n    /**********\n     * Enums *\n     *********/\n\n    enum RevertFlag {\n        OUT_OF_GAS,\n        INTENTIONAL_REVERT,\n        EXCEEDS_NUISANCE_GAS,\n        INVALID_STATE_ACCESS,\n        UNSAFE_BYTECODE,\n        CREATE_COLLISION,\n        STATIC_VIOLATION,\n        CREATOR_NOT_ALLOWED\n    }\n\n    enum GasMetadataKey {\n        CURRENT_EPOCH_START_TIMESTAMP,\n        CUMULATIVE_SEQUENCER_QUEUE_GAS,\n        CUMULATIVE_L1TOL2_QUEUE_GAS,\n        PREV_EPOCH_SEQUENCER_QUEUE_GAS,\n        PREV_EPOCH_L1TOL2_QUEUE_GAS\n    }\n\n    enum MessageType {\n        ovmCALL,\n        ovmSTATICCALL,\n        ovmDELEGATECALL,\n        ovmCREATE,\n        ovmCREATE2\n    }\n\n    /***********\n     * Structs *\n     ***********/\n\n    struct GasMeterConfig {\n        uint256 minTransactionGasLimit;\n        uint256 maxTransactionGasLimit;\n        uint256 maxGasPerQueuePerEpoch;\n        uint256 secondsPerEpoch;\n    }\n\n    struct GlobalContext {\n        uint256 ovmCHAINID;\n    }\n\n    struct TransactionContext {\n        Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN;\n        uint256 ovmTIMESTAMP;\n        uint256 ovmNUMBER;\n        uint256 ovmGASLIMIT;\n        uint256 ovmTXGASLIMIT;\n        address ovmL1TXORIGIN;\n    }\n\n    struct TransactionRecord {\n        uint256 ovmGasRefund;\n    }\n\n    struct MessageContext {\n        address ovmCALLER;\n        address ovmADDRESS;\n        uint256 ovmCALLVALUE;\n        bool isStatic;\n    }\n\n    struct MessageRecord {\n        uint256 nuisanceGasLeft;\n    }\n\n\n    /************************************\n     * Transaction Execution Entrypoint *\n     ************************************/\n\n    function run(\n        Lib_OVMCodec.Transaction calldata _transaction,\n        address _txStateManager\n    ) external returns (bytes memory);\n\n\n    /*******************\n     * Context Opcodes *\n     *******************/\n\n    function ovmCALLER() external view returns (address _caller);\n    function ovmADDRESS() external view returns (address _address);\n    function ovmCALLVALUE() external view returns (uint _callValue);\n    function ovmTIMESTAMP() external view returns (uint256 _timestamp);\n    function ovmNUMBER() external view returns (uint256 _number);\n    function ovmGASLIMIT() external view returns (uint256 _gasLimit);\n    function ovmCHAINID() external view returns (uint256 _chainId);\n\n\n    /**********************\n     * L2 Context Opcodes *\n     **********************/\n\n    function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin);\n    function ovmL1TXORIGIN() external view returns (address _l1TxOrigin);\n\n\n    /*******************\n     * Halting Opcodes *\n     *******************/\n\n    function ovmREVERT(bytes memory _data) external;\n\n\n    /*****************************\n     * Contract Creation Opcodes *\n     *****************************/\n\n    function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata);\n    function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata);\n\n\n    /*******************************\n     * Account Abstraction Opcodes *\n     ******************************/\n\n    function ovmGETNONCE() external returns (uint256 _nonce);\n    function ovmINCREMENTNONCE() external;\n    function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external;\n\n\n    /****************************\n     * Contract Calling Opcodes *\n     ****************************/\n\n    // Valueless ovmCALL for maintaining backwards compatibility with legacy OVM bytecode.\n    function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);\n    function ovmCALL(uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);\n    function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);\n    function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);\n\n\n    /****************************\n     * Contract Storage Opcodes *\n     ****************************/\n\n    function ovmSLOAD(bytes32 _key) external returns (bytes32 _value);\n    function ovmSSTORE(bytes32 _key, bytes32 _value) external;\n\n\n    /*************************\n     * Contract Code Opcodes *\n     *************************/\n\n    function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code);\n    function ovmEXTCODESIZE(address _contract) external returns (uint256 _size);\n    function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash);\n\n\n    /*********************\n     * ETH Value Opcodes *\n     *********************/\n\n    function ovmBALANCE(address _contract) external returns (uint256 _balance);\n    function ovmSELFBALANCE() external returns (uint256 _balance);\n\n\n    /***************************************\n     * Public Functions: Execution Context *\n     ***************************************/\n\n    function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit);\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/execution/iOVM_StateManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\n\n/**\n * @title iOVM_StateManager\n */\ninterface iOVM_StateManager {\n\n    /*******************\n     * Data Structures *\n     *******************/\n\n    enum ItemState {\n        ITEM_UNTOUCHED,\n        ITEM_LOADED,\n        ITEM_CHANGED,\n        ITEM_COMMITTED\n    }\n\n    /***************************\n     * Public Functions: Misc *\n     ***************************/\n\n    function isAuthenticated(address _address) external view returns (bool);\n\n    /***************************\n     * Public Functions: Setup *\n     ***************************/\n\n    function owner() external view returns (address _owner);\n    function ovmExecutionManager() external view returns (address _ovmExecutionManager);\n    function setExecutionManager(address _ovmExecutionManager) external;\n\n\n    /************************************\n     * Public Functions: Account Access *\n     ************************************/\n\n    function putAccount(address _address, Lib_OVMCodec.Account memory _account) external;\n    function putEmptyAccount(address _address) external;\n    function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account);\n    function hasAccount(address _address) external view returns (bool _exists);\n    function hasEmptyAccount(address _address) external view returns (bool _exists);\n    function setAccountNonce(address _address, uint256 _nonce) external;\n    function getAccountNonce(address _address) external view returns (uint256 _nonce);\n    function getAccountEthAddress(address _address) external view returns (address _ethAddress);\n    function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);\n    function initPendingAccount(address _address) external;\n    function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external;\n    function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded);\n    function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged);\n    function commitAccount(address _address) external returns (bool _wasAccountCommitted);\n    function incrementTotalUncommittedAccounts() external;\n    function getTotalUncommittedAccounts() external view returns (uint256 _total);\n    function wasAccountChanged(address _address) external view returns (bool);\n    function wasAccountCommitted(address _address) external view returns (bool);\n\n\n    /************************************\n     * Public Functions: Storage Access *\n     ************************************/\n\n    function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;\n    function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value);\n    function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists);\n    function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded);\n    function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged);\n    function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted);\n    function incrementTotalUncommittedContractStorage() external;\n    function getTotalUncommittedContractStorage() external view returns (uint256 _total);\n    function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool);\n    function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool);\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/execution/iOVM_StateManagerFactory.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Contract Imports */\nimport { iOVM_StateManager } from \"./iOVM_StateManager.sol\";\n\n/**\n * @title iOVM_StateManagerFactory\n */\ninterface iOVM_StateManagerFactory {\n\n    /***************************************\n     * Public Functions: Contract Creation *\n     ***************************************/\n\n    function create(\n        address _owner\n    )\n        external\n        returns (\n            iOVM_StateManager _ovmStateManager\n        );\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/verification/Abs_FraudContributor.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\nimport { iOVM_BondManager } from \"../../iOVM/verification/iOVM_BondManager.sol\";\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\n\n/// Minimal contract to be inherited by contracts consumed by users that provide\n/// data for fraud proofs\nabstract contract Abs_FraudContributor is Lib_AddressResolver {\n    /// Decorate your functions with this modifier to store how much total gas was\n    /// consumed by the sender, to reward users fairly\n    modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) {\n        uint256 startGas = gasleft();\n        _;\n        uint256 gasSpent = startGas - gasleft();\n        iOVM_BondManager(resolve('OVM_BondManager')).recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/resolver/Lib_AddressManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* External Imports */\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/**\n * @title Lib_AddressManager\n */\ncontract Lib_AddressManager is Ownable {\n\n    /**********\n     * Events *\n     **********/\n\n    event AddressSet(\n        string indexed _name,\n        address _newAddress,\n        address _oldAddress\n    );\n\n\n    /*************\n     * Variables *\n     *************/\n\n    mapping (bytes32 => address) private addresses;\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Changes the address associated with a particular name.\n     * @param _name String name to associate an address with.\n     * @param _address Address to associate with the name.\n     */\n    function setAddress(\n        string memory _name,\n        address _address\n    )\n        external\n        onlyOwner\n    {\n        bytes32 nameHash = _getNameHash(_name);\n        address oldAddress = addresses[nameHash];\n        addresses[nameHash] = _address;\n\n        emit AddressSet(\n            _name,\n            _address,\n            oldAddress\n        );\n    }\n\n    /**\n     * Retrieves the address associated with a given name.\n     * @param _name Name to retrieve an address for.\n     * @return Address associated with the given name.\n     */\n    function getAddress(\n        string memory _name\n    )\n        external\n        view\n        returns (\n            address\n        )\n    {\n        return addresses[_getNameHash(_name)];\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Computes the hash of a name.\n     * @param _name Name to compute a hash for.\n     * @return Hash of the given name.\n     */\n    function _getNameHash(\n        string memory _name\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return keccak256(abi.encodePacked(_name));\n    }\n}\n"
    },
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor () internal {\n        address msgSender = _msgSender();\n        _owner = msgSender;\n        emit OwnershipTransferred(address(0), msgSender);\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        _;\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        emit OwnershipTransferred(_owner, address(0));\n        _owner = address(0);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        emit OwnershipTransferred(_owner, newOwner);\n        _owner = newOwner;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/trie/Lib_MerkleTrie.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_BytesUtils } from \"../utils/Lib_BytesUtils.sol\";\nimport { Lib_RLPReader } from \"../rlp/Lib_RLPReader.sol\";\nimport { Lib_RLPWriter } from \"../rlp/Lib_RLPWriter.sol\";\n\n/**\n * @title Lib_MerkleTrie\n */\nlibrary Lib_MerkleTrie {\n\n    /*******************\n     * Data Structures *\n     *******************/\n\n    enum NodeType {\n        BranchNode,\n        ExtensionNode,\n        LeafNode\n    }\n\n    struct TrieNode {\n        bytes encoded;\n        Lib_RLPReader.RLPItem[] decoded;\n    }\n\n\n    /**********************\n     * Contract Constants *\n     **********************/\n\n    // TREE_RADIX determines the number of elements per branch node.\n    uint256 constant TREE_RADIX = 16;\n    // Branch nodes have TREE_RADIX elements plus an additional `value` slot.\n    uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;\n    // Leaf nodes and extension nodes always have two elements, a `path` and a `value`.\n    uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;\n\n    // Prefixes are prepended to the `path` within a leaf or extension node and\n    // allow us to differentiate between the two node types. `ODD` or `EVEN` is\n    // determined by the number of nibbles within the unprefixed `path`. If the\n    // number of nibbles if even, we need to insert an extra padding nibble so\n    // the resulting prefixed `path` has an even number of nibbles.\n    uint8 constant PREFIX_EXTENSION_EVEN = 0;\n    uint8 constant PREFIX_EXTENSION_ODD = 1;\n    uint8 constant PREFIX_LEAF_EVEN = 2;\n    uint8 constant PREFIX_LEAF_ODD = 3;\n\n    // Just a utility constant. RLP represents `NULL` as 0x80.\n    bytes1 constant RLP_NULL = bytes1(0x80);\n    bytes constant RLP_NULL_BYTES = hex'80';\n    bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * @notice Verifies a proof that a given key/value pair is present in the\n     * Merkle trie.\n     * @param _key Key of the node to search for, as a hex string.\n     * @param _value Value of the node to search for, as a hex string.\n     * @param _proof Merkle trie inclusion proof for the desired node. Unlike\n     * traditional Merkle trees, this proof is executed top-down and consists\n     * of a list of RLP-encoded nodes that make a path down to the target node.\n     * @param _root Known root of the Merkle trie. Used to verify that the\n     * included proof is correctly constructed.\n     * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.\n     */\n    function verifyInclusionProof(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (\n            bool _verified\n        )\n    {\n        (\n            bool exists,\n            bytes memory value\n        ) = get(_key, _proof, _root);\n\n        return (\n            exists && Lib_BytesUtils.equal(_value, value)\n        );\n    }\n\n    /**\n     * @notice Updates a Merkle trie and returns a new root hash.\n     * @param _key Key of the node to update, as a hex string.\n     * @param _value Value of the node to update, as a hex string.\n     * @param _proof Merkle trie inclusion proof for the node *nearest* the\n     * target node. If the key exists, we can simply update the value.\n     * Otherwise, we need to modify the trie to handle the new k/v pair.\n     * @param _root Known root of the Merkle trie. Used to verify that the\n     * included proof is correctly constructed.\n     * @return _updatedRoot Root hash of the newly constructed trie.\n     */\n    function update(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (\n            bytes32 _updatedRoot\n        )\n    {\n        // Special case when inserting the very first node.\n        if (_root == KECCAK256_RLP_NULL_BYTES) {\n            return getSingleNodeRootHash(_key, _value);\n        }\n\n        TrieNode[] memory proof = _parseProof(_proof);\n        (uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root);\n        TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value);\n\n        return _getUpdatedTrieRoot(newPath, _key);\n    }\n\n    /**\n     * @notice Retrieves the value associated with a given key.\n     * @param _key Key to search for, as hex bytes.\n     * @param _proof Merkle trie inclusion proof for the key.\n     * @param _root Known root of the Merkle trie.\n     * @return _exists Whether or not the key exists.\n     * @return _value Value of the key if it exists.\n     */\n    function get(\n        bytes memory _key,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (\n            bool _exists,\n            bytes memory _value\n        )\n    {\n        TrieNode[] memory proof = _parseProof(_proof);\n        (uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root);\n\n        bool exists = keyRemainder.length == 0;\n\n        require(\n            exists || isFinalNode,\n            \"Provided proof is invalid.\"\n        );\n\n        bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes('');\n\n        return (\n            exists,\n            value\n        );\n    }\n\n    /**\n     * Computes the root hash for a trie with a single node.\n     * @param _key Key for the single node.\n     * @param _value Value for the single node.\n     * @return _updatedRoot Hash of the trie.\n     */\n    function getSingleNodeRootHash(\n        bytes memory _key,\n        bytes memory _value\n    )\n        internal\n        pure\n        returns (\n            bytes32 _updatedRoot\n        )\n    {\n        return keccak256(_makeLeafNode(\n            Lib_BytesUtils.toNibbles(_key),\n            _value\n        ).encoded);\n    }\n\n\n    /*********************\n     * Private Functions *\n     *********************/\n\n    /**\n     * @notice Walks through a proof using a provided key.\n     * @param _proof Inclusion proof to walk through.\n     * @param _key Key to use for the walk.\n     * @param _root Known root of the trie.\n     * @return _pathLength Length of the final path\n     * @return _keyRemainder Portion of the key remaining after the walk.\n     * @return _isFinalNode Whether or not we've hit a dead end.\n     */\n    function _walkNodePath(\n        TrieNode[] memory _proof,\n        bytes memory _key,\n        bytes32 _root\n    )\n        private\n        pure\n        returns (\n            uint256 _pathLength,\n            bytes memory _keyRemainder,\n            bool _isFinalNode\n        )\n    {\n        uint256 pathLength = 0;\n        bytes memory key = Lib_BytesUtils.toNibbles(_key);\n\n        bytes32 currentNodeID = _root;\n        uint256 currentKeyIndex = 0;\n        uint256 currentKeyIncrement = 0;\n        TrieNode memory currentNode;\n\n        // Proof is top-down, so we start at the first element (root).\n        for (uint256 i = 0; i < _proof.length; i++) {\n            currentNode = _proof[i];\n            currentKeyIndex += currentKeyIncrement;\n\n            // Keep track of the proof elements we actually need.\n            // It's expensive to resize arrays, so this simply reduces gas costs.\n            pathLength += 1;\n\n            if (currentKeyIndex == 0) {\n                // First proof element is always the root node.\n                require(\n                    keccak256(currentNode.encoded) == currentNodeID,\n                    \"Invalid root hash\"\n                );\n            } else if (currentNode.encoded.length >= 32) {\n                // Nodes 32 bytes or larger are hashed inside branch nodes.\n                require(\n                    keccak256(currentNode.encoded) == currentNodeID,\n                    \"Invalid large internal hash\"\n                );\n            } else {\n                // Nodes smaller than 31 bytes aren't hashed.\n                require(\n                    Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID,\n                    \"Invalid internal node hash\"\n                );\n            }\n\n            if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {\n                if (currentKeyIndex == key.length) {\n                    // We've hit the end of the key, meaning the value should be within this branch node.\n                    break;\n                } else {\n                    // We're not at the end of the key yet.\n                    // Figure out what the next node ID should be and continue.\n                    uint8 branchKey = uint8(key[currentKeyIndex]);\n                    Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];\n                    currentNodeID = _getNodeID(nextNode);\n                    currentKeyIncrement = 1;\n                    continue;\n                }\n            } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {\n                bytes memory path = _getNodePath(currentNode);\n                uint8 prefix = uint8(path[0]);\n                uint8 offset = 2 - prefix % 2;\n                bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);\n                bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);\n                uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);\n\n                if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {\n                    if (\n                        pathRemainder.length == sharedNibbleLength &&\n                        keyRemainder.length == sharedNibbleLength\n                    ) {\n                        // The key within this leaf matches our key exactly.\n                        // Increment the key index to reflect that we have no remainder.\n                        currentKeyIndex += sharedNibbleLength;\n                    }\n\n                    // We've hit a leaf node, so our next node should be NULL.\n                    currentNodeID = bytes32(RLP_NULL);\n                    break;\n                } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {\n                    if (sharedNibbleLength != pathRemainder.length) {\n                        // Our extension node is not identical to the remainder.\n                        // We've hit the end of this path, updates will need to modify this extension.\n                        currentNodeID = bytes32(RLP_NULL);\n                        break;\n                    } else {\n                        // Our extension shares some nibbles.\n                        // Carry on to the next node.\n                        currentNodeID = _getNodeID(currentNode.decoded[1]);\n                        currentKeyIncrement = sharedNibbleLength;\n                        continue;\n                    }\n                } else {\n                    revert(\"Received a node with an unknown prefix\");\n                }\n            } else {\n                revert(\"Received an unparseable node.\");\n            }\n        }\n\n        // If our node ID is NULL, then we're at a dead end.\n        bool isFinalNode = currentNodeID == bytes32(RLP_NULL);\n        return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode);\n    }\n\n    /**\n     * @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path.\n     * @param _path Path to the node nearest the k/v pair.\n     * @param _pathLength Length of the path. Necessary because the provided path may include\n     *  additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory\n     *  arrays without costly duplication.\n     * @param _key Full original key.\n     * @param _keyRemainder Portion of the initial key that must be inserted into the trie.\n     * @param _value Value to insert at the given key.\n     * @return _newPath A new path with the inserted k/v pair and extra supporting nodes.\n     */\n    function _getNewPath(\n        TrieNode[] memory _path,\n        uint256 _pathLength,\n        bytes memory _key,\n        bytes memory _keyRemainder,\n        bytes memory _value\n    )\n        private\n        pure\n        returns (\n            TrieNode[] memory _newPath\n        )\n    {\n        bytes memory keyRemainder = _keyRemainder;\n\n        // Most of our logic depends on the status of the last node in the path.\n        TrieNode memory lastNode = _path[_pathLength - 1];\n        NodeType lastNodeType = _getNodeType(lastNode);\n\n        // Create an array for newly created nodes.\n        // We need up to three new nodes, depending on the contents of the last node.\n        // Since array resizing is expensive, we'll keep track of the size manually.\n        // We're using an explicit `totalNewNodes += 1` after insertions for clarity.\n        TrieNode[] memory newNodes = new TrieNode[](3);\n        uint256 totalNewNodes = 0;\n\n        // Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313\n        bool matchLeaf = false;\n        if (lastNodeType == NodeType.LeafNode) {\n            uint256 l = 0;\n            if (_path.length > 0) {\n                for (uint256 i = 0; i < _path.length - 1; i++) {\n                    if (_getNodeType(_path[i]) == NodeType.BranchNode) {\n                        l++;\n                    } else {\n                        l += _getNodeKey(_path[i]).length;\n                    }\n                }\n            }\n\n            if (\n                _getSharedNibbleLength(\n                    _getNodeKey(lastNode),\n                    Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)\n                ) == _getNodeKey(lastNode).length\n                && keyRemainder.length == 0\n            ) {\n                matchLeaf = true;\n            }\n        }\n\n        if (matchLeaf) {\n            // We've found a leaf node with the given key.\n            // Simply need to update the value of the node to match.\n            newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value);\n            totalNewNodes += 1;\n        } else if (lastNodeType == NodeType.BranchNode) {\n            if (keyRemainder.length == 0) {\n                // We've found a branch node with the given key.\n                // Simply need to update the value of the node to match.\n                newNodes[totalNewNodes] = _editBranchValue(lastNode, _value);\n                totalNewNodes += 1;\n            } else {\n                // We've found a branch node, but it doesn't contain our key.\n                // Reinsert the old branch for now.\n                newNodes[totalNewNodes] = lastNode;\n                totalNewNodes += 1;\n                // Create a new leaf node, slicing our remainder since the first byte points\n                // to our branch node.\n                newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value);\n                totalNewNodes += 1;\n            }\n        } else {\n            // Our last node is either an extension node or a leaf node with a different key.\n            bytes memory lastNodeKey = _getNodeKey(lastNode);\n            uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder);\n\n            if (sharedNibbleLength != 0) {\n                // We've got some shared nibbles between the last node and our key remainder.\n                // We'll need to insert an extension node that covers these shared nibbles.\n                bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);\n                newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));\n                totalNewNodes += 1;\n\n                // Cut down the keys since we've just covered these shared nibbles.\n                lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength);\n                keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength);\n            }\n\n            // Create an empty branch to fill in.\n            TrieNode memory newBranch = _makeEmptyBranchNode();\n\n            if (lastNodeKey.length == 0) {\n                // Key remainder was larger than the key for our last node.\n                // The value within our last node is therefore going to be shifted into\n                // a branch value slot.\n                newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));\n            } else {\n                // Last node key was larger than the key remainder.\n                // We're going to modify some index of our branch.\n                uint8 branchKey = uint8(lastNodeKey[0]);\n                // Move on to the next nibble.\n                lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1);\n\n                if (lastNodeType == NodeType.LeafNode) {\n                    // We're dealing with a leaf node.\n                    // We'll modify the key and insert the old leaf node into the branch index.\n                    TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode));\n                    newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));\n                } else if (lastNodeKey.length != 0) {\n                    // We're dealing with a shrinking extension node.\n                    // We need to modify the node to decrease the size of the key.\n                    TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode));\n                    newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));\n                } else {\n                    // We're dealing with an unnecessary extension node.\n                    // We're going to delete the node entirely.\n                    // Simply insert its current value into the branch index.\n                    newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode));\n                }\n            }\n\n            if (keyRemainder.length == 0) {\n                // We've got nothing left in the key remainder.\n                // Simply insert the value into the branch value slot.\n                newBranch = _editBranchValue(newBranch, _value);\n                // Push the branch into the list of new nodes.\n                newNodes[totalNewNodes] = newBranch;\n                totalNewNodes += 1;\n            } else {\n                // We've got some key remainder to work with.\n                // We'll be inserting a leaf node into the trie.\n                // First, move on to the next nibble.\n                keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1);\n                // Push the branch into the list of new nodes.\n                newNodes[totalNewNodes] = newBranch;\n                totalNewNodes += 1;\n                // Push a new leaf node for our k/v pair.\n                newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value);\n                totalNewNodes += 1;\n            }\n        }\n\n        // Finally, join the old path with our newly created nodes.\n        // Since we're overwriting the last node in the path, we use `_pathLength - 1`.\n        return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes);\n    }\n\n    /**\n     * @notice Computes the trie root from a given path.\n     * @param _nodes Path to some k/v pair.\n     * @param _key Key for the k/v pair.\n     * @return _updatedRoot Root hash for the updated trie.\n     */\n    function _getUpdatedTrieRoot(\n        TrieNode[] memory _nodes,\n        bytes memory _key\n    )\n        private\n        pure\n        returns (\n            bytes32 _updatedRoot\n        )\n    {\n        bytes memory key = Lib_BytesUtils.toNibbles(_key);\n\n        // Some variables to keep track of during iteration.\n        TrieNode memory currentNode;\n        NodeType currentNodeType;\n        bytes memory previousNodeHash;\n\n        // Run through the path backwards to rebuild our root hash.\n        for (uint256 i = _nodes.length; i > 0; i--) {\n            // Pick out the current node.\n            currentNode = _nodes[i - 1];\n            currentNodeType = _getNodeType(currentNode);\n\n            if (currentNodeType == NodeType.LeafNode) {\n                // Leaf nodes are already correctly encoded.\n                // Shift the key over to account for the nodes key.\n                bytes memory nodeKey = _getNodeKey(currentNode);\n                key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);\n            } else if (currentNodeType == NodeType.ExtensionNode) {\n                // Shift the key over to account for the nodes key.\n                bytes memory nodeKey = _getNodeKey(currentNode);\n                key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);\n\n                // If this node is the last element in the path, it'll be correctly encoded\n                // and we can skip this part.\n                if (previousNodeHash.length > 0) {\n                    // Re-encode the node based on the previous node.\n                    currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);\n                }\n            } else if (currentNodeType == NodeType.BranchNode) {\n                // If this node is the last element in the path, it'll be correctly encoded\n                // and we can skip this part.\n                if (previousNodeHash.length > 0) {\n                    // Re-encode the node based on the previous node.\n                    uint8 branchKey = uint8(key[key.length - 1]);\n                    key = Lib_BytesUtils.slice(key, 0, key.length - 1);\n                    currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);\n                }\n            }\n\n            // Compute the node hash for the next iteration.\n            previousNodeHash = _getNodeHash(currentNode.encoded);\n        }\n\n        // Current node should be the root at this point.\n        // Simply return the hash of its encoding.\n        return keccak256(currentNode.encoded);\n    }\n\n    /**\n     * @notice Parses an RLP-encoded proof into something more useful.\n     * @param _proof RLP-encoded proof to parse.\n     * @return _parsed Proof parsed into easily accessible structs.\n     */\n    function _parseProof(\n        bytes memory _proof\n    )\n        private\n        pure\n        returns (\n            TrieNode[] memory _parsed\n        )\n    {\n        Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);\n        TrieNode[] memory proof = new TrieNode[](nodes.length);\n\n        for (uint256 i = 0; i < nodes.length; i++) {\n            bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);\n            proof[i] = TrieNode({\n                encoded: encoded,\n                decoded: Lib_RLPReader.readList(encoded)\n            });\n        }\n\n        return proof;\n    }\n\n    /**\n     * @notice Picks out the ID for a node. Node ID is referred to as the\n     * \"hash\" within the specification, but nodes < 32 bytes are not actually\n     * hashed.\n     * @param _node Node to pull an ID for.\n     * @return _nodeID ID for the node, depending on the size of its contents.\n     */\n    function _getNodeID(\n        Lib_RLPReader.RLPItem memory _node\n    )\n        private\n        pure\n        returns (\n            bytes32 _nodeID\n        )\n    {\n        bytes memory nodeID;\n\n        if (_node.length < 32) {\n            // Nodes smaller than 32 bytes are RLP encoded.\n            nodeID = Lib_RLPReader.readRawBytes(_node);\n        } else {\n            // Nodes 32 bytes or larger are hashed.\n            nodeID = Lib_RLPReader.readBytes(_node);\n        }\n\n        return Lib_BytesUtils.toBytes32(nodeID);\n    }\n\n    /**\n     * @notice Gets the path for a leaf or extension node.\n     * @param _node Node to get a path for.\n     * @return _path Node path, converted to an array of nibbles.\n     */\n    function _getNodePath(\n        TrieNode memory _node\n    )\n        private\n        pure\n        returns (\n            bytes memory _path\n        )\n    {\n        return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));\n    }\n\n    /**\n     * @notice Gets the key for a leaf or extension node. Keys are essentially\n     * just paths without any prefix.\n     * @param _node Node to get a key for.\n     * @return _key Node key, converted to an array of nibbles.\n     */\n    function _getNodeKey(\n        TrieNode memory _node\n    )\n        private\n        pure\n        returns (\n            bytes memory _key\n        )\n    {\n        return _removeHexPrefix(_getNodePath(_node));\n    }\n\n    /**\n     * @notice Gets the path for a node.\n     * @param _node Node to get a value for.\n     * @return _value Node value, as hex bytes.\n     */\n    function _getNodeValue(\n        TrieNode memory _node\n    )\n        private\n        pure\n        returns (\n            bytes memory _value\n        )\n    {\n        return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);\n    }\n\n    /**\n     * @notice Computes the node hash for an encoded node. Nodes < 32 bytes\n     * are not hashed, all others are keccak256 hashed.\n     * @param _encoded Encoded node to hash.\n     * @return _hash Hash of the encoded node. Simply the input if < 32 bytes.\n     */\n    function _getNodeHash(\n        bytes memory _encoded\n    )\n        private\n        pure\n        returns (\n            bytes memory _hash\n        )\n    {\n        if (_encoded.length < 32) {\n            return _encoded;\n        } else {\n            return abi.encodePacked(keccak256(_encoded));\n        }\n    }\n\n    /**\n     * @notice Determines the type for a given node.\n     * @param _node Node to determine a type for.\n     * @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.\n     */\n    function _getNodeType(\n        TrieNode memory _node\n    )\n        private\n        pure\n        returns (\n            NodeType _type\n        )\n    {\n        if (_node.decoded.length == BRANCH_NODE_LENGTH) {\n            return NodeType.BranchNode;\n        } else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {\n            bytes memory path = _getNodePath(_node);\n            uint8 prefix = uint8(path[0]);\n\n            if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {\n                return NodeType.LeafNode;\n            } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {\n                return NodeType.ExtensionNode;\n            }\n        }\n\n        revert(\"Invalid node type\");\n    }\n\n    /**\n     * @notice Utility; determines the number of nibbles shared between two\n     * nibble arrays.\n     * @param _a First nibble array.\n     * @param _b Second nibble array.\n     * @return _shared Number of shared nibbles.\n     */\n    function _getSharedNibbleLength(\n        bytes memory _a,\n        bytes memory _b\n    )\n        private\n        pure\n        returns (\n            uint256 _shared\n        )\n    {\n        uint256 i = 0;\n        while (_a.length > i && _b.length > i && _a[i] == _b[i]) {\n            i++;\n        }\n        return i;\n    }\n\n    /**\n     * @notice Utility; converts an RLP-encoded node into our nice struct.\n     * @param _raw RLP-encoded node to convert.\n     * @return _node Node as a TrieNode struct.\n     */\n    function _makeNode(\n        bytes[] memory _raw\n    )\n        private\n        pure\n        returns (\n            TrieNode memory _node\n        )\n    {\n        bytes memory encoded = Lib_RLPWriter.writeList(_raw);\n\n        return TrieNode({\n            encoded: encoded,\n            decoded: Lib_RLPReader.readList(encoded)\n        });\n    }\n\n    /**\n     * @notice Utility; converts an RLP-decoded node into our nice struct.\n     * @param _items RLP-decoded node to convert.\n     * @return _node Node as a TrieNode struct.\n     */\n    function _makeNode(\n        Lib_RLPReader.RLPItem[] memory _items\n    )\n        private\n        pure\n        returns (\n            TrieNode memory _node\n        )\n    {\n        bytes[] memory raw = new bytes[](_items.length);\n        for (uint256 i = 0; i < _items.length; i++) {\n            raw[i] = Lib_RLPReader.readRawBytes(_items[i]);\n        }\n        return _makeNode(raw);\n    }\n\n    /**\n     * @notice Creates a new extension node.\n     * @param _key Key for the extension node, unprefixed.\n     * @param _value Value for the extension node.\n     * @return _node New extension node with the given k/v pair.\n     */\n    function _makeExtensionNode(\n        bytes memory _key,\n        bytes memory _value\n    )\n        private\n        pure\n        returns (\n            TrieNode memory _node\n        )\n    {\n        bytes[] memory raw = new bytes[](2);\n        bytes memory key = _addHexPrefix(_key, false);\n        raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));\n        raw[1] = Lib_RLPWriter.writeBytes(_value);\n        return _makeNode(raw);\n    }\n\n    /**\n     * Creates a new extension node with the same key but a different value.\n     * @param _node Extension node to copy and modify.\n     * @param _value New value for the extension node.\n     * @return New node with the same key and different value.\n     */\n    function _editExtensionNodeValue(\n        TrieNode memory _node,\n        bytes memory _value\n    )\n        private\n        pure\n        returns (\n            TrieNode memory\n        )\n    {\n        bytes[] memory raw = new bytes[](2);\n        bytes memory key = _addHexPrefix(_getNodeKey(_node), false);\n        raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));\n        if (_value.length < 32) {\n            raw[1] = _value;\n        } else {\n            raw[1] = Lib_RLPWriter.writeBytes(_value);\n        }\n        return _makeNode(raw);\n    }\n\n    /**\n     * @notice Creates a new leaf node.\n     * @dev This function is essentially identical to `_makeExtensionNode`.\n     * Although we could route both to a single method with a flag, it's\n     * more gas efficient to keep them separate and duplicate the logic.\n     * @param _key Key for the leaf node, unprefixed.\n     * @param _value Value for the leaf node.\n     * @return _node New leaf node with the given k/v pair.\n     */\n    function _makeLeafNode(\n        bytes memory _key,\n        bytes memory _value\n    )\n        private\n        pure\n        returns (\n            TrieNode memory _node\n        )\n    {\n        bytes[] memory raw = new bytes[](2);\n        bytes memory key = _addHexPrefix(_key, true);\n        raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));\n        raw[1] = Lib_RLPWriter.writeBytes(_value);\n        return _makeNode(raw);\n    }\n\n    /**\n     * @notice Creates an empty branch node.\n     * @return _node Empty branch node as a TrieNode struct.\n     */\n    function _makeEmptyBranchNode()\n        private\n        pure\n        returns (\n            TrieNode memory _node\n        )\n    {\n        bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);\n        for (uint256 i = 0; i < raw.length; i++) {\n            raw[i] = RLP_NULL_BYTES;\n        }\n        return _makeNode(raw);\n    }\n\n    /**\n     * @notice Modifies the value slot for a given branch.\n     * @param _branch Branch node to modify.\n     * @param _value Value to insert into the branch.\n     * @return _updatedNode Modified branch node.\n     */\n    function _editBranchValue(\n        TrieNode memory _branch,\n        bytes memory _value\n    )\n        private\n        pure\n        returns (\n            TrieNode memory _updatedNode\n        )\n    {\n        bytes memory encoded = Lib_RLPWriter.writeBytes(_value);\n        _branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);\n        return _makeNode(_branch.decoded);\n    }\n\n    /**\n     * @notice Modifies a slot at an index for a given branch.\n     * @param _branch Branch node to modify.\n     * @param _index Slot index to modify.\n     * @param _value Value to insert into the slot.\n     * @return _updatedNode Modified branch node.\n     */\n    function _editBranchIndex(\n        TrieNode memory _branch,\n        uint8 _index,\n        bytes memory _value\n    )\n        private\n        pure\n        returns (\n            TrieNode memory _updatedNode\n        )\n    {\n        bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);\n        _branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);\n        return _makeNode(_branch.decoded);\n    }\n\n    /**\n     * @notice Utility; adds a prefix to a key.\n     * @param _key Key to prefix.\n     * @param _isLeaf Whether or not the key belongs to a leaf.\n     * @return _prefixedKey Prefixed key.\n     */\n    function _addHexPrefix(\n        bytes memory _key,\n        bool _isLeaf\n    )\n        private\n        pure\n        returns (\n            bytes memory _prefixedKey\n        )\n    {\n        uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);\n        uint8 offset = uint8(_key.length % 2);\n        bytes memory prefixed = new bytes(2 - offset);\n        prefixed[0] = bytes1(prefix + offset);\n        return abi.encodePacked(prefixed, _key);\n    }\n\n    /**\n     * @notice Utility; removes a prefix from a path.\n     * @param _path Path to remove the prefix from.\n     * @return _unprefixedKey Unprefixed key.\n     */\n    function _removeHexPrefix(\n        bytes memory _path\n    )\n        private\n        pure\n        returns (\n            bytes memory _unprefixedKey\n        )\n    {\n        if (uint8(_path[0]) % 2 == 0) {\n            return Lib_BytesUtils.slice(_path, 2);\n        } else {\n            return Lib_BytesUtils.slice(_path, 1);\n        }\n    }\n\n    /**\n     * @notice Utility; combines two node arrays. Array lengths are required\n     * because the actual lengths may be longer than the filled lengths.\n     * Array resizing is extremely costly and should be avoided.\n     * @param _a First array to join.\n     * @param _aLength Length of the first array.\n     * @param _b Second array to join.\n     * @param _bLength Length of the second array.\n     * @return _joined Combined node array.\n     */\n    function _joinNodeArrays(\n        TrieNode[] memory _a,\n        uint256 _aLength,\n        TrieNode[] memory _b,\n        uint256 _bLength\n    )\n        private\n        pure\n        returns (\n            TrieNode[] memory _joined\n        )\n    {\n        TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);\n\n        // Copy elements from the first array.\n        for (uint256 i = 0; i < _aLength; i++) {\n            ret[i] = _a[i];\n        }\n\n        // Copy elements from the second array.\n        for (uint256 i = 0; i < _bLength; i++) {\n            ret[i + _aLength] = _b[i];\n        }\n\n        return ret;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/verification/OVM_StateTransitionerFactory.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\n\n/* Interface Imports */\nimport { iOVM_StateTransitioner } from \"../../iOVM/verification/iOVM_StateTransitioner.sol\";\nimport { iOVM_StateTransitionerFactory } from \"../../iOVM/verification/iOVM_StateTransitionerFactory.sol\";\nimport { iOVM_FraudVerifier } from \"../../iOVM/verification/iOVM_FraudVerifier.sol\";\n\n/* Contract Imports */\nimport { OVM_StateTransitioner } from \"./OVM_StateTransitioner.sol\";\n\n/**\n * @title OVM_StateTransitionerFactory\n * @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State\n * Transitioner during the initialization of a fraud proof.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver {\n\n    /***************\n     * Constructor *\n     ***************/\n\n    constructor(\n        address _libAddressManager\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {}\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Creates a new OVM_StateTransitioner\n     * @param _libAddressManager Address of the Address Manager.\n     * @param _stateTransitionIndex Index of the state transition being verified.\n     * @param _preStateRoot State root before the transition was executed.\n     * @param _transactionHash Hash of the executed transaction.\n     * @return New OVM_StateTransitioner instance.\n     */\n    function create(\n        address _libAddressManager,\n        uint256 _stateTransitionIndex,\n        bytes32 _preStateRoot,\n        bytes32 _transactionHash\n    )\n        override\n        public\n        returns (\n            iOVM_StateTransitioner\n        )\n    {\n        require(\n            msg.sender == resolve(\"OVM_FraudVerifier\"),\n            \"Create can only be done by the OVM_FraudVerifier.\"\n        );\n\n        return new OVM_StateTransitioner(\n            _libAddressManager,\n            _stateTransitionIndex,\n            _preStateRoot,\n            _transactionHash\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/verification/iOVM_StateTransitionerFactory.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Contract Imports */\nimport { iOVM_StateTransitioner } from \"./iOVM_StateTransitioner.sol\";\n\n/**\n * @title iOVM_StateTransitionerFactory\n */\ninterface iOVM_StateTransitionerFactory {\n\n    /***************************************\n     * Public Functions: Contract Creation *\n     ***************************************/\n\n    function create(\n        address _proxyManager,\n        uint256 _stateTransitionIndex,\n        bytes32 _preStateRoot,\n        bytes32 _transactionHash\n    )\n        external\n        returns (\n            iOVM_StateTransitioner _ovmStateTransitioner\n        );\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/verification/iOVM_FraudVerifier.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\n\n/* Interface Imports */\nimport { iOVM_StateTransitioner } from \"./iOVM_StateTransitioner.sol\";\n\n/**\n * @title iOVM_FraudVerifier\n */\ninterface iOVM_FraudVerifier {\n\n    /**********\n     * Events *\n     **********/\n\n    event FraudProofInitialized(\n        bytes32 _preStateRoot,\n        uint256 _preStateRootIndex,\n        bytes32 _transactionHash,\n        address _who\n    );\n\n    event FraudProofFinalized(\n        bytes32 _preStateRoot,\n        uint256 _preStateRootIndex,\n        bytes32 _transactionHash,\n        address _who\n    );\n\n\n    /***************************************\n     * Public Functions: Transition Status *\n     ***************************************/\n\n    function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner);\n\n\n    /****************************************\n     * Public Functions: Fraud Verification *\n     ****************************************/\n\n    function initializeFraudVerification(\n        bytes32 _preStateRoot,\n        Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,\n        Lib_OVMCodec.Transaction calldata _transaction,\n        Lib_OVMCodec.TransactionChainElement calldata _txChainElement,\n        Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof calldata _transactionProof\n    ) external;\n\n    function finalizeFraudVerification(\n        bytes32 _preStateRoot,\n        Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,\n        bytes32 _txHash,\n        bytes32 _postStateRoot,\n        Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof\n    ) external;\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/verification/OVM_FraudVerifier.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\n\n/* Interface Imports */\nimport { iOVM_FraudVerifier } from \"../../iOVM/verification/iOVM_FraudVerifier.sol\";\nimport { iOVM_StateTransitioner } from \"../../iOVM/verification/iOVM_StateTransitioner.sol\";\nimport { iOVM_StateTransitionerFactory } from \"../../iOVM/verification/iOVM_StateTransitionerFactory.sol\";\nimport { iOVM_BondManager } from \"../../iOVM/verification/iOVM_BondManager.sol\";\nimport { iOVM_StateCommitmentChain } from \"../../iOVM/chain/iOVM_StateCommitmentChain.sol\";\nimport { iOVM_CanonicalTransactionChain } from \"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol\";\n\n/* Contract Imports */\nimport { Abs_FraudContributor } from \"./Abs_FraudContributor.sol\";\n\n\n\n/**\n * @title OVM_FraudVerifier\n * @dev The Fraud Verifier contract coordinates the entire fraud proof verification process.\n * If the fraud proof was successful it prunes any state batches from State Commitment Chain\n * which were published after the fraudulent state root.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_FraudVerifier is Lib_AddressResolver, Abs_FraudContributor, iOVM_FraudVerifier {\n\n    /*******************************************\n     * Contract Variables: Internal Accounting *\n     *******************************************/\n\n    mapping (bytes32 => iOVM_StateTransitioner) internal transitioners;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     */\n    constructor(\n        address _libAddressManager\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {}\n\n\n    /***************************************\n     * Public Functions: Transition Status *\n     ***************************************/\n\n    /**\n     * Retrieves the state transitioner for a given root.\n     * @param _preStateRoot State root to query a transitioner for.\n     * @return _transitioner Corresponding state transitioner contract.\n     */\n    function getStateTransitioner(\n        bytes32 _preStateRoot,\n        bytes32 _txHash\n    )\n        override\n        public\n        view\n        returns (\n            iOVM_StateTransitioner _transitioner\n        )\n    {\n        return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];\n    }\n\n\n    /****************************************\n     * Public Functions: Fraud Verification *\n     ****************************************/\n\n    /**\n     * Begins the fraud verification process.\n     * @param _preStateRoot State root before the fraudulent transaction.\n     * @param _preStateRootBatchHeader Batch header for the provided pre-state root.\n     * @param _preStateRootProof Inclusion proof for the provided pre-state root.\n     * @param _transaction OVM transaction claimed to be fraudulent.\n     * @param _txChainElement OVM transaction chain element.\n     * @param _transactionBatchHeader Batch header for the provided transaction.\n     * @param _transactionProof Inclusion proof for the provided transaction.\n     */\n    function initializeFraudVerification(\n        bytes32 _preStateRoot,\n        Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,\n        Lib_OVMCodec.Transaction memory _transaction,\n        Lib_OVMCodec.TransactionChainElement memory _txChainElement,\n        Lib_OVMCodec.ChainBatchHeader memory _transactionBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _transactionProof\n    )\n        override\n        public\n        contributesToFraudProof(_preStateRoot, Lib_OVMCodec.hashTransaction(_transaction))\n    {\n        bytes32 _txHash = Lib_OVMCodec.hashTransaction(_transaction);\n\n        if (_hasStateTransitioner(_preStateRoot, _txHash)) {\n            return;\n        }\n\n        iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve(\"OVM_StateCommitmentChain\"));\n        iOVM_CanonicalTransactionChain ovmCanonicalTransactionChain = iOVM_CanonicalTransactionChain(resolve(\"OVM_CanonicalTransactionChain\"));\n\n        require(\n            ovmStateCommitmentChain.verifyStateCommitment(\n                _preStateRoot,\n                _preStateRootBatchHeader,\n                _preStateRootProof\n            ),\n            \"Invalid pre-state root inclusion proof.\"\n        );\n\n        require(\n            ovmCanonicalTransactionChain.verifyTransaction(\n                _transaction,\n                _txChainElement,\n                _transactionBatchHeader,\n                _transactionProof\n            ),\n            \"Invalid transaction inclusion proof.\"\n        );\n\n        require (\n            _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1 == _transactionBatchHeader.prevTotalElements + _transactionProof.index,\n            \"Pre-state root global index must equal to the transaction root global index.\"\n        );\n\n        _deployTransitioner(_preStateRoot, _txHash, _preStateRootProof.index);\n\n        emit FraudProofInitialized(\n            _preStateRoot,\n            _preStateRootProof.index,\n            _txHash,\n            msg.sender\n        );\n    }\n\n    /**\n     * Finalizes the fraud verification process.\n     * @param _preStateRoot State root before the fraudulent transaction.\n     * @param _preStateRootBatchHeader Batch header for the provided pre-state root.\n     * @param _preStateRootProof Inclusion proof for the provided pre-state root.\n     * @param _txHash The transaction for the state root\n     * @param _postStateRoot State root after the fraudulent transaction.\n     * @param _postStateRootBatchHeader Batch header for the provided post-state root.\n     * @param _postStateRootProof Inclusion proof for the provided post-state root.\n     */\n    function finalizeFraudVerification(\n        bytes32 _preStateRoot,\n        Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,\n        bytes32 _txHash,\n        bytes32 _postStateRoot,\n        Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _postStateRootProof\n    )\n        override\n        public\n        contributesToFraudProof(_preStateRoot, _txHash)\n    {\n        iOVM_StateTransitioner transitioner = getStateTransitioner(_preStateRoot, _txHash);\n        iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve(\"OVM_StateCommitmentChain\"));\n\n        require(\n            transitioner.isComplete() == true,\n            \"State transition process must be completed prior to finalization.\"\n        );\n\n        require (\n            _postStateRootBatchHeader.prevTotalElements + _postStateRootProof.index == _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1,\n            \"Post-state root global index must equal to the pre state root global index plus one.\"\n        );\n\n        require(\n            ovmStateCommitmentChain.verifyStateCommitment(\n                _preStateRoot,\n                _preStateRootBatchHeader,\n                _preStateRootProof\n            ),\n            \"Invalid pre-state root inclusion proof.\"\n        );\n\n        require(\n            ovmStateCommitmentChain.verifyStateCommitment(\n                _postStateRoot,\n                _postStateRootBatchHeader,\n                _postStateRootProof\n            ),\n            \"Invalid post-state root inclusion proof.\"\n        );\n\n        // If the post state root did not match, then there was fraud and we should delete the batch\n        require(\n            _postStateRoot != transitioner.getPostStateRoot(),\n            \"State transition has not been proven fraudulent.\"\n        );\n\n        _cancelStateTransition(_postStateRootBatchHeader, _preStateRoot);\n\n        // TEMPORARY: Remove the transitioner; for minnet.\n        transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitioner(0x0000000000000000000000000000000000000000);\n\n        emit FraudProofFinalized(\n            _preStateRoot,\n            _preStateRootProof.index,\n            _txHash,\n            msg.sender\n        );\n    }\n\n\n    /************************************\n     * Internal Functions: Verification *\n     ************************************/\n\n    /**\n     * Checks whether a transitioner already exists for a given pre-state root.\n     * @param _preStateRoot Pre-state root to check.\n     * @return _exists Whether or not we already have a transitioner for the root.\n     */\n    function _hasStateTransitioner(\n        bytes32 _preStateRoot,\n        bytes32 _txHash\n    )\n        internal\n        view\n        returns (\n            bool _exists\n        )\n    {\n        return address(getStateTransitioner(_preStateRoot, _txHash)) != address(0);\n    }\n\n    /**\n     * Deploys a new state transitioner.\n     * @param _preStateRoot Pre-state root to initialize the transitioner with.\n     * @param _txHash Hash of the transaction this transitioner will execute.\n     * @param _stateTransitionIndex Index of the transaction in the chain.\n     */\n    function _deployTransitioner(\n        bytes32 _preStateRoot,\n        bytes32 _txHash,\n        uint256 _stateTransitionIndex\n    )\n        internal\n    {\n        transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitionerFactory(\n            resolve(\"OVM_StateTransitionerFactory\")\n        ).create(\n            address(libAddressManager),\n            _stateTransitionIndex,\n            _preStateRoot,\n            _txHash\n        );\n    }\n\n    /**\n     * Removes a state transition from the state commitment chain.\n     * @param _postStateRootBatchHeader Header for the post-state root.\n     * @param _preStateRoot Pre-state root hash.\n     */\n    function _cancelStateTransition(\n        Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,\n        bytes32 _preStateRoot\n    )\n        internal\n    {\n        iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve(\"OVM_StateCommitmentChain\"));\n        iOVM_BondManager ovmBondManager = iOVM_BondManager(resolve(\"OVM_BondManager\"));\n\n        // Delete the state batch.\n        ovmStateCommitmentChain.deleteStateBatch(\n            _postStateRootBatchHeader\n        );\n\n        // Get the timestamp and publisher for that block.\n        (uint256 timestamp, address publisher) = abi.decode(_postStateRootBatchHeader.extraData, (uint256, address));\n\n        // Slash the bonds at the bond manager.\n        ovmBondManager.finalize(\n            _preStateRoot,\n            publisher,\n            timestamp\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/chain/iOVM_StateCommitmentChain.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\n\n/**\n * @title iOVM_StateCommitmentChain\n */\ninterface iOVM_StateCommitmentChain {\n\n    /**********\n     * Events *\n     **********/\n\n    event StateBatchAppended(\n        uint256 indexed _batchIndex,\n        bytes32 _batchRoot,\n        uint256 _batchSize,\n        uint256 _prevTotalElements,\n        bytes _extraData\n    );\n\n    event StateBatchDeleted(\n        uint256 indexed _batchIndex,\n        bytes32 _batchRoot\n    );\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Retrieves the total number of elements submitted.\n     * @return _totalElements Total submitted elements.\n     */\n    function getTotalElements()\n        external\n        view\n        returns (\n            uint256 _totalElements\n        );\n\n    /**\n     * Retrieves the total number of batches submitted.\n     * @return _totalBatches Total submitted batches.\n     */\n    function getTotalBatches()\n        external\n        view\n        returns (\n            uint256 _totalBatches\n        );\n\n    /**\n     * Retrieves the timestamp of the last batch submitted by the sequencer.\n     * @return _lastSequencerTimestamp Last sequencer batch timestamp.\n     */\n    function getLastSequencerTimestamp()\n        external\n        view\n        returns (\n            uint256 _lastSequencerTimestamp\n        );\n\n    /**\n     * Appends a batch of state roots to the chain.\n     * @param _batch Batch of state roots.\n     * @param _shouldStartAtElement Index of the element at which this batch should start.\n     */\n    function appendStateBatch(\n        bytes32[] calldata _batch,\n        uint256 _shouldStartAtElement\n    )\n        external;\n\n    /**\n     * Deletes all state roots after (and including) a given batch.\n     * @param _batchHeader Header of the batch to start deleting from.\n     */\n    function deleteStateBatch(\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n    )\n        external;\n\n    /**\n     * Verifies a batch inclusion proof.\n     * @param _element Hash of the element to verify a proof for.\n     * @param _batchHeader Header of the batch in which the element was included.\n     * @param _proof Merkle inclusion proof for the element.\n     */\n    function verifyStateCommitment(\n        bytes32 _element,\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _proof\n    )\n        external\n        view\n        returns (\n            bool _verified\n        );\n\n    /**\n     * Checks whether a given batch is still inside its fraud proof window.\n     * @param _batchHeader Header of the batch to check.\n     * @return _inside Whether or not the batch is inside the fraud proof window.\n     */\n    function insideFraudProofWindow(\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n    )\n        external\n        view\n        returns (\n            bool _inside\n        );\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/chain/iOVM_CanonicalTransactionChain.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\n\n/* Interface Imports */\nimport { iOVM_ChainStorageContainer } from \"./iOVM_ChainStorageContainer.sol\";\n\n/**\n * @title iOVM_CanonicalTransactionChain\n */\ninterface iOVM_CanonicalTransactionChain {\n\n    /**********\n     * Events *\n     **********/\n\n    event TransactionEnqueued(\n        address _l1TxOrigin,\n        address _target,\n        uint256 _gasLimit,\n        bytes _data,\n        uint256 _queueIndex,\n        uint256 _timestamp\n    );\n\n    event QueueBatchAppended(\n        uint256 _startingQueueIndex,\n        uint256 _numQueueElements,\n        uint256 _totalElements\n    );\n\n    event SequencerBatchAppended(\n        uint256 _startingQueueIndex,\n        uint256 _numQueueElements,\n        uint256 _totalElements\n    );\n\n    event TransactionBatchAppended(\n        uint256 indexed _batchIndex,\n        bytes32 _batchRoot,\n        uint256 _batchSize,\n        uint256 _prevTotalElements,\n        bytes _extraData\n    );\n\n\n    /***********\n     * Structs *\n     ***********/\n\n    struct BatchContext {\n        uint256 numSequencedTransactions;\n        uint256 numSubsequentQueueTransactions;\n        uint256 timestamp;\n        uint256 blockNumber;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n\n    /**\n     * Accesses the batch storage container.\n     * @return Reference to the batch storage container.\n     */\n    function batches()\n        external\n        view\n        returns (\n            iOVM_ChainStorageContainer\n        );\n\n    /**\n     * Accesses the queue storage container.\n     * @return Reference to the queue storage container.\n     */\n    function queue()\n        external\n        view\n        returns (\n            iOVM_ChainStorageContainer\n        );\n\n    /**\n     * Retrieves the total number of elements submitted.\n     * @return _totalElements Total submitted elements.\n     */\n    function getTotalElements()\n        external\n        view\n        returns (\n            uint256 _totalElements\n        );\n\n    /**\n     * Retrieves the total number of batches submitted.\n     * @return _totalBatches Total submitted batches.\n     */\n    function getTotalBatches()\n        external\n        view\n        returns (\n            uint256 _totalBatches\n        );\n\n    /**\n     * Returns the index of the next element to be enqueued.\n     * @return Index for the next queue element.\n     */\n    function getNextQueueIndex()\n        external\n        view\n        returns (\n            uint40\n        );\n\n    /**\n     * Gets the queue element at a particular index.\n     * @param _index Index of the queue element to access.\n     * @return _element Queue element at the given index.\n     */\n    function getQueueElement(\n        uint256 _index\n    )\n        external\n        view\n        returns (\n            Lib_OVMCodec.QueueElement memory _element\n        );\n\n    /**\n     * Returns the timestamp of the last transaction.\n     * @return Timestamp for the last transaction.\n     */\n    function getLastTimestamp()\n        external\n        view\n        returns (\n            uint40\n        );\n\n    /**\n     * Returns the blocknumber of the last transaction.\n     * @return Blocknumber for the last transaction.\n     */\n    function getLastBlockNumber()\n        external\n        view\n        returns (\n            uint40\n        );\n\n    /**\n     * Get the number of queue elements which have not yet been included.\n     * @return Number of pending queue elements.\n     */\n    function getNumPendingQueueElements()\n        external\n        view\n        returns (\n            uint40\n        );\n\n    /**\n     * Retrieves the length of the queue, including\n     * both pending and canonical transactions.\n     * @return Length of the queue.\n     */\n    function getQueueLength()\n        external\n        view\n        returns (\n            uint40\n        );\n\n\n    /**\n     * Adds a transaction to the queue.\n     * @param _target Target contract to send the transaction to.\n     * @param _gasLimit Gas limit for the given transaction.\n     * @param _data Transaction data.\n     */\n    function enqueue(\n        address _target,\n        uint256 _gasLimit,\n        bytes memory _data\n    )\n        external;\n\n    /**\n     * Appends a given number of queued transactions as a single batch.\n     * @param _numQueuedTransactions Number of transactions to append.\n     */\n    function appendQueueBatch(\n        uint256 _numQueuedTransactions\n    )\n        external;\n\n    /**\n     * Allows the sequencer to append a batch of transactions.\n     * @dev This function uses a custom encoding scheme for efficiency reasons.\n     * .param _shouldStartAtElement Specific batch we expect to start appending to.\n     * .param _totalElementsToAppend Total number of batch elements we expect to append.\n     * .param _contexts Array of batch contexts.\n     * .param _transactionDataFields Array of raw transaction data.\n     */\n    function appendSequencerBatch(\n        // uint40 _shouldStartAtElement,\n        // uint24 _totalElementsToAppend,\n        // BatchContext[] _contexts,\n        // bytes[] _transactionDataFields\n    )\n        external;\n\n    /**\n     * Verifies whether a transaction is included in the chain.\n     * @param _transaction Transaction to verify.\n     * @param _txChainElement Transaction chain element corresponding to the transaction.\n     * @param _batchHeader Header of the batch the transaction was included in.\n     * @param _inclusionProof Inclusion proof for the provided transaction chain element.\n     * @return True if the transaction exists in the CTC, false if not.\n     */\n    function verifyTransaction(\n        Lib_OVMCodec.Transaction memory _transaction,\n        Lib_OVMCodec.TransactionChainElement memory _txChainElement,\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _inclusionProof\n    )\n        external\n        view\n        returns (\n            bool\n        );\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/chain/iOVM_ChainStorageContainer.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title iOVM_ChainStorageContainer\n */\ninterface iOVM_ChainStorageContainer {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Sets the container's global metadata field. We're using `bytes27` here because we use five\n     * bytes to maintain the length of the underlying data structure, meaning we have an extra\n     * 27 bytes to store arbitrary data.\n     * @param _globalMetadata New global metadata to set.\n     */\n    function setGlobalMetadata(\n        bytes27 _globalMetadata\n    )\n        external;\n\n    /**\n     * Retrieves the container's global metadata field.\n     * @return Container global metadata field.\n     */\n    function getGlobalMetadata()\n        external\n        view\n        returns (\n            bytes27\n        );\n\n    /**\n     * Retrieves the number of objects stored in the container.\n     * @return Number of objects in the container.\n     */\n    function length()\n        external\n        view\n        returns (\n            uint256\n        );\n\n    /**\n     * Pushes an object into the container.\n     * @param _object A 32 byte value to insert into the container.\n     */\n    function push(\n        bytes32 _object\n    )\n        external;\n\n    /**\n     * Pushes an object into the container. Function allows setting the global metadata since\n     * we'll need to touch the \"length\" storage slot anyway, which also contains the global\n     * metadata (it's an optimization).\n     * @param _object A 32 byte value to insert into the container.\n     * @param _globalMetadata New global metadata for the container.\n     */\n    function push(\n        bytes32 _object,\n        bytes27 _globalMetadata\n    )\n        external;\n\n    /**\n     * Retrieves an object from the container.\n     * @param _index Index of the particular object to access.\n     * @return 32 byte object value.\n     */\n    function get(\n        uint256 _index\n    )\n        external\n        view\n        returns (\n            bytes32\n        );\n\n    /**\n     * Removes all objects after and including a given index.\n     * @param _index Object index to delete from.\n     */\n    function deleteElementsAfterInclusive(\n        uint256 _index\n    )\n        external;\n\n    /**\n     * Removes all objects after and including a given index. Also allows setting the global\n     * metadata field.\n     * @param _index Object index to delete from.\n     * @param _globalMetadata New global metadata for the container.\n     */\n    function deleteElementsAfterInclusive(\n        uint256 _index,\n        bytes27 _globalMetadata\n    )\n        external;\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/verification/OVM_BondManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\n\n/* Interface Imports */\nimport { iOVM_BondManager, Errors, ERC20 } from \"../../iOVM/verification/iOVM_BondManager.sol\";\nimport { iOVM_FraudVerifier } from \"../../iOVM/verification/iOVM_FraudVerifier.sol\";\n\n/**\n * @title OVM_BondManager\n * @dev The Bond Manager contract handles deposits in the form of an ERC20 token from bonded\n * Proposers. It also handles the accounting of gas costs spent by a Verifier during the course of a\n * fraud proof. In the event of a successful fraud proof, the fraudulent Proposer's bond is slashed,\n * and the Verifier's gas costs are refunded.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_BondManager is iOVM_BondManager, Lib_AddressResolver {\n\n    /****************************\n     * Constants and Parameters *\n     ****************************/\n\n    /// The period to find the earliest fraud proof for a publisher\n    uint256 public constant multiFraudProofPeriod = 7 days;\n\n    /// The dispute period\n    uint256 public constant disputePeriodSeconds = 7 days;\n\n    /// The minimum collateral a sequencer must post\n    uint256 public constant requiredCollateral = 1 ether;\n\n\n    /*******************************************\n     * Contract Variables: Contract References *\n     *******************************************/\n\n    /// The bond token\n    ERC20 immutable public token;\n\n\n    /********************************************\n     * Contract Variables: Internal Accounting  *\n     *******************************************/\n\n    /// The bonds posted by each proposer\n    mapping(address => Bond) public bonds;\n\n    /// For each pre-state root, there's an array of witnessProviders that must be rewarded\n    /// for posting witnesses\n    mapping(bytes32 => Rewards) public witnessProviders;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /// Initializes with a ERC20 token to be used for the fidelity bonds\n    /// and with the Address Manager\n    constructor(\n        ERC20 _token,\n        address _libAddressManager\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {\n        token = _token;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /// Adds `who` to the list of witnessProviders for the provided `preStateRoot`.\n    function recordGasSpent(bytes32 _preStateRoot, bytes32 _txHash, address who, uint256 gasSpent) override public {\n        // The sender must be the transitioner that corresponds to the claimed pre-state root\n        address transitioner = address(iOVM_FraudVerifier(resolve(\"OVM_FraudVerifier\")).getStateTransitioner(_preStateRoot, _txHash));\n        require(transitioner == msg.sender, Errors.ONLY_TRANSITIONER);\n\n        witnessProviders[_preStateRoot].total += gasSpent;\n        witnessProviders[_preStateRoot].gasSpent[who] += gasSpent;\n    }\n\n    /// Slashes + distributes rewards or frees up the sequencer's bond, only called by\n    /// `FraudVerifier.finalizeFraudVerification`\n    function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) override public {\n        require(msg.sender == resolve(\"OVM_FraudVerifier\"), Errors.ONLY_FRAUD_VERIFIER);\n        require(witnessProviders[_preStateRoot].canClaim == false, Errors.ALREADY_FINALIZED);\n\n        // allow users to claim from that state root's\n        // pool of collateral (effectively slashing the sequencer)\n        witnessProviders[_preStateRoot].canClaim = true;\n\n        Bond storage bond = bonds[publisher];\n        if (bond.firstDisputeAt == 0) {\n            bond.firstDisputeAt = block.timestamp;\n            bond.earliestDisputedStateRoot = _preStateRoot;\n            bond.earliestTimestamp = timestamp;\n        } else if (\n            // only update the disputed state root for the publisher if it's within\n            // the dispute period _and_ if it's before the previous one\n            block.timestamp < bond.firstDisputeAt + multiFraudProofPeriod &&\n            timestamp < bond.earliestTimestamp\n        ) {\n            bond.earliestDisputedStateRoot = _preStateRoot;\n            bond.earliestTimestamp = timestamp;\n        }\n\n        // if the fraud proof's dispute period does not intersect with the\n        // withdrawal's timestamp, then the user should not be slashed\n        // e.g if a user at day 10 submits a withdrawal, and a fraud proof\n        // from day 1 gets published, the user won't be slashed since day 8 (1d + 7d)\n        // is before the user started their withdrawal. on the contrary, if the user\n        // had started their withdrawal at, say, day 6, they would be slashed\n        if (\n            bond.withdrawalTimestamp != 0 &&\n            uint256(bond.withdrawalTimestamp) > timestamp + disputePeriodSeconds &&\n            bond.state == State.WITHDRAWING\n        ) {\n            return;\n        }\n\n        // slash!\n        bond.state = State.NOT_COLLATERALIZED;\n    }\n\n    /// Sequencers call this function to post collateral which will be used for\n    /// the `appendBatch` call\n    function deposit() override public {\n        require(\n            token.transferFrom(msg.sender, address(this), requiredCollateral),\n            Errors.ERC20_ERR\n        );\n\n        // This cannot overflow\n        bonds[msg.sender].state = State.COLLATERALIZED;\n    }\n\n    /// Starts the withdrawal for a publisher\n    function startWithdrawal() override public {\n        Bond storage bond = bonds[msg.sender];\n        require(bond.withdrawalTimestamp == 0, Errors.WITHDRAWAL_PENDING);\n        require(bond.state == State.COLLATERALIZED, Errors.WRONG_STATE);\n\n        bond.state = State.WITHDRAWING;\n        bond.withdrawalTimestamp = uint32(block.timestamp);\n    }\n\n    /// Finalizes a pending withdrawal from a publisher\n    function finalizeWithdrawal() override public {\n        Bond storage bond = bonds[msg.sender];\n\n        require(\n            block.timestamp >= uint256(bond.withdrawalTimestamp) + disputePeriodSeconds,\n            Errors.TOO_EARLY\n        );\n        require(bond.state == State.WITHDRAWING, Errors.SLASHED);\n\n        // refunds!\n        bond.state = State.NOT_COLLATERALIZED;\n        bond.withdrawalTimestamp = 0;\n\n        require(\n            token.transfer(msg.sender, requiredCollateral),\n            Errors.ERC20_ERR\n        );\n    }\n\n    /// Claims the user's reward for the witnesses they provided for the earliest\n    /// disputed state root of the designated publisher\n    function claim(address who) override public {\n        Bond storage bond = bonds[who];\n        require(\n            block.timestamp >= bond.firstDisputeAt + multiFraudProofPeriod,\n            Errors.WAIT_FOR_DISPUTES\n        );\n\n        // reward the earliest state root for this publisher\n        bytes32 _preStateRoot = bond.earliestDisputedStateRoot;\n        Rewards storage rewards = witnessProviders[_preStateRoot];\n\n        // only allow claiming if fraud was proven in `finalize`\n        require(rewards.canClaim, Errors.CANNOT_CLAIM);\n\n        // proportional allocation - only reward 50% (rest gets locked in the\n        // contract forever\n        uint256 amount = (requiredCollateral * rewards.gasSpent[msg.sender]) / (2 * rewards.total);\n\n        // reset the user's spent gas so they cannot double claim\n        rewards.gasSpent[msg.sender] = 0;\n\n        // transfer\n        require(token.transfer(msg.sender, amount), Errors.ERC20_ERR);\n    }\n\n    /// Checks if the user is collateralized\n    function isCollateralized(address who) override public view returns (bool) {\n        return bonds[who].state == State.COLLATERALIZED;\n    }\n\n    /// Gets how many witnesses the user has provided for the state root\n    function getGasSpent(bytes32 preStateRoot, address who) override public view returns (uint256) {\n        return witnessProviders[preStateRoot].gasSpent[who];\n    }\n}\n"
    },
    "contracts/test-helpers/Mock_FraudVerifier.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\nimport { OVM_BondManager } from \"./../optimistic-ethereum/OVM/verification/OVM_BondManager.sol\";\n\ncontract Mock_FraudVerifier {\n    OVM_BondManager bondManager;\n\n    mapping (bytes32 => address) transitioners;\n\n    function setBondManager(OVM_BondManager _bondManager) public {\n        bondManager = _bondManager;\n    }\n\n    function setStateTransitioner(bytes32 preStateRoot, bytes32 txHash, address addr) public {\n        transitioners[keccak256(abi.encodePacked(preStateRoot, txHash))] = addr;\n    }\n\n    function getStateTransitioner(\n        bytes32 _preStateRoot,\n        bytes32 _txHash\n    )\n        public\n        view\n        returns (\n            address\n        )\n    {\n        return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];\n    }\n\n    function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) public {\n        bondManager.finalize(_preStateRoot, publisher, timestamp);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/chain/OVM_StateCommitmentChain.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\nimport { Lib_MerkleTree } from \"../../libraries/utils/Lib_MerkleTree.sol\";\n\n/* Interface Imports */\nimport { iOVM_FraudVerifier } from \"../../iOVM/verification/iOVM_FraudVerifier.sol\";\nimport { iOVM_StateCommitmentChain } from \"../../iOVM/chain/iOVM_StateCommitmentChain.sol\";\nimport { iOVM_CanonicalTransactionChain } from \"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol\";\nimport { iOVM_BondManager } from \"../../iOVM/verification/iOVM_BondManager.sol\";\nimport { iOVM_ChainStorageContainer } from \"../../iOVM/chain/iOVM_ChainStorageContainer.sol\";\n\n/* External Imports */\nimport '@openzeppelin/contracts/math/SafeMath.sol';\n\n/**\n * @title OVM_StateCommitmentChain\n * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which\n * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC).\n * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique\n * state root calculated off-chain by applying the canonical transactions one by one.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_StateCommitmentChain is iOVM_StateCommitmentChain, Lib_AddressResolver {\n\n    /*************\n     * Constants *\n     *************/\n\n    uint256 public FRAUD_PROOF_WINDOW;\n    uint256 public SEQUENCER_PUBLISH_WINDOW;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     */\n    constructor(\n        address _libAddressManager,\n        uint256 _fraudProofWindow,\n        uint256 _sequencerPublishWindow\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {\n        FRAUD_PROOF_WINDOW = _fraudProofWindow;\n        SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Accesses the batch storage container.\n     * @return Reference to the batch storage container.\n     */\n    function batches()\n        public\n        view\n        returns (\n            iOVM_ChainStorageContainer\n        )\n    {\n        return iOVM_ChainStorageContainer(\n            resolve(\"OVM_ChainStorageContainer-SCC-batches\")\n        );\n    }\n\n    /**\n     * @inheritdoc iOVM_StateCommitmentChain\n     */\n    function getTotalElements()\n        override\n        public\n        view\n        returns (\n            uint256 _totalElements\n        )\n    {\n        (uint40 totalElements, ) = _getBatchExtraData();\n        return uint256(totalElements);\n    }\n\n    /**\n     * @inheritdoc iOVM_StateCommitmentChain\n     */\n    function getTotalBatches()\n        override\n        public\n        view\n        returns (\n            uint256 _totalBatches\n        )\n    {\n        return batches().length();\n    }\n\n    /**\n     * @inheritdoc iOVM_StateCommitmentChain\n     */\n    function getLastSequencerTimestamp()\n        override\n        public\n        view\n        returns (\n            uint256 _lastSequencerTimestamp\n        )\n    {\n        (, uint40 lastSequencerTimestamp) = _getBatchExtraData();\n        return uint256(lastSequencerTimestamp);\n    }\n\n    /**\n     * @inheritdoc iOVM_StateCommitmentChain\n     */\n    function appendStateBatch(\n        bytes32[] memory _batch,\n        uint256 _shouldStartAtElement\n    )\n        override\n        public\n    {\n        // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the\n        // publication of batches by some other user.\n        require(\n            _shouldStartAtElement == getTotalElements(),\n            \"Actual batch start index does not match expected start index.\"\n        );\n\n        // Proposers must have previously staked at the BondManager\n        require(\n            iOVM_BondManager(resolve(\"OVM_BondManager\")).isCollateralized(msg.sender),\n            \"Proposer does not have enough collateral posted\"\n        );\n\n        require(\n            _batch.length > 0,\n            \"Cannot submit an empty state batch.\"\n        );\n\n        require(\n            getTotalElements() + _batch.length <= iOVM_CanonicalTransactionChain(resolve(\"OVM_CanonicalTransactionChain\")).getTotalElements(),\n            \"Number of state roots cannot exceed the number of canonical transactions.\"\n        );\n\n        // Pass the block's timestamp and the publisher of the data\n        // to be used in the fraud proofs\n        _appendBatch(\n            _batch,\n            abi.encode(block.timestamp, msg.sender)\n        );\n    }\n\n    /**\n     * @inheritdoc iOVM_StateCommitmentChain\n     */\n    function deleteStateBatch(\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n    )\n        override\n        public\n    {\n        require(\n            msg.sender == resolve(\"OVM_FraudVerifier\"),\n            \"State batches can only be deleted by the OVM_FraudVerifier.\"\n        );\n\n        require(\n            _isValidBatchHeader(_batchHeader),\n            \"Invalid batch header.\"\n        );\n\n        require(\n            insideFraudProofWindow(_batchHeader),\n            \"State batches can only be deleted within the fraud proof window.\"\n        );\n\n        _deleteBatch(_batchHeader);\n    }\n\n    /**\n     * @inheritdoc iOVM_StateCommitmentChain\n     */\n    function verifyStateCommitment(\n        bytes32 _element,\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _proof\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        require(\n            _isValidBatchHeader(_batchHeader),\n            \"Invalid batch header.\"\n        );\n\n        require(\n            Lib_MerkleTree.verify(\n                _batchHeader.batchRoot,\n                _element,\n                _proof.index,\n                _proof.siblings,\n                _batchHeader.batchSize\n            ),\n            \"Invalid inclusion proof.\"\n        );\n\n        return true;\n    }\n\n    /**\n     * @inheritdoc iOVM_StateCommitmentChain\n     */\n    function insideFraudProofWindow(\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n    )\n        override\n        public\n        view\n        returns (\n            bool _inside\n        )\n    {\n        (uint256 timestamp,) = abi.decode(\n            _batchHeader.extraData,\n            (uint256, address)\n        );\n\n        require(\n            timestamp != 0,\n            \"Batch header timestamp cannot be zero\"\n        );\n        return SafeMath.add(timestamp, FRAUD_PROOF_WINDOW) > block.timestamp;\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Parses the batch context from the extra data.\n     * @return Total number of elements submitted.\n     * @return Timestamp of the last batch submitted by the sequencer.\n     */\n    function _getBatchExtraData()\n        internal\n        view\n        returns (\n            uint40,\n            uint40\n        )\n    {\n        bytes27 extraData = batches().getGlobalMetadata();\n\n        uint40 totalElements;\n        uint40 lastSequencerTimestamp;\n        assembly {\n            extraData              := shr(40, extraData)\n            totalElements          :=         and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)\n            lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))\n        }\n\n        return (\n            totalElements,\n            lastSequencerTimestamp\n        );\n    }\n\n    /**\n     * Encodes the batch context for the extra data.\n     * @param _totalElements Total number of elements submitted.\n     * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer.\n     * @return Encoded batch context.\n     */\n    function _makeBatchExtraData(\n        uint40 _totalElements,\n        uint40 _lastSequencerTimestamp\n    )\n        internal\n        pure\n        returns (\n            bytes27\n        )\n    {\n        bytes27 extraData;\n        assembly {\n            extraData := _totalElements\n            extraData := or(extraData, shl(40, _lastSequencerTimestamp))\n            extraData := shl(40, extraData)\n        }\n\n        return extraData;\n    }\n\n    /**\n     * Appends a batch to the chain.\n     * @param _batch Elements within the batch.\n     * @param _extraData Any extra data to append to the batch.\n     */\n    function _appendBatch(\n        bytes32[] memory _batch,\n        bytes memory _extraData\n    )\n        internal\n    {\n        address sequencer = resolve(\"OVM_Proposer\");\n        (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData();\n\n        if (msg.sender == sequencer) {\n            lastSequencerTimestamp = uint40(block.timestamp);\n        } else {\n            // We keep track of the last batch submitted by the sequencer so there's a window in\n            // which only the sequencer can publish state roots. A window like this just reduces\n            // the chance of \"system breaking\" state roots being published while we're still in\n            // testing mode. This window should be removed or significantly reduced in the future.\n            require(\n                lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp,\n                \"Cannot publish state roots within the sequencer publication window.\"\n            );\n        }\n\n        // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place\n        // while calculating the root hash therefore any arguments passed to it must not\n        // be used again afterwards\n        Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({\n            batchIndex: getTotalBatches(),\n            batchRoot: Lib_MerkleTree.getMerkleRoot(_batch),\n            batchSize: _batch.length,\n            prevTotalElements: totalElements,\n            extraData: _extraData\n        });\n\n        emit StateBatchAppended(\n            batchHeader.batchIndex,\n            batchHeader.batchRoot,\n            batchHeader.batchSize,\n            batchHeader.prevTotalElements,\n            batchHeader.extraData\n        );\n\n        batches().push(\n            Lib_OVMCodec.hashBatchHeader(batchHeader),\n            _makeBatchExtraData(\n                uint40(batchHeader.prevTotalElements + batchHeader.batchSize),\n                lastSequencerTimestamp\n            )\n        );\n    }\n\n    /**\n     * Removes a batch and all subsequent batches from the chain.\n     * @param _batchHeader Header of the batch to remove.\n     */\n    function _deleteBatch(\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n    )\n        internal\n    {\n        require(\n            _batchHeader.batchIndex < batches().length(),\n            \"Invalid batch index.\"\n        );\n\n        require(\n            _isValidBatchHeader(_batchHeader),\n            \"Invalid batch header.\"\n        );\n\n        batches().deleteElementsAfterInclusive(\n            _batchHeader.batchIndex,\n            _makeBatchExtraData(\n                uint40(_batchHeader.prevTotalElements),\n                0\n            )\n        );\n\n        emit StateBatchDeleted(\n            _batchHeader.batchIndex,\n            _batchHeader.batchRoot\n        );\n    }\n\n    /**\n     * Checks that a batch header matches the stored hash for the given index.\n     * @param _batchHeader Batch header to validate.\n     * @return Whether or not the header matches the stored one.\n     */\n    function _isValidBatchHeader(\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n    )\n        internal\n        view\n        returns (\n            bool\n        )\n    {\n        return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/utils/Lib_MerkleTree.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title Lib_MerkleTree\n * @author River Keefer\n */\nlibrary Lib_MerkleTree {\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Calculates a merkle root for a list of 32-byte leaf hashes.  WARNING: If the number\n     * of leaves passed in is not a power of two, it pads out the tree with zero hashes.\n     * If you do not know the original length of elements for the tree you are verifying,\n     * then this may allow empty leaves past _elements.length to pass a verification check down the line.\n     * Note that the _elements argument is modified, therefore it must not be used again afterwards\n     * @param _elements Array of hashes from which to generate a merkle root.\n     * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).\n     */\n    function getMerkleRoot(\n        bytes32[] memory _elements\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        require(\n            _elements.length > 0,\n            \"Lib_MerkleTree: Must provide at least one leaf hash.\"\n        );\n\n        if (_elements.length == 1) {\n            return _elements[0];\n        }\n\n        uint256[16] memory defaults = [\n            0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,\n            0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,\n            0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,\n            0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,\n            0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,\n            0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,\n            0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,\n            0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,\n            0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,\n            0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,\n            0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,\n            0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,\n            0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,\n            0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,\n            0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,\n            0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10\n        ];\n\n        // Reserve memory space for our hashes.\n        bytes memory buf = new bytes(64);\n\n        // We'll need to keep track of left and right siblings.\n        bytes32 leftSibling;\n        bytes32 rightSibling;\n\n        // Number of non-empty nodes at the current depth.\n        uint256 rowSize = _elements.length;\n\n        // Current depth, counting from 0 at the leaves\n        uint256 depth = 0;\n\n        // Common sub-expressions\n        uint256 halfRowSize;         // rowSize / 2\n        bool rowSizeIsOdd;           // rowSize % 2 == 1\n\n        while (rowSize > 1) {\n            halfRowSize = rowSize / 2;\n            rowSizeIsOdd = rowSize % 2 == 1;\n\n            for (uint256 i = 0; i < halfRowSize; i++) {\n                leftSibling  = _elements[(2 * i)    ];\n                rightSibling = _elements[(2 * i) + 1];\n                assembly {\n                    mstore(add(buf, 32), leftSibling )\n                    mstore(add(buf, 64), rightSibling)\n                }\n\n                _elements[i] = keccak256(buf);\n            }\n\n            if (rowSizeIsOdd) {\n                leftSibling  = _elements[rowSize - 1];\n                rightSibling = bytes32(defaults[depth]);\n                assembly {\n                    mstore(add(buf, 32), leftSibling)\n                    mstore(add(buf, 64), rightSibling)\n                }\n\n                _elements[halfRowSize] = keccak256(buf);\n            }\n\n            rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);\n            depth++;\n        }\n\n        return _elements[0];\n    }\n\n    /**\n     * Verifies a merkle branch for the given leaf hash.  Assumes the original length\n     * of leaves generated is a known, correct input, and does not return true for indices\n     * extending past that index (even if _siblings would be otherwise valid.)\n     * @param _root The Merkle root to verify against.\n     * @param _leaf The leaf hash to verify inclusion of.\n     * @param _index The index in the tree of this leaf.\n     * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 (bottom of the tree).\n     * @param _totalLeaves The total number of leaves originally passed into.\n     * @return Whether or not the merkle branch and leaf passes verification.\n     */\n    function verify(\n        bytes32 _root,\n        bytes32 _leaf,\n        uint256 _index,\n        bytes32[] memory _siblings,\n        uint256 _totalLeaves\n    )\n        internal\n        pure\n        returns (\n            bool\n        )\n    {\n        require(\n            _totalLeaves > 0,\n            \"Lib_MerkleTree: Total leaves must be greater than zero.\"\n        );\n\n        require(\n            _index < _totalLeaves,\n            \"Lib_MerkleTree: Index out of bounds.\"\n        );\n\n        require(\n            _siblings.length == _ceilLog2(_totalLeaves),\n            \"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves.\"\n        );\n\n        bytes32 computedRoot = _leaf;\n\n        for (uint256 i = 0; i < _siblings.length; i++) {\n            if ((_index & 1) == 1) {\n                computedRoot = keccak256(\n                    abi.encodePacked(\n                        _siblings[i],\n                        computedRoot\n                    )\n                );\n            } else {\n                computedRoot = keccak256(\n                    abi.encodePacked(\n                        computedRoot,\n                        _siblings[i]\n                    )\n                );\n            }\n\n            _index >>= 1;\n        }\n\n        return _root == computedRoot;\n    }\n\n\n    /*********************\n     * Private Functions *\n     *********************/\n\n    /**\n     * Calculates the integer ceiling of the log base 2 of an input.\n     * @param _in Unsigned input to calculate the log.\n     * @return ceil(log_base_2(_in))\n     */\n    function _ceilLog2(\n        uint256 _in\n    )\n        private\n        pure\n        returns (\n            uint256\n        )\n    {\n        require(\n            _in > 0,\n            \"Lib_MerkleTree: Cannot compute ceil(log_2) of 0.\"\n        );\n\n        if (_in == 1) {\n            return 0;\n        }\n\n        // Find the highest set bit (will be floor(log_2)).\n        // Borrowed with <3 from https://github.com/ethereum/solidity-examples\n        uint256 val = _in;\n        uint256 highest = 0;\n        for (uint256 i = 128; i >= 1; i >>= 1) {\n            if (val & (uint(1) << i) - 1 << i != 0) {\n                highest += i;\n                val >>= i;\n            }\n        }\n\n        // Increment by one if this is not a perfect logarithm.\n        if ((uint(1) << highest) != _in) {\n            highest += 1;\n        }\n\n        return highest;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/chain/OVM_ChainStorageContainer.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_Buffer } from \"../../libraries/utils/Lib_Buffer.sol\";\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\n\n/* Interface Imports */\nimport { iOVM_ChainStorageContainer } from \"../../iOVM/chain/iOVM_ChainStorageContainer.sol\";\n\n/**\n * @title OVM_ChainStorageContainer\n * @dev The Chain Storage Container provides its owner contract with read, write and delete functionality.\n * This provides gas efficiency gains by enabling it to overwrite storage slots which can no longer be used\n * in a fraud proof due to the fraud window having passed, and the associated chain state or\n * transactions being finalized.\n * Three distinct Chain Storage Containers will be deployed on Layer 1:\n * 1. Stores transaction batches for the Canonical Transaction Chain\n * 2. Stores queued transactions for the Canonical Transaction Chain\n * 3. Stores chain state batches for the State Commitment Chain\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_ChainStorageContainer is iOVM_ChainStorageContainer, Lib_AddressResolver {\n\n    /*************\n     * Libraries *\n     *************/\n\n    using Lib_Buffer for Lib_Buffer.Buffer;\n\n\n    /*************\n     * Variables *\n     *************/\n\n    string public owner;\n    Lib_Buffer.Buffer internal buffer;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     * @param _owner Name of the contract that owns this container (will be resolved later).\n     */\n    constructor(\n        address _libAddressManager,\n        string memory _owner\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {\n        owner = _owner;\n    }\n\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    modifier onlyOwner() {\n        require(\n            msg.sender == resolve(owner),\n            \"OVM_ChainStorageContainer: Function can only be called by the owner.\"\n        );\n        _;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function setGlobalMetadata(\n        bytes27 _globalMetadata\n    )\n        override\n        public\n        onlyOwner\n    {\n        return buffer.setExtraData(_globalMetadata);\n    }\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function getGlobalMetadata()\n        override\n        public\n        view\n        returns (\n            bytes27\n        )\n    {\n        return buffer.getExtraData();\n    }\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function length()\n        override\n        public\n        view\n        returns (\n            uint256\n        )\n    {\n        return uint256(buffer.getLength());\n    }\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function push(\n        bytes32 _object\n    )\n        override\n        public\n        onlyOwner\n    {\n        buffer.push(_object);\n    }\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function push(\n        bytes32 _object,\n        bytes27 _globalMetadata\n    )\n        override\n        public\n        onlyOwner\n    {\n        buffer.push(_object, _globalMetadata);\n    }\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function get(\n        uint256 _index\n    )\n        override\n        public\n        view\n        returns (\n            bytes32\n        )\n    {\n        return buffer.get(uint40(_index));\n    }\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function deleteElementsAfterInclusive(\n        uint256 _index\n    )\n        override\n        public\n        onlyOwner\n    {\n        buffer.deleteElementsAfterInclusive(\n            uint40(_index)\n        );\n    }\n\n    /**\n     * @inheritdoc iOVM_ChainStorageContainer\n     */\n    function deleteElementsAfterInclusive(\n        uint256 _index,\n        bytes27 _globalMetadata\n    )\n        override\n        public\n        onlyOwner\n    {\n        buffer.deleteElementsAfterInclusive(\n            uint40(_index),\n            _globalMetadata\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/utils/Lib_Buffer.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title Lib_Buffer\n * @dev This library implements a bytes32 storage array with some additional gas-optimized\n * functionality. In particular, it encodes its length as a uint40, and tightly packs this with an\n * overwritable \"extra data\" field so we can store more information with a single SSTORE.\n */\nlibrary Lib_Buffer {\n\n    /*************\n     * Libraries *\n     *************/\n\n    using Lib_Buffer for Buffer;\n\n\n    /***********\n     * Structs *\n     ***********/\n\n    struct Buffer {\n        bytes32 context;\n        mapping (uint256 => bytes32) buf;\n    }\n\n    struct BufferContext {\n        // Stores the length of the array. Uint40 is way more elements than we'll ever reasonably\n        // need in an array and we get an extra 27 bytes of extra data to play with.\n        uint40 length;\n\n        // Arbitrary extra data that can be modified whenever the length is updated. Useful for\n        // squeezing out some gas optimizations.\n        bytes27 extraData;\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Pushes a single element to the buffer.\n     * @param _self Buffer to access.\n     * @param _value Value to push to the buffer.\n     * @param _extraData Global extra data.\n     */\n    function push(\n        Buffer storage _self,\n        bytes32 _value,\n        bytes27 _extraData\n    )\n        internal\n    {\n        BufferContext memory ctx = _self.getContext();\n\n        _self.buf[ctx.length] = _value;\n\n        // Bump the global index and insert our extra data, then save the context.\n        ctx.length++;\n        ctx.extraData = _extraData;\n        _self.setContext(ctx);\n    }\n\n    /**\n     * Pushes a single element to the buffer.\n     * @param _self Buffer to access.\n     * @param _value Value to push to the buffer.\n     */\n    function push(\n        Buffer storage _self,\n        bytes32 _value\n    )\n        internal\n    {\n        BufferContext memory ctx = _self.getContext();\n\n        _self.push(\n            _value,\n            ctx.extraData\n        );\n    }\n\n    /**\n     * Retrieves an element from the buffer.\n     * @param _self Buffer to access.\n     * @param _index Element index to retrieve.\n     * @return Value of the element at the given index.\n     */\n    function get(\n        Buffer storage _self,\n        uint256 _index\n    )\n        internal\n        view\n        returns (\n            bytes32\n        )\n    {\n        BufferContext memory ctx = _self.getContext();\n\n        require(\n            _index < ctx.length,\n            \"Index out of bounds.\"\n        );\n\n        return _self.buf[_index];\n    }\n\n    /**\n     * Deletes all elements after (and including) a given index.\n     * @param _self Buffer to access.\n     * @param _index Index of the element to delete from (inclusive).\n     * @param _extraData Optional global extra data.\n     */\n    function deleteElementsAfterInclusive(\n        Buffer storage _self,\n        uint40 _index,\n        bytes27 _extraData\n    )\n        internal\n    {\n        BufferContext memory ctx = _self.getContext();\n\n        require(\n            _index < ctx.length,\n            \"Index out of bounds.\"\n        );\n\n        // Set our length and extra data, save the context.\n        ctx.length = _index;\n        ctx.extraData = _extraData;\n        _self.setContext(ctx);\n    }\n\n    /**\n     * Deletes all elements after (and including) a given index.\n     * @param _self Buffer to access.\n     * @param _index Index of the element to delete from (inclusive).\n     */\n    function deleteElementsAfterInclusive(\n        Buffer storage _self,\n        uint40 _index\n    )\n        internal\n    {\n        BufferContext memory ctx = _self.getContext();\n        _self.deleteElementsAfterInclusive(\n            _index,\n            ctx.extraData\n        );\n    }\n\n    /**\n     * Retrieves the current global index.\n     * @param _self Buffer to access.\n     * @return Current global index.\n     */\n    function getLength(\n        Buffer storage _self\n    )\n        internal\n        view\n        returns (\n            uint40\n        )\n    {\n        BufferContext memory ctx = _self.getContext();\n        return ctx.length;\n    }\n\n    /**\n     * Changes current global extra data.\n     * @param _self Buffer to access.\n     * @param _extraData New global extra data.\n     */\n    function setExtraData(\n        Buffer storage _self,\n        bytes27 _extraData\n    )\n        internal\n    {\n        BufferContext memory ctx = _self.getContext();\n        ctx.extraData = _extraData;\n        _self.setContext(ctx);\n    }\n\n    /**\n     * Retrieves the current global extra data.\n     * @param _self Buffer to access.\n     * @return Current global extra data.\n     */\n    function getExtraData(\n        Buffer storage _self\n    )\n        internal\n        view\n        returns (\n            bytes27\n        )\n    {\n        BufferContext memory ctx = _self.getContext();\n        return ctx.extraData;\n    }\n\n    /**\n     * Sets the current buffer context.\n     * @param _self Buffer to access.\n     * @param _ctx Current buffer context.\n     */\n    function setContext(\n        Buffer storage _self,\n        BufferContext memory _ctx\n    )\n        internal\n    {\n        bytes32 context;\n        uint40 length = _ctx.length;\n        bytes27 extraData = _ctx.extraData;\n        assembly {\n            context := length\n            context := or(context, extraData)\n        }\n\n        if (_self.context != context) {\n            _self.context = context;\n        }\n    }\n\n    /**\n     * Retrieves the current buffer context.\n     * @param _self Buffer to access.\n     * @return Current buffer context.\n     */\n    function getContext(\n        Buffer storage _self\n    )\n        internal\n        view\n        returns (\n            BufferContext memory\n        )\n    {\n        bytes32 context = _self.context;\n        uint40 length;\n        bytes27 extraData;\n        assembly {\n            length    := and(context, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)\n            extraData := and(context, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)\n        }\n\n        return BufferContext({\n            length: length,\n            extraData: extraData\n        });\n    }\n}\n"
    },
    "contracts/test-libraries/utils/TestLib_Buffer.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_Buffer } from \"../../optimistic-ethereum/libraries/utils/Lib_Buffer.sol\";\n\n/**\n * @title TestLib_Buffer\n */\ncontract TestLib_Buffer {\n    using Lib_Buffer for Lib_Buffer.Buffer;\n\n    Lib_Buffer.Buffer internal buf;\n\n    function push(\n        bytes32 _value,\n        bytes27 _extraData\n    )\n        public\n    {\n        buf.push(\n            _value,\n            _extraData\n        );\n    }\n\n    function get(\n        uint256 _index\n    )\n        public\n        view\n        returns (\n            bytes32\n        )\n    {\n        return buf.get(_index);\n    }\n\n    function deleteElementsAfterInclusive(\n        uint40 _index\n    )\n        public\n    {\n        return buf.deleteElementsAfterInclusive(\n            _index\n        );\n    }\n\n    function deleteElementsAfterInclusive(\n        uint40 _index,\n        bytes27 _extraData\n    )\n        public\n    {\n        return buf.deleteElementsAfterInclusive(\n            _index,\n            _extraData\n        );\n    }\n\n    function getLength()\n        public\n        view\n        returns (\n            uint40\n        )\n    {\n        return buf.getLength();\n    }\n\n    function setExtraData(\n        bytes27 _extraData\n    )\n        public\n    {\n        return buf.setExtraData(\n            _extraData\n        );\n    }\n\n    function getExtraData()\n        public\n        view\n        returns (\n            bytes27\n        )\n    {\n        return buf.getExtraData();\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/chain/OVM_CanonicalTransactionChain.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\nimport { Lib_MerkleTree } from \"../../libraries/utils/Lib_MerkleTree.sol\";\n\n/* Interface Imports */\nimport { iOVM_CanonicalTransactionChain } from \"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol\";\nimport { iOVM_ChainStorageContainer } from \"../../iOVM/chain/iOVM_ChainStorageContainer.sol\";\n\n/* Contract Imports */\nimport { OVM_ExecutionManager } from \"../execution/OVM_ExecutionManager.sol\";\n\n/* External Imports */\nimport { Math } from \"@openzeppelin/contracts/math/Math.sol\";\n\n/**\n * @title OVM_CanonicalTransactionChain\n * @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions\n * which must be applied to the rollup state. It defines the ordering of rollup transactions by\n * writing them to the 'CTC:batches' instance of the Chain Storage Container.\n * The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the Sequencer\n * will eventually append it to the rollup state.\n * If the Sequencer does not include an enqueued transaction within the 'force inclusion period',\n * then any account may force it to be included by calling appendQueueBatch().\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_CanonicalTransactionChain is iOVM_CanonicalTransactionChain, Lib_AddressResolver {\n\n    /*************\n     * Constants *\n     *************/\n\n    // L2 tx gas-related\n    uint256 constant public MIN_ROLLUP_TX_GAS = 100000;\n    uint256 constant public MAX_ROLLUP_TX_SIZE = 50000;\n    uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32;\n\n    // Encoding-related (all in bytes)\n    uint256 constant internal BATCH_CONTEXT_SIZE = 16;\n    uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12;\n    uint256 constant internal BATCH_CONTEXT_START_POS = 15;\n    uint256 constant internal TX_DATA_HEADER_SIZE = 3;\n    uint256 constant internal BYTES_TILL_TX_DATA = 65;\n\n\n    /*************\n     * Variables *\n     *************/\n\n    uint256 public forceInclusionPeriodSeconds;\n    uint256 public forceInclusionPeriodBlocks;\n    uint256 public maxTransactionGasLimit;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    constructor(\n        address _libAddressManager,\n        uint256 _forceInclusionPeriodSeconds,\n        uint256 _forceInclusionPeriodBlocks,\n        uint256 _maxTransactionGasLimit\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {\n        forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds;\n        forceInclusionPeriodBlocks = _forceInclusionPeriodBlocks;\n        maxTransactionGasLimit = _maxTransactionGasLimit;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Accesses the batch storage container.\n     * @return Reference to the batch storage container.\n     */\n    function batches()\n        override\n        public\n        view\n        returns (\n            iOVM_ChainStorageContainer\n        )\n    {\n        return iOVM_ChainStorageContainer(\n            resolve(\"OVM_ChainStorageContainer-CTC-batches\")\n        );\n    }\n\n    /**\n     * Accesses the queue storage container.\n     * @return Reference to the queue storage container.\n     */\n    function queue()\n        override\n        public\n        view\n        returns (\n            iOVM_ChainStorageContainer\n        )\n    {\n        return iOVM_ChainStorageContainer(\n            resolve(\"OVM_ChainStorageContainer-CTC-queue\")\n        );\n    }\n\n    /**\n     * Retrieves the total number of elements submitted.\n     * @return _totalElements Total submitted elements.\n     */\n    function getTotalElements()\n        override\n        public\n        view\n        returns (\n            uint256 _totalElements\n        )\n    {\n        (uint40 totalElements,,,) = _getBatchExtraData();\n        return uint256(totalElements);\n    }\n\n    /**\n     * Retrieves the total number of batches submitted.\n     * @return _totalBatches Total submitted batches.\n     */\n    function getTotalBatches()\n        override\n        public\n        view\n        returns (\n            uint256 _totalBatches\n        )\n    {\n        return batches().length();\n    }\n\n    /**\n     * Returns the index of the next element to be enqueued.\n     * @return Index for the next queue element.\n     */\n    function getNextQueueIndex()\n        override\n        public\n        view\n        returns (\n            uint40\n        )\n    {\n        (,uint40 nextQueueIndex,,) = _getBatchExtraData();\n        return nextQueueIndex;\n    }\n\n    /**\n     * Returns the timestamp of the last transaction.\n     * @return Timestamp for the last transaction.\n     */\n    function getLastTimestamp()\n        override\n        public\n        view\n        returns (\n            uint40\n        )\n    {\n        (,,uint40 lastTimestamp,) = _getBatchExtraData();\n        return lastTimestamp;\n    }\n\n    /**\n     * Returns the blocknumber of the last transaction.\n     * @return Blocknumber for the last transaction.\n     */\n    function getLastBlockNumber()\n        override\n        public\n        view\n        returns (\n            uint40\n        )\n    {\n        (,,,uint40 lastBlockNumber) = _getBatchExtraData();\n        return lastBlockNumber;\n    }\n\n    /**\n     * Gets the queue element at a particular index.\n     * @param _index Index of the queue element to access.\n     * @return _element Queue element at the given index.\n     */\n    function getQueueElement(\n        uint256 _index\n    )\n        override\n        public\n        view\n        returns (\n            Lib_OVMCodec.QueueElement memory _element\n        )\n    {\n        return _getQueueElement(\n            _index,\n            queue()\n        );\n    }\n\n    /**\n     * Get the number of queue elements which have not yet been included.\n     * @return Number of pending queue elements.\n     */\n    function getNumPendingQueueElements()\n        override\n        public\n        view\n        returns (\n            uint40\n        )\n    {\n        return getQueueLength() - getNextQueueIndex();\n    }\n\n   /**\n     * Retrieves the length of the queue, including\n     * both pending and canonical transactions.\n     * @return Length of the queue.\n     */\n    function getQueueLength()\n        override\n        public\n        view\n        returns (\n            uint40\n        )\n    {\n        return _getQueueLength(\n            queue()\n        );\n    }\n\n    /**\n     * Adds a transaction to the queue.\n     * @param _target Target L2 contract to send the transaction to.\n     * @param _gasLimit Gas limit for the enqueued L2 transaction.\n     * @param _data Transaction data.\n     */\n    function enqueue(\n        address _target,\n        uint256 _gasLimit,\n        bytes memory _data\n    )\n        override\n        public\n    {\n        require(\n            _data.length <= MAX_ROLLUP_TX_SIZE,\n            \"Transaction data size exceeds maximum for rollup transaction.\"\n        );\n\n        require(\n            _gasLimit <= maxTransactionGasLimit,\n            \"Transaction gas limit exceeds maximum for rollup transaction.\"\n        );\n\n        require(\n            _gasLimit >= MIN_ROLLUP_TX_GAS,\n            \"Transaction gas limit too low to enqueue.\"\n        );\n\n        // We need to consume some amount of L1 gas in order to rate limit transactions going into\n        // L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the\n        // provided L1 gas.\n        uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR;\n        uint256 startingGas = gasleft();\n\n        // Although this check is not necessary (burn below will run out of gas if not true), it\n        // gives the user an explicit reason as to why the enqueue attempt failed.\n        require(\n            startingGas > gasToConsume,\n            \"Insufficient gas for L2 rate limiting burn.\"\n        );\n\n        // Here we do some \"dumb\" work in order to burn gas, although we should probably replace\n        // this with something like minting gas token later on.\n        uint256 i;\n        while(startingGas - gasleft() < gasToConsume) {\n            i++;\n        }\n\n        bytes32 transactionHash = keccak256(\n            abi.encode(\n                msg.sender,\n                _target,\n                _gasLimit,\n                _data\n            )\n        );\n\n        bytes32 timestampAndBlockNumber;\n        assembly {\n            timestampAndBlockNumber := timestamp()\n            timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number()))\n        }\n\n        iOVM_ChainStorageContainer queueRef = queue();\n\n        queueRef.push(transactionHash);\n        queueRef.push(timestampAndBlockNumber);\n\n        // The underlying queue data structure stores 2 elements\n        // per insertion, so to get the real queue length we need\n        // to divide by 2 and subtract 1.\n        uint256 queueIndex = queueRef.length() / 2 - 1;\n        emit TransactionEnqueued(\n            msg.sender,\n            _target,\n            _gasLimit,\n            _data,\n            queueIndex,\n            block.timestamp\n        );\n    }\n\n    /**\n     * Appends a given number of queued transactions as a single batch.\n     * param _numQueuedTransactions Number of transactions to append.\n     */\n    function appendQueueBatch(\n        uint256 // _numQueuedTransactions\n    )\n        override\n        public\n        pure\n    {\n        // TEMPORARY: Disable `appendQueueBatch` for minnet\n        revert(\"appendQueueBatch is currently disabled.\");\n\n        // _numQueuedTransactions = Math.min(_numQueuedTransactions, getNumPendingQueueElements());\n        // require(\n        //     _numQueuedTransactions > 0,\n        //     \"Must append more than zero transactions.\"\n        // );\n\n        // bytes32[] memory leaves = new bytes32[](_numQueuedTransactions);\n        // uint40 nextQueueIndex = getNextQueueIndex();\n\n        // for (uint256 i = 0; i < _numQueuedTransactions; i++) {\n        //     if (msg.sender != resolve(\"OVM_Sequencer\")) {\n        //         Lib_OVMCodec.QueueElement memory el = getQueueElement(nextQueueIndex);\n        //         require(\n        //             el.timestamp + forceInclusionPeriodSeconds < block.timestamp,\n        //             \"Queue transactions cannot be submitted during the sequencer inclusion period.\"\n        //         );\n        //     }\n        //     leaves[i] = _getQueueLeafHash(nextQueueIndex);\n        //     nextQueueIndex++;\n        // }\n\n        // Lib_OVMCodec.QueueElement memory lastElement = getQueueElement(nextQueueIndex - 1);\n\n        // _appendBatch(\n        //     Lib_MerkleTree.getMerkleRoot(leaves),\n        //     _numQueuedTransactions,\n        //     _numQueuedTransactions,\n        //     lastElement.timestamp,\n        //     lastElement.blockNumber\n        // );\n\n        // emit QueueBatchAppended(\n        //     nextQueueIndex - _numQueuedTransactions,\n        //     _numQueuedTransactions,\n        //     getTotalElements()\n        // );\n    }\n\n    /**\n     * Allows the sequencer to append a batch of transactions.\n     * @dev This function uses a custom encoding scheme for efficiency reasons.\n     * .param _shouldStartAtElement Specific batch we expect to start appending to.\n     * .param _totalElementsToAppend Total number of batch elements we expect to append.\n     * .param _contexts Array of batch contexts.\n     * .param _transactionDataFields Array of raw transaction data.\n     */\n    function appendSequencerBatch()\n        override\n        public\n    {\n        uint40 shouldStartAtElement;\n        uint24 totalElementsToAppend;\n        uint24 numContexts;\n        assembly {\n            shouldStartAtElement  := shr(216, calldataload(4))\n            totalElementsToAppend := shr(232, calldataload(9))\n            numContexts           := shr(232, calldataload(12))\n        }\n\n        require(\n            shouldStartAtElement == getTotalElements(),\n            \"Actual batch start index does not match expected start index.\"\n        );\n\n        require(\n            msg.sender == resolve(\"OVM_Sequencer\"),\n            \"Function can only be called by the Sequencer.\"\n        );\n\n        require(\n            numContexts > 0,\n            \"Must provide at least one batch context.\"\n        );\n\n        require(\n            totalElementsToAppend > 0,\n            \"Must append at least one element.\"\n        );\n\n        uint40 nextTransactionPtr = uint40(BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts);\n\n        require(\n            msg.data.length >= nextTransactionPtr,\n            \"Not enough BatchContexts provided.\"\n        );\n\n        // Take a reference to the queue and its length so we don't have to keep resolving it.\n        // Length isn't going to change during the course of execution, so it's fine to simply\n        // resolve this once at the start. Saves gas.\n        iOVM_ChainStorageContainer queueRef = queue();\n        uint40 queueLength = _getQueueLength(queueRef);\n\n        // Reserve some memory to save gas on hashing later on. This is a relatively safe estimate\n        // for the average transaction size that will prevent having to resize this chunk of memory\n        // later on. Saves gas.\n        bytes memory hashMemory = new bytes((msg.data.length / totalElementsToAppend) * 2);\n\n        // Initialize the array of canonical chain leaves that we will append.\n        bytes32[] memory leaves = new bytes32[](totalElementsToAppend);\n\n        // Each leaf index corresponds to a tx, either sequenced or enqueued.\n        uint32 leafIndex = 0;\n\n        // Counter for number of sequencer transactions appended so far.\n        uint32 numSequencerTransactions = 0;\n\n        // We will sequentially append leaves which are pointers to the queue.\n        // The initial queue index is what is currently in storage.\n        uint40 nextQueueIndex = getNextQueueIndex();\n\n        BatchContext memory curContext;\n        for (uint32 i = 0; i < numContexts; i++) {\n            BatchContext memory nextContext = _getBatchContext(i);\n\n            if (i == 0) {\n                // Execute a special check for the first batch.\n                _validateFirstBatchContext(nextContext);\n            }\n\n            // Execute this check on every single batch, including the first one.\n            _validateNextBatchContext(\n                curContext,\n                nextContext,\n                nextQueueIndex,\n                queueRef\n            );\n\n            // Now we can update our current context.\n            curContext = nextContext;\n\n            // Process sequencer transactions first.\n            for (uint32 j = 0; j < curContext.numSequencedTransactions; j++) {\n                uint256 txDataLength;\n                assembly {\n                    txDataLength := shr(232, calldataload(nextTransactionPtr))\n                }\n                require(\n                    txDataLength <= MAX_ROLLUP_TX_SIZE,\n                    \"Transaction data size exceeds maximum for rollup transaction.\"\n                );\n\n                leaves[leafIndex] = _getSequencerLeafHash(\n                    curContext,\n                    nextTransactionPtr,\n                    txDataLength,\n                    hashMemory\n                );\n\n                nextTransactionPtr += uint40(TX_DATA_HEADER_SIZE + txDataLength);\n                numSequencerTransactions++;\n                leafIndex++;\n            }\n\n            // Now process any subsequent queue transactions.\n            for (uint32 j = 0; j < curContext.numSubsequentQueueTransactions; j++) {\n                require(\n                    nextQueueIndex < queueLength,\n                    \"Not enough queued transactions to append.\"\n                );\n\n                leaves[leafIndex] = _getQueueLeafHash(nextQueueIndex);\n                nextQueueIndex++;\n                leafIndex++;\n            }\n        }\n\n        _validateFinalBatchContext(\n            curContext,\n            nextQueueIndex,\n            queueLength,\n            queueRef\n        );\n\n        require(\n            msg.data.length == nextTransactionPtr,\n            \"Not all sequencer transactions were processed.\"\n        );\n\n        require(\n            leafIndex == totalElementsToAppend,\n            \"Actual transaction index does not match expected total elements to append.\"\n        );\n\n        // Generate the required metadata that we need to append this batch\n        uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;\n        uint40 blockTimestamp;\n        uint40 blockNumber;\n        if (curContext.numSubsequentQueueTransactions == 0) {\n            // The last element is a sequencer tx, therefore pull timestamp and block number from the last context.\n            blockTimestamp = uint40(curContext.timestamp);\n            blockNumber = uint40(curContext.blockNumber);\n        } else {\n            // The last element is a queue tx, therefore pull timestamp and block number from the queue element.\n            // curContext.numSubsequentQueueTransactions > 0 which means that we've processed at least one queue element.\n            // We increment nextQueueIndex after processing each queue element,\n            // so the index of the last element we processed is nextQueueIndex - 1.\n            Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement(\n                nextQueueIndex - 1,\n                queueRef\n            );\n\n            blockTimestamp = lastElement.timestamp;\n            blockNumber = lastElement.blockNumber;\n        }\n\n        // For efficiency reasons getMerkleRoot modifies the `leaves` argument in place\n        // while calculating the root hash therefore any arguments passed to it must not\n        // be used again afterwards\n        _appendBatch(\n            Lib_MerkleTree.getMerkleRoot(leaves),\n            totalElementsToAppend,\n            numQueuedTransactions,\n            blockTimestamp,\n            blockNumber\n        );\n\n        emit SequencerBatchAppended(\n            nextQueueIndex - numQueuedTransactions,\n            numQueuedTransactions,\n            getTotalElements()\n        );\n    }\n\n    /**\n     * Verifies whether a transaction is included in the chain.\n     * @param _transaction Transaction to verify.\n     * @param _txChainElement Transaction chain element corresponding to the transaction.\n     * @param _batchHeader Header of the batch the transaction was included in.\n     * @param _inclusionProof Inclusion proof for the provided transaction chain element.\n     * @return True if the transaction exists in the CTC, false if not.\n     */\n    function verifyTransaction(\n        Lib_OVMCodec.Transaction memory _transaction,\n        Lib_OVMCodec.TransactionChainElement memory _txChainElement,\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _inclusionProof\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        if (_txChainElement.isSequenced == true) {\n            return _verifySequencerTransaction(\n                _transaction,\n                _txChainElement,\n                _batchHeader,\n                _inclusionProof\n            );\n        } else {\n            return _verifyQueueTransaction(\n                _transaction,\n                _txChainElement.queueIndex,\n                _batchHeader,\n                _inclusionProof\n            );\n        }\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Returns the BatchContext located at a particular index.\n     * @param _index The index of the BatchContext\n     * @return The BatchContext at the specified index.\n     */\n    function _getBatchContext(\n        uint256 _index\n    )\n        internal\n        pure\n        returns (\n            BatchContext memory\n        )\n    {\n        uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;\n        uint256 numSequencedTransactions;\n        uint256 numSubsequentQueueTransactions;\n        uint256 ctxTimestamp;\n        uint256 ctxBlockNumber;\n\n        assembly {\n            numSequencedTransactions       := shr(232, calldataload(contextPtr))\n            numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))\n            ctxTimestamp                   := shr(216, calldataload(add(contextPtr, 6)))\n            ctxBlockNumber                 := shr(216, calldataload(add(contextPtr, 11)))\n        }\n\n        return BatchContext({\n            numSequencedTransactions: numSequencedTransactions,\n            numSubsequentQueueTransactions: numSubsequentQueueTransactions,\n            timestamp: ctxTimestamp,\n            blockNumber: ctxBlockNumber\n        });\n    }\n\n    /**\n     * Parses the batch context from the extra data.\n     * @return Total number of elements submitted.\n     * @return Index of the next queue element.\n     */\n    function _getBatchExtraData()\n        internal\n        view\n        returns (\n            uint40,\n            uint40,\n            uint40,\n            uint40\n        )\n    {\n        bytes27 extraData = batches().getGlobalMetadata();\n\n        uint40 totalElements;\n        uint40 nextQueueIndex;\n        uint40 lastTimestamp;\n        uint40 lastBlockNumber;\n        assembly {\n            extraData       :=  shr(40, extraData)\n            totalElements   :=  and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)\n            nextQueueIndex  :=  shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000))\n            lastTimestamp   :=  shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000))\n            lastBlockNumber :=  shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000))\n        }\n\n        return (\n            totalElements,\n            nextQueueIndex,\n            lastTimestamp,\n            lastBlockNumber\n        );\n    }\n\n    /**\n     * Encodes the batch context for the extra data.\n     * @param _totalElements Total number of elements submitted.\n     * @param _nextQueueIndex Index of the next queue element.\n     * @param _timestamp Timestamp for the last batch.\n     * @param _blockNumber Block number of the last batch.\n     * @return Encoded batch context.\n     */\n    function _makeBatchExtraData(\n        uint40 _totalElements,\n        uint40 _nextQueueIndex,\n        uint40 _timestamp,\n        uint40 _blockNumber\n    )\n        internal\n        pure\n        returns (\n            bytes27\n        )\n    {\n        bytes27 extraData;\n        assembly {\n            extraData := _totalElements\n            extraData := or(extraData, shl(40, _nextQueueIndex))\n            extraData := or(extraData, shl(80, _timestamp))\n            extraData := or(extraData, shl(120, _blockNumber))\n            extraData := shl(40, extraData)\n        }\n\n        return extraData;\n    }\n\n    /**\n     * Retrieves the hash of a queue element.\n     * @param _index Index of the queue element to retrieve a hash for.\n     * @return Hash of the queue element.\n     */\n    function _getQueueLeafHash(\n        uint256 _index\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return _hashTransactionChainElement(\n            Lib_OVMCodec.TransactionChainElement({\n                isSequenced: false,\n                queueIndex: _index,\n                timestamp: 0,\n                blockNumber: 0,\n                txData: hex\"\"\n            })\n        );\n    }\n\n    /**\n     * Gets the queue element at a particular index.\n     * @param _index Index of the queue element to access.\n     * @return _element Queue element at the given index.\n     */\n    function _getQueueElement(\n        uint256 _index,\n        iOVM_ChainStorageContainer _queueRef\n    )\n        internal\n        view\n        returns (\n            Lib_OVMCodec.QueueElement memory _element\n        )\n    {\n        // The underlying queue data structure stores 2 elements\n        // per insertion, so to get the actual desired queue index\n        // we need to multiply by 2.\n        uint40 trueIndex = uint40(_index * 2);\n        bytes32 transactionHash = _queueRef.get(trueIndex);\n        bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1);\n\n        uint40 elementTimestamp;\n        uint40 elementBlockNumber;\n        assembly {\n            elementTimestamp   :=         and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)\n            elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))\n        }\n\n        return Lib_OVMCodec.QueueElement({\n            transactionHash: transactionHash,\n            timestamp: elementTimestamp,\n            blockNumber: elementBlockNumber\n        });\n    }\n\n    /**\n     * Retrieves the length of the queue.\n     * @return Length of the queue.\n     */\n    function _getQueueLength(\n        iOVM_ChainStorageContainer _queueRef\n    )\n        internal\n        view\n        returns (\n            uint40\n        )\n    {\n        // The underlying queue data structure stores 2 elements\n        // per insertion, so to get the real queue length we need\n        // to divide by 2.\n        return uint40(_queueRef.length() / 2);\n    }\n\n    /**\n     * Retrieves the hash of a sequencer element.\n     * @param _context Batch context for the given element.\n     * @param _nextTransactionPtr Pointer to the next transaction in the calldata.\n     * @param _txDataLength Length of the transaction item.\n     * @return Hash of the sequencer element.\n     */\n    function _getSequencerLeafHash(\n        BatchContext memory _context,\n        uint256 _nextTransactionPtr,\n        uint256 _txDataLength,\n        bytes memory _hashMemory\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        // Only allocate more memory if we didn't reserve enough to begin with.\n        if (BYTES_TILL_TX_DATA + _txDataLength > _hashMemory.length) {\n            _hashMemory = new bytes(BYTES_TILL_TX_DATA + _txDataLength);\n        }\n\n        uint256 ctxTimestamp = _context.timestamp;\n        uint256 ctxBlockNumber = _context.blockNumber;\n\n        bytes32 leafHash;\n        assembly {\n            let chainElementStart := add(_hashMemory, 0x20)\n\n            // Set the first byte equal to `1` to indicate this is a sequencer chain element.\n            // This distinguishes sequencer ChainElements from queue ChainElements because\n            // all queue ChainElements are ABI encoded and the first byte of ABI encoded\n            // elements is always zero\n            mstore8(chainElementStart, 1)\n\n            mstore(add(chainElementStart, 1), ctxTimestamp)\n            mstore(add(chainElementStart, 33), ctxBlockNumber)\n\n            calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength)\n\n            leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength))\n        }\n\n        return leafHash;\n    }\n\n    /**\n     * Retrieves the hash of a sequencer element.\n     * @param _txChainElement The chain element which is hashed to calculate the leaf.\n     * @return Hash of the sequencer element.\n     */\n    function _getSequencerLeafHash(\n        Lib_OVMCodec.TransactionChainElement memory _txChainElement\n    )\n        internal\n        view\n        returns(\n            bytes32\n        )\n    {\n        bytes memory txData = _txChainElement.txData;\n        uint256 txDataLength = _txChainElement.txData.length;\n\n        bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength);\n        uint256 ctxTimestamp = _txChainElement.timestamp;\n        uint256 ctxBlockNumber = _txChainElement.blockNumber;\n\n        bytes32 leafHash;\n        assembly {\n            let chainElementStart := add(chainElement, 0x20)\n\n            // Set the first byte equal to `1` to indicate this is a sequencer chain element.\n            // This distinguishes sequencer ChainElements from queue ChainElements because\n            // all queue ChainElements are ABI encoded and the first byte of ABI encoded\n            // elements is always zero\n            mstore8(chainElementStart, 1)\n\n            mstore(add(chainElementStart, 1), ctxTimestamp)\n            mstore(add(chainElementStart, 33), ctxBlockNumber)\n\n            pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength))\n\n            leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength))\n        }\n\n        return leafHash;\n    }\n\n    /**\n     * Inserts a batch into the chain of batches.\n     * @param _transactionRoot Root of the transaction tree for this batch.\n     * @param _batchSize Number of elements in the batch.\n     * @param _numQueuedTransactions Number of queue transactions in the batch.\n     * @param _timestamp The latest batch timestamp.\n     * @param _blockNumber The latest batch blockNumber.\n     */\n    function _appendBatch(\n        bytes32 _transactionRoot,\n        uint256 _batchSize,\n        uint256 _numQueuedTransactions,\n        uint40 _timestamp,\n        uint40 _blockNumber\n    )\n        internal\n    {\n        iOVM_ChainStorageContainer batchesRef = batches();\n        (uint40 totalElements, uint40 nextQueueIndex,,) = _getBatchExtraData();\n\n        Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({\n            batchIndex: batchesRef.length(),\n            batchRoot: _transactionRoot,\n            batchSize: _batchSize,\n            prevTotalElements: totalElements,\n            extraData: hex\"\"\n        });\n\n        emit TransactionBatchAppended(\n            header.batchIndex,\n            header.batchRoot,\n            header.batchSize,\n            header.prevTotalElements,\n            header.extraData\n        );\n\n        bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);\n        bytes27 latestBatchContext = _makeBatchExtraData(\n            totalElements + uint40(header.batchSize),\n            nextQueueIndex + uint40(_numQueuedTransactions),\n            _timestamp,\n            _blockNumber\n        );\n\n        batchesRef.push(batchHeaderHash, latestBatchContext);\n    }\n\n    /**\n     * Checks that the first batch context in a sequencer submission is valid\n     * @param _firstContext The batch context to validate.\n     */\n    function _validateFirstBatchContext(\n        BatchContext memory _firstContext\n    )\n        internal\n        view\n    {\n        // If there are existing elements, this batch must have the same context\n        // or a later timestamp and block number.\n        if (getTotalElements() > 0) {\n            (,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData();\n\n            require(\n                _firstContext.blockNumber >= lastBlockNumber,\n                \"Context block number is lower than last submitted.\"\n            );\n\n            require(\n                _firstContext.timestamp >= lastTimestamp,\n                \"Context timestamp is lower than last submitted.\"\n            );\n        }\n\n        // Sequencer cannot submit contexts which are more than the force inclusion period old.\n        require(\n            _firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp,\n            \"Context timestamp too far in the past.\"\n        );\n\n        require(\n            _firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number,\n            \"Context block number too far in the past.\"\n        );\n    }\n\n    /**\n     * Checks that a given batch context has a time context which is below a given que element\n     * @param _context The batch context to validate has values lower.\n     * @param _queueIndex Index of the queue element we are validating came later than the context.\n     * @param _queueRef The storage container for the queue.\n     */\n    function _validateContextBeforeEnqueue(\n        BatchContext memory _context,\n        uint40 _queueIndex,\n        iOVM_ChainStorageContainer _queueRef\n    )\n        internal\n        view\n    {\n            Lib_OVMCodec.QueueElement memory nextQueueElement = _getQueueElement(\n                _queueIndex,\n                _queueRef\n            );\n\n            // If the force inclusion period has passed for an enqueued transaction, it MUST be the next chain element.\n            require(\n                block.timestamp < nextQueueElement.timestamp + forceInclusionPeriodSeconds,\n                \"Previously enqueued batches have expired and must be appended before a new sequencer batch.\"\n            );\n\n            // Just like sequencer transaction times must be increasing relative to each other,\n            // We also require that they be increasing relative to any interspersed queue elements.\n            require(\n                _context.timestamp <= nextQueueElement.timestamp,\n                \"Sequencer transaction timestamp exceeds that of next queue element.\"\n            );\n\n            require(\n                _context.blockNumber <= nextQueueElement.blockNumber,\n                \"Sequencer transaction blockNumber exceeds that of next queue element.\"\n            );\n    }\n\n    /**\n     * Checks that a given batch context is valid based on its previous context, and the next queue elemtent.\n     * @param _prevContext The previously validated batch context.\n     * @param _nextContext The batch context to validate with this call.\n     * @param _nextQueueIndex Index of the next queue element to process for the _nextContext's subsequentQueueElements.\n     * @param _queueRef The storage container for the queue.\n     */\n    function _validateNextBatchContext(\n        BatchContext memory _prevContext,\n        BatchContext memory _nextContext,\n        uint40 _nextQueueIndex,\n        iOVM_ChainStorageContainer _queueRef\n    )\n        internal\n        view\n    {\n        // All sequencer transactions' times must be greater than or equal to the previous ones.\n        require(\n            _nextContext.timestamp >= _prevContext.timestamp,\n            \"Context timestamp values must monotonically increase.\"\n        );\n\n        require(\n            _nextContext.blockNumber >= _prevContext.blockNumber,\n            \"Context blockNumber values must monotonically increase.\"\n        );\n\n        // If there is going to be a queue element pulled in from this context:\n        if (_nextContext.numSubsequentQueueTransactions > 0) {\n            _validateContextBeforeEnqueue(\n                _nextContext,\n                _nextQueueIndex,\n                _queueRef\n            );\n        }\n    }\n\n    /**\n     * Checks that the final batch context in a sequencer submission is valid.\n     * @param _finalContext The batch context to validate.\n     * @param _queueLength The length of the queue at the start of the batchAppend call.\n     * @param _nextQueueIndex The next element in the queue that will be pulled into the CTC.\n     * @param _queueRef The storage container for the queue.\n     */\n    function _validateFinalBatchContext(\n        BatchContext memory _finalContext,\n        uint40 _nextQueueIndex,\n        uint40 _queueLength,\n        iOVM_ChainStorageContainer _queueRef\n    )\n        internal\n        view\n    {\n        // If the queue is not now empty, check the mononoticity of whatever the next batch that will come in is.\n        if (_queueLength - _nextQueueIndex > 0 && _finalContext.numSubsequentQueueTransactions == 0) {\n            _validateContextBeforeEnqueue(\n                _finalContext,\n                _nextQueueIndex,\n                _queueRef\n            );\n        }\n        // Batches cannot be added from the future, or subsequent enqueue() contexts would violate monotonicity.\n        require(_finalContext.timestamp <= block.timestamp, \"Context timestamp is from the future.\");\n        require(_finalContext.blockNumber <= block.number, \"Context block number is from the future.\");\n    }\n\n    /**\n     * Hashes a transaction chain element.\n     * @param _element Chain element to hash.\n     * @return Hash of the chain element.\n     */\n    function _hashTransactionChainElement(\n        Lib_OVMCodec.TransactionChainElement memory _element\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return keccak256(\n            abi.encode(\n                _element.isSequenced,\n                _element.queueIndex,\n                _element.timestamp,\n                _element.blockNumber,\n                _element.txData\n            )\n        );\n    }\n\n    /**\n     * Verifies a sequencer transaction, returning true if it was indeed included in the CTC\n     * @param _transaction The transaction we are verifying inclusion of.\n     * @param _txChainElement The chain element that the transaction is claimed to be a part of.\n     * @param _batchHeader Header of the batch the transaction was included in.\n     * @param _inclusionProof An inclusion proof into the CTC at a particular index.\n     * @return True if the transaction was included in the specified location, else false.\n     */\n    function _verifySequencerTransaction(\n        Lib_OVMCodec.Transaction memory _transaction,\n        Lib_OVMCodec.TransactionChainElement memory _txChainElement,\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _inclusionProof\n    )\n        internal\n        view\n        returns (\n            bool\n        )\n    {\n        OVM_ExecutionManager ovmExecutionManager = OVM_ExecutionManager(resolve(\"OVM_ExecutionManager\"));\n        uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit();\n        bytes32 leafHash = _getSequencerLeafHash(_txChainElement);\n\n        require(\n            _verifyElement(\n                leafHash,\n                _batchHeader,\n                _inclusionProof\n            ),\n            \"Invalid Sequencer transaction inclusion proof.\"\n        );\n\n        require(\n            _transaction.blockNumber        == _txChainElement.blockNumber\n            && _transaction.timestamp       == _txChainElement.timestamp\n            && _transaction.entrypoint      == resolve(\"OVM_DecompressionPrecompileAddress\")\n            && _transaction.gasLimit        == gasLimit\n            && _transaction.l1TxOrigin      == address(0)\n            && _transaction.l1QueueOrigin   == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE\n            && keccak256(_transaction.data) == keccak256(_txChainElement.txData),\n            \"Invalid Sequencer transaction.\"\n        );\n\n        return true;\n    }\n\n    /**\n     * Verifies a queue transaction, returning true if it was indeed included in the CTC\n     * @param _transaction The transaction we are verifying inclusion of.\n     * @param _queueIndex The queueIndex of the queued transaction.\n     * @param _batchHeader Header of the batch the transaction was included in.\n     * @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to queue tx).\n     * @return True if the transaction was included in the specified location, else false.\n     */\n    function _verifyQueueTransaction(\n        Lib_OVMCodec.Transaction memory _transaction,\n        uint256 _queueIndex,\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _inclusionProof\n    )\n        internal\n        view\n        returns (\n            bool\n        )\n    {\n        bytes32 leafHash = _getQueueLeafHash(_queueIndex);\n\n        require(\n            _verifyElement(\n                leafHash,\n                _batchHeader,\n                _inclusionProof\n            ),\n            \"Invalid Queue transaction inclusion proof.\"\n        );\n\n        bytes32 transactionHash = keccak256(\n            abi.encode(\n                _transaction.l1TxOrigin,\n                _transaction.entrypoint,\n                _transaction.gasLimit,\n                _transaction.data\n            )\n        );\n\n        Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex);\n        require(\n            el.transactionHash      == transactionHash\n            && el.timestamp   == _transaction.timestamp\n            && el.blockNumber == _transaction.blockNumber,\n            \"Invalid Queue transaction.\"\n        );\n\n        return true;\n    }\n\n    /**\n     * Verifies a batch inclusion proof.\n     * @param _element Hash of the element to verify a proof for.\n     * @param _batchHeader Header of the batch in which the element was included.\n     * @param _proof Merkle inclusion proof for the element.\n     */\n    function _verifyElement(\n        bytes32 _element,\n        Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n        Lib_OVMCodec.ChainInclusionProof memory _proof\n    )\n        internal\n        view\n        returns (\n            bool\n        )\n    {\n        require(\n            Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(uint32(_batchHeader.batchIndex)),\n            \"Invalid batch header.\"\n        );\n\n        require(\n            Lib_MerkleTree.verify(\n                _batchHeader.batchRoot,\n                _element,\n                _proof.index,\n                _proof.siblings,\n                _batchHeader.batchSize\n            ),\n            \"Invalid inclusion proof.\"\n        );\n\n        return true;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/execution/OVM_ExecutionManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\nimport { Lib_Bytes32Utils } from \"../../libraries/utils/Lib_Bytes32Utils.sol\";\nimport { Lib_EthUtils } from \"../../libraries/utils/Lib_EthUtils.sol\";\nimport { Lib_ErrorUtils } from \"../../libraries/utils/Lib_ErrorUtils.sol\";\nimport { Lib_PredeployAddresses } from \"../../libraries/constants/Lib_PredeployAddresses.sol\";\n\n/* Interface Imports */\nimport { iOVM_ExecutionManager } from \"../../iOVM/execution/iOVM_ExecutionManager.sol\";\nimport { iOVM_StateManager } from \"../../iOVM/execution/iOVM_StateManager.sol\";\nimport { iOVM_SafetyChecker } from \"../../iOVM/execution/iOVM_SafetyChecker.sol\";\n\n/* Contract Imports */\nimport { OVM_DeployerWhitelist } from \"../predeploys/OVM_DeployerWhitelist.sol\";\n\n/* External Imports */\nimport { Math } from \"@openzeppelin/contracts/math/Math.sol\";\n\n/**\n * @title OVM_ExecutionManager\n * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed\n * environment allowing us to execute OVM transactions deterministically on either Layer 1 or\n * Layer 2.\n * The EM's run() function is the first function called during the execution of any\n * transaction on L2.\n * For each context-dependent EVM operation the EM has a function which implements a corresponding\n * OVM operation, which will read state from the State Manager contract.\n * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any\n * context-dependent operations.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver {\n\n    /********************************\n     * External Contract References *\n     ********************************/\n\n    iOVM_SafetyChecker internal ovmSafetyChecker;\n    iOVM_StateManager internal ovmStateManager;\n\n\n    /*******************************\n     * Execution Context Variables *\n     *******************************/\n\n    GasMeterConfig internal gasMeterConfig;\n    GlobalContext internal globalContext;\n    TransactionContext internal transactionContext;\n    MessageContext internal messageContext;\n    TransactionRecord internal transactionRecord;\n    MessageRecord internal messageRecord;\n\n\n    /**************************\n     * Gas Metering Constants *\n     **************************/\n\n    address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5;\n    uint256 constant NUISANCE_GAS_SLOAD = 20000;\n    uint256 constant NUISANCE_GAS_SSTORE = 20000;\n    uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000;\n    uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100;\n    uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000;\n\n\n    /**************************\n     * Native Value Constants *\n     **************************/\n\n    // Public so we can access and make assertions in integration tests.\n    uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000;\n\n\n    /**************************\n     * Default Context Values *\n     **************************/\n\n    uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d;\n    address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0;\n\n\n    /*************************************\n     * Container Contract Address Prefix *\n     *************************************/\n\n    /**\n     * @dev The Execution Manager and State Manager each have this 30 byte prefix, and are uncallable.\n     */\n    address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     */\n    constructor(\n        address _libAddressManager,\n        GasMeterConfig memory _gasMeterConfig,\n        GlobalContext memory _globalContext\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {\n        ovmSafetyChecker = iOVM_SafetyChecker(resolve(\"OVM_SafetyChecker\"));\n        gasMeterConfig = _gasMeterConfig;\n        globalContext = _globalContext;\n        _resetContext();\n    }\n\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    /**\n     * Applies dynamically-sized refund to a transaction to account for the difference in execution\n     * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed.\n     * @param _cost Desired gas cost for the function after the refund.\n     */\n    modifier netGasCost(\n        uint256 _cost\n    ) {\n        uint256 gasProvided = gasleft();\n        _;\n        uint256 gasUsed = gasProvided - gasleft();\n\n        // We want to refund everything *except* the specified cost.\n        if (_cost < gasUsed) {\n            transactionRecord.ovmGasRefund += gasUsed - _cost;\n        }\n    }\n\n    /**\n     * Applies a fixed-size gas refund to a transaction to account for the difference in execution\n     * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered.\n     * @param _discount Amount of gas cost to refund for the ovmOPCODE.\n     */\n    modifier fixedGasDiscount(\n        uint256 _discount\n    ) {\n        uint256 gasProvided = gasleft();\n        _;\n        uint256 gasUsed = gasProvided - gasleft();\n\n        // We want to refund the specified _discount, unless this risks underflow.\n        if (_discount < gasUsed) {\n            transactionRecord.ovmGasRefund += _discount;\n        } else {\n            // refund all we can without risking underflow.\n            transactionRecord.ovmGasRefund += gasUsed;\n        }\n    }\n\n    /**\n     * Makes sure we're not inside a static context.\n     */\n    modifier notStatic() {\n        if (messageContext.isStatic == true) {\n            _revertWithFlag(RevertFlag.STATIC_VIOLATION);\n        }\n        _;\n    }\n\n\n    /************************************\n     * Transaction Execution Entrypoint *\n     ************************************/\n\n    /**\n     * Starts the execution of a transaction via the OVM_ExecutionManager.\n     * @param _transaction Transaction data to be executed.\n     * @param _ovmStateManager iOVM_StateManager implementation providing account state.\n     */\n    function run(\n        Lib_OVMCodec.Transaction memory _transaction,\n        address _ovmStateManager\n    )\n        override\n        external\n        returns (\n            bytes memory\n        )\n    {\n        // Make sure that run() is not re-enterable.  This condition should always be satisfied\n        // Once run has been called once, due to the behavior of _isValidInput().\n        if (transactionContext.ovmNUMBER != DEFAULT_UINT256) {\n            return bytes(\"\");\n        }\n\n        // Store our OVM_StateManager instance (significantly easier than attempting to pass the\n        // address around in calldata).\n        ovmStateManager = iOVM_StateManager(_ovmStateManager);\n\n        // Make sure this function can't be called by anyone except the owner of the\n        // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because\n        // this would make the `run` itself invalid.\n        require(\n            // This method may return false during fraud proofs, but always returns true in L2 nodes' State Manager precompile.\n            ovmStateManager.isAuthenticated(msg.sender),\n            \"Only authenticated addresses in ovmStateManager can call this function\"\n        );\n\n        // Initialize the execution context, must be initialized before we perform any gas metering\n        // or we'll throw a nuisance gas error.\n        _initContext(_transaction);\n\n        // TEMPORARY: Gas metering is disabled for minnet.\n        // // Check whether we need to start a new epoch, do so if necessary.\n        // _checkNeedsNewEpoch(_transaction.timestamp);\n\n        // Make sure the transaction's gas limit is valid. We don't revert here because we reserve\n        // reverts for INVALID_STATE_ACCESS.\n        if (_isValidInput(_transaction) == false) {\n            _resetContext();\n            return bytes(\"\");\n        }\n\n        // TEMPORARY: Gas metering is disabled for minnet.\n        // // Check gas right before the call to get total gas consumed by OVM transaction.\n        // uint256 gasProvided = gasleft();\n\n        // Run the transaction, make sure to meter the gas usage.\n        (, bytes memory returndata) = ovmCALL(\n            _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit,\n            _transaction.entrypoint,\n            0,\n            _transaction.data\n        );\n\n        // TEMPORARY: Gas metering is disabled for minnet.\n        // // Update the cumulative gas based on the amount of gas used.\n        // uint256 gasUsed = gasProvided - gasleft();\n        // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin);\n\n        // Wipe the execution context.\n        _resetContext();\n\n        return returndata;\n    }\n\n\n    /******************************\n     * Opcodes: Execution Context *\n     ******************************/\n\n    /**\n     * @notice Overrides CALLER.\n     * @return _CALLER Address of the CALLER within the current message context.\n     */\n    function ovmCALLER()\n        override\n        external\n        view\n        returns (\n            address _CALLER\n        )\n    {\n        return messageContext.ovmCALLER;\n    }\n\n    /**\n     * @notice Overrides ADDRESS.\n     * @return _ADDRESS Active ADDRESS within the current message context.\n     */\n    function ovmADDRESS()\n        override\n        public\n        view\n        returns (\n            address _ADDRESS\n        )\n    {\n        return messageContext.ovmADDRESS;\n    }\n\n    /**\n     * @notice Overrides CALLVALUE.\n     * @return _CALLVALUE Value sent along with the call according to the current message context.\n     */\n    function ovmCALLVALUE()\n        override\n        public\n        view\n        returns (\n            uint256 _CALLVALUE\n        )\n    {\n        return messageContext.ovmCALLVALUE;\n    }\n\n    /**\n     * @notice Overrides TIMESTAMP.\n     * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context.\n     */\n    function ovmTIMESTAMP()\n        override\n        external\n        view\n        returns (\n            uint256 _TIMESTAMP\n        )\n    {\n        return transactionContext.ovmTIMESTAMP;\n    }\n\n    /**\n     * @notice Overrides NUMBER.\n     * @return _NUMBER Value of the NUMBER within the transaction context.\n     */\n    function ovmNUMBER()\n        override\n        external\n        view\n        returns (\n            uint256 _NUMBER\n        )\n    {\n        return transactionContext.ovmNUMBER;\n    }\n\n    /**\n     * @notice Overrides GASLIMIT.\n     * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context.\n     */\n    function ovmGASLIMIT()\n        override\n        external\n        view\n        returns (\n            uint256 _GASLIMIT\n        )\n    {\n        return transactionContext.ovmGASLIMIT;\n    }\n\n    /**\n     * @notice Overrides CHAINID.\n     * @return _CHAINID Value of the chain's CHAINID within the global context.\n     */\n    function ovmCHAINID()\n        override\n        external\n        view\n        returns (\n            uint256 _CHAINID\n        )\n    {\n        return globalContext.ovmCHAINID;\n    }\n\n    /*********************************\n     * Opcodes: L2 Execution Context *\n     *********************************/\n\n    /**\n     * @notice Specifies from which source (Sequencer or Queue) this transaction originated from.\n     * @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context.\n     */\n    function ovmL1QUEUEORIGIN()\n        override\n        external\n        view\n        returns (\n            Lib_OVMCodec.QueueOrigin _queueOrigin\n        )\n    {\n        return transactionContext.ovmL1QUEUEORIGIN;\n    }\n\n    /**\n     * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue().\n     * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1.\n     */\n    function ovmL1TXORIGIN()\n        override\n        external\n        view\n        returns (\n            address _l1TxOrigin\n        )\n    {\n        return transactionContext.ovmL1TXORIGIN;\n    }\n\n    /********************\n     * Opcodes: Halting *\n     ********************/\n\n    /**\n     * @notice Overrides REVERT.\n     * @param _data Bytes data to pass along with the REVERT.\n     */\n    function ovmREVERT(\n        bytes memory _data\n    )\n        override\n        public\n    {\n        _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data);\n    }\n\n\n    /******************************\n     * Opcodes: Contract Creation *\n     ******************************/\n\n    /**\n     * @notice Overrides CREATE.\n     * @param _bytecode Code to be used to CREATE a new contract.\n     * @return Address of the created contract.\n     * @return Revert data, if and only if the creation threw an exception.\n     */\n    function ovmCREATE(\n        bytes memory _bytecode\n    )\n        override\n        public\n        notStatic\n        fixedGasDiscount(40000)\n        returns (\n            address,\n            bytes memory\n        )\n    {\n        // Creator is always the current ADDRESS.\n        address creator = ovmADDRESS();\n\n        // Check that the deployer is whitelisted, or\n        // that arbitrary contract deployment has been enabled.\n        _checkDeployerAllowed(creator);\n\n        // Generate the correct CREATE address.\n        address contractAddress = Lib_EthUtils.getAddressForCREATE(\n            creator,\n            _getAccountNonce(creator)\n        );\n\n        return _createContract(\n            contractAddress,\n            _bytecode,\n            MessageType.ovmCREATE\n        );\n    }\n\n    /**\n     * @notice Overrides CREATE2.\n     * @param _bytecode Code to be used to CREATE2 a new contract.\n     * @param _salt Value used to determine the contract's address.\n     * @return Address of the created contract.\n     * @return Revert data, if and only if the creation threw an exception.\n     */\n    function ovmCREATE2(\n        bytes memory _bytecode,\n        bytes32 _salt\n    )\n        override\n        external\n        notStatic\n        fixedGasDiscount(40000)\n        returns (\n            address,\n            bytes memory\n        )\n    {\n        // Creator is always the current ADDRESS.\n        address creator = ovmADDRESS();\n\n        // Check that the deployer is whitelisted, or\n        // that arbitrary contract deployment has been enabled.\n        _checkDeployerAllowed(creator);\n\n        // Generate the correct CREATE2 address.\n        address contractAddress = Lib_EthUtils.getAddressForCREATE2(\n            creator,\n            _bytecode,\n            _salt\n        );\n\n        return _createContract(\n            contractAddress,\n            _bytecode,\n            MessageType.ovmCREATE2\n        );\n    }\n\n\n    /*******************************\n     * Account Abstraction Opcodes *\n     ******************************/\n\n    /**\n     * Retrieves the nonce of the current ovmADDRESS.\n     * @return _nonce Nonce of the current contract.\n     */\n    function ovmGETNONCE()\n        override\n        external\n        returns (\n            uint256 _nonce\n        )\n    {\n        return _getAccountNonce(ovmADDRESS());\n    }\n\n    /**\n     * Bumps the nonce of the current ovmADDRESS by one.\n     */\n    function ovmINCREMENTNONCE()\n        override\n        external\n        notStatic\n    {\n        address account = ovmADDRESS();\n        uint256 nonce = _getAccountNonce(account);\n\n        // Prevent overflow.\n        if (nonce + 1 > nonce) {\n            _setAccountNonce(account, nonce + 1);\n        }\n    }\n\n    /**\n     * Creates a new EOA contract account, for account abstraction.\n     * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks\n     *      because the contract we're creating is trusted (no need to do safety checking or to\n     *      handle unexpected reverts). Doesn't need to return an address because the address is\n     *      assumed to be the user's actual address.\n     * @param _messageHash Hash of a message signed by some user, for verification.\n     * @param _v Signature `v` parameter.\n     * @param _r Signature `r` parameter.\n     * @param _s Signature `s` parameter.\n     */\n    function ovmCREATEEOA(\n        bytes32 _messageHash,\n        uint8 _v,\n        bytes32 _r,\n        bytes32 _s\n    )\n        override\n        public\n        notStatic\n    {\n        // Recover the EOA address from the message hash and signature parameters. Since we do the\n        // hashing in advance, we don't have handle different message hashing schemes. Even if this\n        // function were to return the wrong address (rather than explicitly returning the zero\n        // address), the rest of the transaction would simply fail (since there's no EOA account to\n        // actually execute the transaction).\n        address eoa = ecrecover(\n            _messageHash,\n            _v + 27,\n            _r,\n            _s\n        );\n\n        // Invalid signature is a case we proactively handle with a revert. We could alternatively\n        // have this function return a `success` boolean, but this is just easier.\n        if (eoa == address(0)) {\n            ovmREVERT(bytes(\"Signature provided for EOA contract creation is invalid.\"));\n        }\n\n        // If the user already has an EOA account, then there's no need to perform this operation.\n        if (_hasEmptyAccount(eoa) == false) {\n            return;\n        }\n\n        // We always need to initialize the contract with the default account values.\n        _initPendingAccount(eoa);\n\n        // Temporarily set the current address so it's easier to access on L2.\n        address prevADDRESS = messageContext.ovmADDRESS;\n        messageContext.ovmADDRESS = eoa;\n\n        // Creates a duplicate of the OVM_ProxyEOA located at 0x42....09. Uses the following\n        // \"magic\" prefix to deploy an exact copy of the code:\n        // PUSH1 0x0D   # size of this prefix in bytes\n        // CODESIZE\n        // SUB          # subtract prefix size from codesize\n        // DUP1\n        // PUSH1 0x0D\n        // PUSH1 0x00\n        // CODECOPY     # copy everything after prefix into memory at pos 0\n        // PUSH1 0x00\n        // RETURN       # return the copied code\n        address proxyEOA = Lib_EthUtils.createContract(abi.encodePacked(\n            hex\"600D380380600D6000396000f3\",\n            ovmEXTCODECOPY(\n                Lib_PredeployAddresses.PROXY_EOA,\n                0,\n                ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA)\n            )\n        ));\n\n        // Reset the address now that we're done deploying.\n        messageContext.ovmADDRESS = prevADDRESS;\n\n        // Commit the account with its final values.\n        _commitPendingAccount(\n            eoa,\n            address(proxyEOA),\n            keccak256(Lib_EthUtils.getCode(address(proxyEOA)))\n        );\n\n        _setAccountNonce(eoa, 0);\n    }\n\n\n    /*********************************\n     * Opcodes: Contract Interaction *\n     *********************************/\n\n    /**\n     * @notice Overrides CALL.\n     * @param _gasLimit Amount of gas to be passed into this call.\n     * @param _address Address of the contract to call.\n     * @param _value ETH value to pass with the call.\n     * @param _calldata Data to send along with the call.\n     * @return _success Whether or not the call returned (rather than reverted).\n     * @return _returndata Data returned by the call.\n     */\n    function ovmCALL(\n        uint256 _gasLimit,\n        address _address,\n        uint256 _value,\n        bytes memory _calldata\n    )\n        override\n        public\n        fixedGasDiscount(100000)\n        returns (\n            bool _success,\n            bytes memory _returndata\n        )\n    {\n        // CALL updates the CALLER and ADDRESS.\n        MessageContext memory nextMessageContext = messageContext;\n        nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;\n        nextMessageContext.ovmADDRESS = _address;\n        nextMessageContext.ovmCALLVALUE = _value;\n\n        return _callContract(\n            nextMessageContext,\n            _gasLimit,\n            _address,\n            _calldata,\n            MessageType.ovmCALL\n        );\n    }\n\n    /**\n     * @notice Overrides STATICCALL.\n     * @param _gasLimit Amount of gas to be passed into this call.\n     * @param _address Address of the contract to call.\n     * @param _calldata Data to send along with the call.\n     * @return _success Whether or not the call returned (rather than reverted).\n     * @return _returndata Data returned by the call.\n     */\n    function ovmSTATICCALL(\n        uint256 _gasLimit,\n        address _address,\n        bytes memory _calldata\n    )\n        override\n        public\n        fixedGasDiscount(80000)\n        returns (\n            bool _success,\n            bytes memory _returndata\n        )\n    {\n        // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static, valueless context.\n        MessageContext memory nextMessageContext = messageContext;\n        nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;\n        nextMessageContext.ovmADDRESS = _address;\n        nextMessageContext.isStatic = true;\n        nextMessageContext.ovmCALLVALUE = 0;\n\n        return _callContract(\n            nextMessageContext,\n            _gasLimit,\n            _address,\n            _calldata,\n            MessageType.ovmSTATICCALL\n        );\n    }\n\n    /**\n     * @notice Overrides DELEGATECALL.\n     * @param _gasLimit Amount of gas to be passed into this call.\n     * @param _address Address of the contract to call.\n     * @param _calldata Data to send along with the call.\n     * @return _success Whether or not the call returned (rather than reverted).\n     * @return _returndata Data returned by the call.\n     */\n    function ovmDELEGATECALL(\n        uint256 _gasLimit,\n        address _address,\n        bytes memory _calldata\n    )\n        override\n        public\n        fixedGasDiscount(40000)\n        returns (\n            bool _success,\n            bytes memory _returndata\n        )\n    {\n        // DELEGATECALL does not change anything about the message context.\n        MessageContext memory nextMessageContext = messageContext;\n\n        return _callContract(\n            nextMessageContext,\n            _gasLimit,\n            _address,\n            _calldata,\n            MessageType.ovmDELEGATECALL\n        );\n    }\n\n    /**\n     * @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards compatibility.\n     * @param _gasLimit Amount of gas to be passed into this call.\n     * @param _address Address of the contract to call.\n     * @param _calldata Data to send along with the call.\n     * @return _success Whether or not the call returned (rather than reverted).\n     * @return _returndata Data returned by the call.\n     */\n    function ovmCALL(\n        uint256 _gasLimit,\n        address _address,\n        bytes memory _calldata\n    )\n        override\n        public\n        returns(\n            bool _success,\n            bytes memory _returndata\n        )\n    {\n        // Legacy ovmCALL assumed always-0 value.\n        return ovmCALL(\n            _gasLimit,\n            _address,\n            0,\n            _calldata\n        );\n    }\n\n\n    /************************************\n     * Opcodes: Contract Storage Access *\n     ************************************/\n\n    /**\n     * @notice Overrides SLOAD.\n     * @param _key 32 byte key of the storage slot to load.\n     * @return _value 32 byte value of the requested storage slot.\n     */\n    function ovmSLOAD(\n        bytes32 _key\n    )\n        override\n        external\n        netGasCost(40000)\n        returns (\n            bytes32 _value\n        )\n    {\n        // We always SLOAD from the storage of ADDRESS.\n        address contractAddress = ovmADDRESS();\n\n        return _getContractStorage(\n            contractAddress,\n            _key\n        );\n    }\n\n    /**\n     * @notice Overrides SSTORE.\n     * @param _key 32 byte key of the storage slot to set.\n     * @param _value 32 byte value for the storage slot.\n     */\n    function ovmSSTORE(\n        bytes32 _key,\n        bytes32 _value\n    )\n        override\n        external\n        notStatic\n        netGasCost(60000)\n    {\n        // We always SSTORE to the storage of ADDRESS.\n        address contractAddress = ovmADDRESS();\n\n        _putContractStorage(\n            contractAddress,\n            _key,\n            _value\n        );\n    }\n\n\n    /*********************************\n     * Opcodes: Contract Code Access *\n     *********************************/\n\n    /**\n     * @notice Overrides EXTCODECOPY.\n     * @param _contract Address of the contract to copy code from.\n     * @param _offset Offset in bytes from the start of contract code to copy beyond.\n     * @param _length Total number of bytes to copy from the contract's code.\n     * @return _code Bytes of code copied from the requested contract.\n     */\n    function ovmEXTCODECOPY(\n        address _contract,\n        uint256 _offset,\n        uint256 _length\n    )\n        override\n        public\n        returns (\n            bytes memory _code\n        )\n    {\n        return Lib_EthUtils.getCode(\n            _getAccountEthAddress(_contract),\n            _offset,\n            _length\n        );\n    }\n\n    /**\n     * @notice Overrides EXTCODESIZE.\n     * @param _contract Address of the contract to query the size of.\n     * @return _EXTCODESIZE Size of the requested contract in bytes.\n     */\n    function ovmEXTCODESIZE(\n        address _contract\n    )\n        override\n        public\n        returns (\n            uint256 _EXTCODESIZE\n        )\n    {\n        return Lib_EthUtils.getCodeSize(\n            _getAccountEthAddress(_contract)\n        );\n    }\n\n    /**\n     * @notice Overrides EXTCODEHASH.\n     * @param _contract Address of the contract to query the hash of.\n     * @return _EXTCODEHASH Hash of the requested contract.\n     */\n    function ovmEXTCODEHASH(\n        address _contract\n    )\n        override\n        external\n        returns (\n            bytes32 _EXTCODEHASH\n        )\n    {\n        return Lib_EthUtils.getCodeHash(\n            _getAccountEthAddress(_contract)\n        );\n    }\n\n\n    /***************************************\n     * Public Functions: ETH Value Opcodes *\n     ***************************************/\n\n    /**\n     * @notice Overrides BALANCE.\n     * NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...).\n     * @param _contract Address of the contract to query the OVM_ETH balance of.\n     * @return _BALANCE OVM_ETH balance of the requested contract.\n     */\n    function ovmBALANCE(\n        address _contract\n    )\n        override\n        public\n        returns (\n            uint256 _BALANCE\n        )\n    {\n        // Easiest way to get the balance is query OVM_ETH as normal.\n        bytes memory balanceOfCalldata = abi.encodeWithSignature(\n            \"balanceOf(address)\",\n            _contract\n        );\n\n        // Static call because this should be a read-only query.\n        (bool success, bytes memory returndata) = ovmSTATICCALL(\n            gasleft(),\n            Lib_PredeployAddresses.OVM_ETH,\n            balanceOfCalldata\n        );\n\n        // All balanceOf queries should successfully return a uint, otherwise this must be an OOG.\n        if (!success || returndata.length != 32) {\n            _revertWithFlag(RevertFlag.OUT_OF_GAS);\n        }\n\n        // Return the decoded balance.\n        return abi.decode(returndata, (uint256));\n    }\n\n    /**\n     * @notice Overrides SELFBALANCE.\n     * @return _BALANCE OVM_ETH balance of the requesting contract.\n     */\n    function ovmSELFBALANCE()\n        override\n        external\n        returns (\n            uint256 _BALANCE\n        )\n    {\n        return ovmBALANCE(ovmADDRESS());\n    }\n\n\n    /***************************************\n     * Public Functions: Execution Context *\n     ***************************************/\n\n    function getMaxTransactionGasLimit()\n        external\n        view\n        override\n        returns (\n            uint256 _maxTransactionGasLimit\n        )\n    {\n        return gasMeterConfig.maxTransactionGasLimit;\n    }\n\n    /********************************************\n     * Public Functions: Deployment Whitelisting *\n     ********************************************/\n\n    /**\n     * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, and reverts if not.\n     * @param _deployerAddress Address attempting to deploy a contract.\n     */\n    function _checkDeployerAllowed(\n        address _deployerAddress\n    )\n        internal\n    {\n        // From an OVM semantics perspective, this will appear identical to\n        // the deployer ovmCALLing the whitelist.  This is fine--in a sense, we are forcing them to.\n        (bool success, bytes memory data) = ovmSTATICCALL(\n            gasleft(),\n            Lib_PredeployAddresses.DEPLOYER_WHITELIST,\n            abi.encodeWithSelector(\n                OVM_DeployerWhitelist.isDeployerAllowed.selector,\n                _deployerAddress\n            )\n        );\n        bool isAllowed = abi.decode(data, (bool));\n\n        if (!isAllowed || !success) {\n            _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED);\n        }\n    }\n\n    /********************************************\n     * Internal Functions: Contract Interaction *\n     ********************************************/\n\n    /**\n     * Creates a new contract and associates it with some contract address.\n     * @param _contractAddress Address to associate the created contract with.\n     * @param _bytecode Bytecode to be used to create the contract.\n     * @return Final OVM contract address.\n     * @return Revertdata, if and only if the creation threw an exception.\n     */\n    function _createContract(\n        address _contractAddress,\n        bytes memory _bytecode,\n        MessageType _messageType\n    )\n        internal\n        returns (\n            address,\n            bytes memory\n        )\n    {\n        // We always update the nonce of the creating account, even if the creation fails.\n        _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1);\n\n        // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point\n        // to the contract's associated address and CALLER to point to the previous ADDRESS.\n        MessageContext memory nextMessageContext = messageContext;\n        nextMessageContext.ovmCALLER = messageContext.ovmADDRESS;\n        nextMessageContext.ovmADDRESS = _contractAddress;\n\n        // Run the common logic which occurs between call-type and create-type messages,\n        // passing in the creation bytecode and `true` to trigger create-specific logic.\n        (bool success, bytes memory data) = _handleExternalMessage(\n            nextMessageContext,\n            gasleft(),\n            _contractAddress,\n            _bytecode,\n            _messageType\n        );\n\n        // Yellow paper requires that address returned is zero if the contract deployment fails.\n        return (\n            success ? _contractAddress : address(0),\n            data\n        );\n    }\n\n    /**\n     * Calls the deployed contract associated with a given address.\n     * @param _nextMessageContext Message context to be used for the call.\n     * @param _gasLimit Amount of gas to be passed into this call.\n     * @param _contract OVM address to be called.\n     * @param _calldata Data to send along with the call.\n     * @return _success Whether or not the call returned (rather than reverted).\n     * @return _returndata Data returned by the call.\n     */\n    function _callContract(\n        MessageContext memory _nextMessageContext,\n        uint256 _gasLimit,\n        address _contract,\n        bytes memory _calldata,\n        MessageType _messageType\n    )\n        internal\n        returns (\n            bool _success,\n            bytes memory _returndata\n        )\n    {\n        // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 geth.\n        // So, we block calls to these addresses since they are not safe to run as an OVM contract itself.\n        if (\n            (uint256(_contract) & uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000))\n            == uint256(CONTAINER_CONTRACT_PREFIX)\n        ) {\n            // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604\n            return (true, hex'');\n        }\n\n        // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> no trie lookup needed.\n        address codeContractAddress =\n            uint(_contract) < 100\n            ? _contract\n            : _getAccountEthAddress(_contract);\n\n        return _handleExternalMessage(\n            _nextMessageContext,\n            _gasLimit,\n            codeContractAddress,\n            _calldata,\n            _messageType\n        );\n    }\n\n    /**\n     * Handles all interactions which involve the execution manager calling out to untrusted code (both calls and creates).\n     * Ensures that OVM-related measures are enforced, including L2 gas refunds, nuisance gas, and flagged reversions.\n     *\n     * @param _nextMessageContext Message context to be used for the external message.\n     * @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is overwritten in some cases to avoid stack-too-deep.\n     * @param _contract OVM address being called or deployed to\n     * @param _data Data for the message (either calldata or creation code)\n     * @param _messageType What type of ovmOPCODE this message corresponds to.\n     * @return Whether or not the message (either a call or deployment) succeeded.\n     * @return Data returned by the message.\n     */\n    function _handleExternalMessage(\n        MessageContext memory _nextMessageContext,\n        // NOTE: this argument is overwritten in some cases to avoid stack-too-deep.\n        uint256 _gasLimit,\n        address _contract,\n        bytes memory _data,\n        MessageType _messageType\n    )\n        internal\n        returns (\n            bool,\n            bytes memory\n        )\n    {\n        uint256 messageValue = _nextMessageContext.ovmCALLVALUE;\n        // If there is value in this message, we need to transfer the ETH over before switching contexts.\n        if (\n            messageValue > 0\n            && _isValueType(_messageType)\n        ) {\n            // Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall \"appears to revert\" if we don't have enough gas to transfer the ETH.\n            // Similar to dynamic gas cost of value exceeding gas here:\n            // https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273\n            if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) {\n                return (false, hex\"\");\n            }\n\n            // If there *is* enough gas to transfer ETH, then we need to make sure this amount of gas is reserved (i.e. not\n            // given to the _contract.call below) to guarantee that _handleExternalMessage can't run out of gas.\n            // In particular, in the event that the call fails, we will need to transfer the ETH back to the sender.\n            // Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS guarantees that the second\n            // _attemptForcedEthTransfer below, if needed, always has enough gas to succeed.\n            _gasLimit = Math.min(\n                _gasLimit,\n                gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check.\n            );\n\n            // Now transfer the value of the call.\n            // The target is interpreted to be the next message's ovmADDRESS account.\n            bool transferredOvmEth = _attemptForcedEthTransfer(\n                _nextMessageContext.ovmADDRESS,\n                messageValue\n            );\n\n            // If the ETH transfer fails (should only be possible in the case of insufficient balance), then treat this as a revert.\n            // This mirrors EVM behavior, see https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298\n            if (!transferredOvmEth) {\n                return (false, hex\"\");\n            }\n        }\n\n        // We need to switch over to our next message context for the duration of this call.\n        MessageContext memory prevMessageContext = messageContext;\n        _switchMessageContext(prevMessageContext, _nextMessageContext);\n\n        // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs\n        // expensive by touching a lot of different accounts or storage slots. Since most contracts\n        // only use a few storage slots during any given transaction, this shouldn't be a limiting\n        // factor.\n        uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft;\n        uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit);\n        messageRecord.nuisanceGasLeft = nuisanceGasLimit;\n\n        // Make the call and make sure to pass in the gas limit. Another instance of hidden\n        // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert\n        // behavior can be controlled. In particular, we enforce that flags are passed through\n        // revert data as to retrieve execution metadata that would normally be reverted out of\n        // existence.\n\n        bool success;\n        bytes memory returndata;\n        if (_isCreateType(_messageType)) {\n            // safeCREATE() is a function which replicates a CREATE message, but uses return values\n            // Which match that of CALL (i.e. bool, bytes).  This allows many security checks to be\n            // to be shared between untrusted call and create call frames.\n            (success, returndata) = address(this).call{gas: _gasLimit}(\n                abi.encodeWithSelector(\n                    this.safeCREATE.selector,\n                    _data,\n                    _contract\n                )\n            );\n        } else {\n            (success, returndata) = _contract.call{gas: _gasLimit}(_data);\n        }\n\n        // If the message threw an exception, its value should be returned back to the sender.\n        // So, we force it back, BEFORE returning the messageContext to the previous addresses.\n        // This operation is part of the reason we \"reserved the intrinsic gas\" above.\n        if (\n            messageValue > 0\n            && _isValueType(_messageType)\n            && !success\n        ) {\n            bool transferredOvmEth = _attemptForcedEthTransfer(\n                prevMessageContext.ovmADDRESS,\n                messageValue\n            );\n\n            // Since we transferred it in above and the call reverted, the transfer back should always pass.\n            // This code path should NEVER be triggered since we sent `messageValue` worth of OVM_ETH into the target\n            // and reserved sufficient gas to execute the transfer, but in case there is some edge case which has\n            // been missed, we revert the entire frame (and its parent) to make sure the ETH gets sent back.\n            if (!transferredOvmEth) {\n                _revertWithFlag(RevertFlag.OUT_OF_GAS);\n            }\n        }\n\n        // Switch back to the original message context now that we're out of the call and all OVM_ETH is in the right place.\n        _switchMessageContext(_nextMessageContext, prevMessageContext);\n\n        // Assuming there were no reverts, the message record should be accurate here. We'll update\n        // this value in the case of a revert.\n        uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft;\n\n        // Reverts at this point are completely OK, but we need to make a few updates based on the\n        // information passed through the revert.\n        if (success == false) {\n            (\n                RevertFlag flag,\n                uint256 nuisanceGasLeftPostRevert,\n                uint256 ovmGasRefund,\n                bytes memory returndataFromFlag\n            ) = _decodeRevertData(returndata);\n\n            // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the\n            // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must\n            // halt any further transaction execution that could impact the execution result.\n            if (flag == RevertFlag.INVALID_STATE_ACCESS) {\n                _revertWithFlag(flag);\n            }\n\n            // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't\n            // dependent on the input state, so we can just handle them like standard reverts. Our only change here\n            // is to record the gas refund reported by the call (enforced by safety checking).\n            if (\n                flag == RevertFlag.INTENTIONAL_REVERT\n                || flag == RevertFlag.UNSAFE_BYTECODE\n                || flag == RevertFlag.STATIC_VIOLATION\n                || flag == RevertFlag.CREATOR_NOT_ALLOWED\n            ) {\n                transactionRecord.ovmGasRefund = ovmGasRefund;\n            }\n\n            // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the\n            // flag, *not* the full encoded flag.  Additionally, we surface custom error messages\n            // to developers in the case of unsafe creations for improved devex.\n            // All other revert types return no data.\n            if (\n                flag == RevertFlag.INTENTIONAL_REVERT\n                || flag == RevertFlag.UNSAFE_BYTECODE\n            ) {\n                returndata = returndataFromFlag;\n            } else {\n                returndata = hex'';\n            }\n\n            // Reverts mean we need to use up whatever \"nuisance gas\" was used by the call.\n            // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message\n            // to zero. OUT_OF_GAS is a \"pseudo\" flag given that messages return no data when they\n            // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags\n            // will simply pass up the remaining nuisance gas.\n            nuisanceGasLeft = nuisanceGasLeftPostRevert;\n        }\n\n        // We need to reset the nuisance gas back to its original value minus the amount used here.\n        messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft);\n\n        return (\n            success,\n            returndata\n        );\n    }\n\n    /**\n     * Handles the creation-specific safety measures required for OVM contract deployment.\n     * This function sanitizes the return types for creation messages to match calls (bool, bytes),\n     * by being an external function which the EM can call, that mimics the success/fail case of the CREATE.\n     * This allows for consistent handling of both types of messages in _handleExternalMessage().\n     * Having this step occur as a separate call frame also allows us to easily revert the\n     * contract deployment in the event that the code is unsafe.\n     *\n     * @param _creationCode Code to pass into CREATE for deployment.\n     * @param _address OVM address being deployed to.\n     */\n    function safeCREATE(\n        bytes memory _creationCode,\n        address _address\n    )\n        external\n    {\n        // The only way this should callable is from within _createContract(),\n        // and it should DEFINITELY not be callable by a non-EM code contract.\n        if (msg.sender != address(this)) {\n            return;\n        }\n        // Check that there is not already code at this address.\n        if (_hasEmptyAccount(_address) == false) {\n            // Note: in the EVM, this case burns all allotted gas.  For improved\n            // developer experience, we do return the remaining gas.\n            _revertWithFlag(\n                RevertFlag.CREATE_COLLISION\n            );\n        }\n\n        // Check the creation bytecode against the OVM_SafetyChecker.\n        if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) {\n            // Note: in the EVM, this case burns all allotted gas.  For improved\n            // developer experience, we do return the remaining gas.\n            _revertWithFlag(\n                RevertFlag.UNSAFE_BYTECODE,\n                Lib_ErrorUtils.encodeRevertString(\"Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?\")\n            );\n        }\n\n        // We always need to initialize the contract with the default account values.\n        _initPendingAccount(_address);\n\n        // Actually execute the EVM create message.\n        // NOTE: The inline assembly below means we can NOT make any evm calls between here and then.\n        address ethAddress = Lib_EthUtils.createContract(_creationCode);\n\n        if (ethAddress == address(0)) {\n            // If the creation fails, the EVM lets us grab its revert data. This may contain a revert flag\n            // to be used above in _handleExternalMessage, so we pass the revert data back up unmodified.\n            assembly {\n                returndatacopy(0,0,returndatasize())\n                revert(0, returndatasize())\n            }\n        }\n\n        // Again simply checking that the deployed code is safe too. Contracts can generate\n        // arbitrary deployment code, so there's no easy way to analyze this beforehand.\n        bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress);\n        if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) {\n            _revertWithFlag(\n                RevertFlag.UNSAFE_BYTECODE,\n                Lib_ErrorUtils.encodeRevertString(\"Constructor attempted to deploy unsafe bytecode.\")\n            );\n        }\n\n        // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by\n        // associating the desired address with the newly created contract's code hash and address.\n        _commitPendingAccount(\n            _address,\n            ethAddress,\n            Lib_EthUtils.getCodeHash(ethAddress)\n        );\n    }\n\n    /******************************************\n     * Internal Functions: Value Manipulation *\n     ******************************************/\n\n    /**\n     * Invokes an ovmCALL to OVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to force movement of OVM_ETH in correspondence with ETH's native value functionality.\n     * WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage at the time of the call.\n     * NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...).\n     * @param _to Amount of OVM_ETH to be sent.\n     * @param _value Amount of OVM_ETH to send.\n     * @return _success Whether or not the transfer worked.\n     */\n    function _attemptForcedEthTransfer(\n        address _to,\n        uint256 _value\n    )\n        internal\n        returns(\n            bool _success\n        )\n    {\n        bytes memory transferCalldata = abi.encodeWithSignature(\n            \"transfer(address,uint256)\",\n            _to,\n            _value\n        );\n\n        // OVM_ETH inherits from the UniswapV2ERC20 standard.  In this implementation, its return type\n        // is a boolean.  However, the implementation always returns true if it does not revert.\n        // Thus, success of the call frame is sufficient to infer success of the transfer itself.\n        (bool success, ) = ovmCALL(\n            gasleft(),\n            Lib_PredeployAddresses.OVM_ETH,\n            0,\n            transferCalldata\n        );\n\n        return success;\n    }\n\n    /******************************************\n     * Internal Functions: State Manipulation *\n     ******************************************/\n\n    /**\n     * Checks whether an account exists within the OVM_StateManager.\n     * @param _address Address of the account to check.\n     * @return _exists Whether or not the account exists.\n     */\n    function _hasAccount(\n        address _address\n    )\n        internal\n        returns (\n            bool _exists\n        )\n    {\n        _checkAccountLoad(_address);\n        return ovmStateManager.hasAccount(_address);\n    }\n\n    /**\n     * Checks whether a known empty account exists within the OVM_StateManager.\n     * @param _address Address of the account to check.\n     * @return _exists Whether or not the account empty exists.\n     */\n    function _hasEmptyAccount(\n        address _address\n    )\n        internal\n        returns (\n            bool _exists\n        )\n    {\n        _checkAccountLoad(_address);\n        return ovmStateManager.hasEmptyAccount(_address);\n    }\n\n    /**\n     * Sets the nonce of an account.\n     * @param _address Address of the account to modify.\n     * @param _nonce New account nonce.\n     */\n    function _setAccountNonce(\n        address _address,\n        uint256 _nonce\n    )\n        internal\n    {\n        _checkAccountChange(_address);\n        ovmStateManager.setAccountNonce(_address, _nonce);\n    }\n\n    /**\n     * Gets the nonce of an account.\n     * @param _address Address of the account to access.\n     * @return _nonce Nonce of the account.\n     */\n    function _getAccountNonce(\n        address _address\n    )\n        internal\n        returns (\n            uint256 _nonce\n        )\n    {\n        _checkAccountLoad(_address);\n        return ovmStateManager.getAccountNonce(_address);\n    }\n\n    /**\n     * Retrieves the Ethereum address of an account.\n     * @param _address Address of the account to access.\n     * @return _ethAddress Corresponding Ethereum address.\n     */\n    function _getAccountEthAddress(\n        address _address\n    )\n        internal\n        returns (\n            address _ethAddress\n        )\n    {\n        _checkAccountLoad(_address);\n        return ovmStateManager.getAccountEthAddress(_address);\n    }\n\n    /**\n     * Creates the default account object for the given address.\n     * @param _address Address of the account create.\n     */\n    function _initPendingAccount(\n        address _address\n    )\n        internal\n    {\n        // Although it seems like `_checkAccountChange` would be more appropriate here, we don't\n        // actually consider an account \"changed\" until it's inserted into the state (in this case\n        // by `_commitPendingAccount`).\n        _checkAccountLoad(_address);\n        ovmStateManager.initPendingAccount(_address);\n    }\n\n    /**\n     * Stores additional relevant data for a new account, thereby \"committing\" it to the state.\n     * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract\n     * creation.\n     * @param _address Address of the account to commit.\n     * @param _ethAddress Address of the associated deployed contract.\n     * @param _codeHash Hash of the code stored at the address.\n     */\n    function _commitPendingAccount(\n        address _address,\n        address _ethAddress,\n        bytes32 _codeHash\n    )\n        internal\n    {\n        _checkAccountChange(_address);\n        ovmStateManager.commitPendingAccount(\n            _address,\n            _ethAddress,\n            _codeHash\n        );\n    }\n\n    /**\n     * Retrieves the value of a storage slot.\n     * @param _contract Address of the contract to query.\n     * @param _key 32 byte key of the storage slot.\n     * @return _value 32 byte storage slot value.\n     */\n    function _getContractStorage(\n        address _contract,\n        bytes32 _key\n    )\n        internal\n        returns (\n            bytes32 _value\n        )\n    {\n        _checkContractStorageLoad(_contract, _key);\n        return ovmStateManager.getContractStorage(_contract, _key);\n    }\n\n    /**\n     * Sets the value of a storage slot.\n     * @param _contract Address of the contract to modify.\n     * @param _key 32 byte key of the storage slot.\n     * @param _value 32 byte storage slot value.\n     */\n    function _putContractStorage(\n        address _contract,\n        bytes32 _key,\n        bytes32 _value\n    )\n        internal\n    {\n        // We don't set storage if the value didn't change. Although this acts as a convenient\n        // optimization, it's also necessary to avoid the case in which a contract with no storage\n        // attempts to store the value \"0\" at any key. Putting this value (and therefore requiring\n        // that the value be committed into the storage trie after execution) would incorrectly\n        // modify the storage root.\n        if (_getContractStorage(_contract, _key) == _value) {\n            return;\n        }\n\n        _checkContractStorageChange(_contract, _key);\n        ovmStateManager.putContractStorage(_contract, _key, _value);\n    }\n\n    /**\n     * Validation whenever a contract needs to be loaded. Checks that the account exists, charges\n     * nuisance gas if the account hasn't been loaded before.\n     * @param _address Address of the account to load.\n     */\n    function _checkAccountLoad(\n        address _address\n    )\n        internal\n    {\n        // See `_checkContractStorageLoad` for more information.\n        if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {\n            _revertWithFlag(RevertFlag.OUT_OF_GAS);\n        }\n\n        // See `_checkContractStorageLoad` for more information.\n        if (ovmStateManager.hasAccount(_address) == false) {\n            _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);\n        }\n\n        // Check whether the account has been loaded before and mark it as loaded if not. We need\n        // this because \"nuisance gas\" only applies to the first time that an account is loaded.\n        (\n            bool _wasAccountAlreadyLoaded\n        ) = ovmStateManager.testAndSetAccountLoaded(_address);\n\n        // If we hadn't already loaded the account, then we'll need to charge \"nuisance gas\" based\n        // on the size of the contract code.\n        if (_wasAccountAlreadyLoaded == false) {\n            _useNuisanceGas(\n                (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT\n            );\n        }\n    }\n\n    /**\n     * Validation whenever a contract needs to be changed. Checks that the account exists, charges\n     * nuisance gas if the account hasn't been changed before.\n     * @param _address Address of the account to change.\n     */\n    function _checkAccountChange(\n        address _address\n    )\n        internal\n    {\n        // Start by checking for a load as we only want to charge nuisance gas proportional to\n        // contract size once.\n        _checkAccountLoad(_address);\n\n        // Check whether the account has been changed before and mark it as changed if not. We need\n        // this because \"nuisance gas\" only applies to the first time that an account is changed.\n        (\n            bool _wasAccountAlreadyChanged\n        ) = ovmStateManager.testAndSetAccountChanged(_address);\n\n        // If we hadn't already loaded the account, then we'll need to charge \"nuisance gas\" based\n        // on the size of the contract code.\n        if (_wasAccountAlreadyChanged == false) {\n            ovmStateManager.incrementTotalUncommittedAccounts();\n            _useNuisanceGas(\n                (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT\n            );\n        }\n    }\n\n    /**\n     * Validation whenever a slot needs to be loaded. Checks that the account exists, charges\n     * nuisance gas if the slot hasn't been loaded before.\n     * @param _contract Address of the account to load from.\n     * @param _key 32 byte key to load.\n     */\n    function _checkContractStorageLoad(\n        address _contract,\n        bytes32 _key\n    )\n        internal\n    {\n        // Another case of hidden complexity. If we didn't enforce this requirement, then a\n        // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail\n        // on L1 but not on L2. A contract could use this behavior to prevent the\n        // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS\n        // allows us to also charge for the full message nuisance gas, because you deserve that for\n        // trying to break the contract in this way.\n        if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {\n            _revertWithFlag(RevertFlag.OUT_OF_GAS);\n        }\n\n        // We need to make sure that the transaction isn't trying to access storage that hasn't\n        // been provided to the OVM_StateManager. We'll immediately abort if this is the case.\n        // We know that we have enough gas to do this check because of the above test.\n        if (ovmStateManager.hasContractStorage(_contract, _key) == false) {\n            _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);\n        }\n\n        // Check whether the slot has been loaded before and mark it as loaded if not. We need\n        // this because \"nuisance gas\" only applies to the first time that a slot is loaded.\n        (\n            bool _wasContractStorageAlreadyLoaded\n        ) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key);\n\n        // If we hadn't already loaded the account, then we'll need to charge some fixed amount of\n        // \"nuisance gas\".\n        if (_wasContractStorageAlreadyLoaded == false) {\n            _useNuisanceGas(NUISANCE_GAS_SLOAD);\n        }\n    }\n\n    /**\n     * Validation whenever a slot needs to be changed. Checks that the account exists, charges\n     * nuisance gas if the slot hasn't been changed before.\n     * @param _contract Address of the account to change.\n     * @param _key 32 byte key to change.\n     */\n    function _checkContractStorageChange(\n        address _contract,\n        bytes32 _key\n    )\n        internal\n    {\n        // Start by checking for load to make sure we have the storage slot and that we charge the\n        // \"nuisance gas\" necessary to prove the storage slot state.\n        _checkContractStorageLoad(_contract, _key);\n\n        // Check whether the slot has been changed before and mark it as changed if not. We need\n        // this because \"nuisance gas\" only applies to the first time that a slot is changed.\n        (\n            bool _wasContractStorageAlreadyChanged\n        ) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key);\n\n        // If we hadn't already changed the account, then we'll need to charge some fixed amount of\n        // \"nuisance gas\".\n        if (_wasContractStorageAlreadyChanged == false) {\n            // Changing a storage slot means that we're also going to have to change the\n            // corresponding account, so do an account change check.\n            _checkAccountChange(_contract);\n\n            ovmStateManager.incrementTotalUncommittedContractStorage();\n            _useNuisanceGas(NUISANCE_GAS_SSTORE);\n        }\n    }\n\n\n    /************************************\n     * Internal Functions: Revert Logic *\n     ************************************/\n\n    /**\n     * Simple encoding for revert data.\n     * @param _flag Flag to revert with.\n     * @param _data Additional user-provided revert data.\n     * @return _revertdata Encoded revert data.\n     */\n    function _encodeRevertData(\n        RevertFlag _flag,\n        bytes memory _data\n    )\n        internal\n        view\n        returns (\n            bytes memory _revertdata\n        )\n    {\n        // Out of gas and create exceptions will fundamentally return no data, so simulating it shouldn't either.\n        if (\n            _flag == RevertFlag.OUT_OF_GAS\n        ) {\n            return bytes('');\n        }\n\n        // INVALID_STATE_ACCESS doesn't need to return any data other than the flag.\n        if (_flag == RevertFlag.INVALID_STATE_ACCESS) {\n            return abi.encode(\n                _flag,\n                0,\n                0,\n                bytes('')\n            );\n        }\n\n        // Just ABI encode the rest of the parameters.\n        return abi.encode(\n            _flag,\n            messageRecord.nuisanceGasLeft,\n            transactionRecord.ovmGasRefund,\n            _data\n        );\n    }\n\n    /**\n     * Simple decoding for revert data.\n     * @param _revertdata Revert data to decode.\n     * @return _flag Flag used to revert.\n     * @return _nuisanceGasLeft Amount of nuisance gas unused by the message.\n     * @return _ovmGasRefund Amount of gas refunded during the message.\n     * @return _data Additional user-provided revert data.\n     */\n    function _decodeRevertData(\n        bytes memory _revertdata\n    )\n        internal\n        pure\n        returns (\n            RevertFlag _flag,\n            uint256 _nuisanceGasLeft,\n            uint256 _ovmGasRefund,\n            bytes memory _data\n        )\n    {\n        // A length of zero means the call ran out of gas, just return empty data.\n        if (_revertdata.length == 0) {\n            return (\n                RevertFlag.OUT_OF_GAS,\n                0,\n                0,\n                bytes('')\n            );\n        }\n\n        // ABI decode the incoming data.\n        return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes));\n    }\n\n    /**\n     * Causes a message to revert or abort.\n     * @param _flag Flag to revert with.\n     * @param _data Additional user-provided data.\n     */\n    function _revertWithFlag(\n        RevertFlag _flag,\n        bytes memory _data\n    )\n        internal\n        view\n    {\n        bytes memory revertdata = _encodeRevertData(\n            _flag,\n            _data\n        );\n\n        assembly {\n            revert(add(revertdata, 0x20), mload(revertdata))\n        }\n    }\n\n    /**\n     * Causes a message to revert or abort.\n     * @param _flag Flag to revert with.\n     */\n    function _revertWithFlag(\n        RevertFlag _flag\n    )\n        internal\n    {\n        _revertWithFlag(_flag, bytes(''));\n    }\n\n\n    /******************************************\n     * Internal Functions: Nuisance Gas Logic *\n     ******************************************/\n\n    /**\n     * Computes the nuisance gas limit from the gas limit.\n     * @dev This function is currently using a naive implementation whereby the nuisance gas limit\n     *      is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that\n     *      this implementation is perfectly fine, but we may change this formula later.\n     * @param _gasLimit Gas limit to compute from.\n     * @return _nuisanceGasLimit Computed nuisance gas limit.\n     */\n    function _getNuisanceGasLimit(\n        uint256 _gasLimit\n    )\n        internal\n        view\n        returns (\n            uint256 _nuisanceGasLimit\n        )\n    {\n        return _gasLimit < gasleft() ? _gasLimit : gasleft();\n    }\n\n    /**\n     * Uses a certain amount of nuisance gas.\n     * @param _amount Amount of nuisance gas to use.\n     */\n    function _useNuisanceGas(\n        uint256 _amount\n    )\n        internal\n    {\n        // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas\n        // refund to be given at the end of the transaction.\n        if (messageRecord.nuisanceGasLeft < _amount) {\n            _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS);\n        }\n\n        messageRecord.nuisanceGasLeft -= _amount;\n    }\n\n\n    /************************************\n     * Internal Functions: Gas Metering *\n     ************************************/\n\n    /**\n     * Checks whether a transaction needs to start a new epoch and does so if necessary.\n     * @param _timestamp Transaction timestamp.\n     */\n    function _checkNeedsNewEpoch(\n        uint256 _timestamp\n    )\n        internal\n    {\n        if (\n            _timestamp >= (\n                _getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP)\n                + gasMeterConfig.secondsPerEpoch\n            )\n        ) {\n            _putGasMetadata(\n                GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP,\n                _timestamp\n            );\n\n            _putGasMetadata(\n                GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS,\n                _getGasMetadata(\n                    GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS\n                )\n            );\n\n            _putGasMetadata(\n                GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS,\n                _getGasMetadata(\n                    GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS\n                )\n            );\n        }\n    }\n\n    /**\n     * Validates the input values of a transaction.\n     * @return _valid Whether or not the transaction data is valid.\n     */\n    function _isValidInput(\n        Lib_OVMCodec.Transaction memory _transaction\n    )\n        view\n        internal\n        returns (\n            bool\n        )\n    {\n        // Prevent reentrancy to run():\n        // This check prevents calling run with the default ovmNumber.\n        // Combined with the first check in run():\n        //      if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; }\n        // It should be impossible to re-enter since run() returns before any other call frames are created.\n        // Since this value is already being written to storage, we save much gas compared to\n        // using the standard nonReentrant pattern.\n        if (_transaction.blockNumber == DEFAULT_UINT256)  {\n            return false;\n        }\n\n        if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) {\n            return false;\n        }\n\n        return true;\n    }\n\n    /**\n     * Validates the gas limit for a given transaction.\n     * @param _gasLimit Gas limit provided by the transaction.\n     * param _queueOrigin Queue from which the transaction originated.\n     * @return _valid Whether or not the gas limit is valid.\n     */\n    function _isValidGasLimit(\n        uint256 _gasLimit,\n        Lib_OVMCodec.QueueOrigin // _queueOrigin\n    )\n        view\n        internal\n        returns (\n            bool _valid\n        )\n    {\n        // Always have to be below the maximum gas limit.\n        if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) {\n            return false;\n        }\n\n        // Always have to be above the minimum gas limit.\n        if (_gasLimit < gasMeterConfig.minTransactionGasLimit) {\n            return false;\n        }\n\n        // TEMPORARY: Gas metering is disabled for minnet.\n        return true;\n        // GasMetadataKey cumulativeGasKey;\n        // GasMetadataKey prevEpochGasKey;\n        // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) {\n        //     cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;\n        //     prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS;\n        // } else {\n        //     cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;\n        //     prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS;\n        // }\n\n        // return (\n        //     (\n        //         _getGasMetadata(cumulativeGasKey)\n        //         - _getGasMetadata(prevEpochGasKey)\n        //         + _gasLimit\n        //     ) < gasMeterConfig.maxGasPerQueuePerEpoch\n        // );\n    }\n\n    /**\n     * Updates the cumulative gas after a transaction.\n     * @param _gasUsed Gas used by the transaction.\n     * @param _queueOrigin Queue from which the transaction originated.\n     */\n    function _updateCumulativeGas(\n        uint256 _gasUsed,\n        Lib_OVMCodec.QueueOrigin _queueOrigin\n    )\n        internal\n    {\n        GasMetadataKey cumulativeGasKey;\n        if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) {\n            cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;\n        } else {\n            cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;\n        }\n\n        _putGasMetadata(\n            cumulativeGasKey,\n            (\n                _getGasMetadata(cumulativeGasKey)\n                + gasMeterConfig.minTransactionGasLimit\n                + _gasUsed\n                - transactionRecord.ovmGasRefund\n            )\n        );\n    }\n\n    /**\n     * Retrieves the value of a gas metadata key.\n     * @param _key Gas metadata key to retrieve.\n     * @return _value Value stored at the given key.\n     */\n    function _getGasMetadata(\n        GasMetadataKey _key\n    )\n        internal\n        returns (\n            uint256 _value\n        )\n    {\n        return uint256(_getContractStorage(\n            GAS_METADATA_ADDRESS,\n            bytes32(uint256(_key))\n        ));\n    }\n\n    /**\n     * Sets the value of a gas metadata key.\n     * @param _key Gas metadata key to set.\n     * @param _value Value to store at the given key.\n     */\n    function _putGasMetadata(\n        GasMetadataKey _key,\n        uint256 _value\n    )\n        internal\n    {\n        _putContractStorage(\n            GAS_METADATA_ADDRESS,\n            bytes32(uint256(_key)),\n            bytes32(uint256(_value))\n        );\n    }\n\n\n    /*****************************************\n     * Internal Functions: Execution Context *\n     *****************************************/\n\n    /**\n     * Swaps over to a new message context.\n     * @param _prevMessageContext Context we're switching from.\n     * @param _nextMessageContext Context we're switching to.\n     */\n    function _switchMessageContext(\n        MessageContext memory _prevMessageContext,\n        MessageContext memory _nextMessageContext\n    )\n        internal\n    {\n        // These conditionals allow us to avoid unneccessary SSTOREs.  However, they do mean that the current storage\n        // value for the messageContext MUST equal the _prevMessageContext argument, or an SSTORE might be erroneously skipped.\n        if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) {\n            messageContext.ovmCALLER = _nextMessageContext.ovmCALLER;\n        }\n\n        if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) {\n            messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS;\n        }\n\n        if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) {\n            messageContext.isStatic = _nextMessageContext.isStatic;\n        }\n\n        if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) {\n            messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE;\n        }\n    }\n\n    /**\n     * Initializes the execution context.\n     * @param _transaction OVM transaction being executed.\n     */\n    function _initContext(\n        Lib_OVMCodec.Transaction memory _transaction\n    )\n        internal\n    {\n        transactionContext.ovmTIMESTAMP = _transaction.timestamp;\n        transactionContext.ovmNUMBER = _transaction.blockNumber;\n        transactionContext.ovmTXGASLIMIT = _transaction.gasLimit;\n        transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin;\n        transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin;\n        transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch;\n\n        messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit);\n    }\n\n    /**\n     * Resets the transaction and message context.\n     */\n    function _resetContext()\n        internal\n    {\n        transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS;\n        transactionContext.ovmTIMESTAMP = DEFAULT_UINT256;\n        transactionContext.ovmNUMBER = DEFAULT_UINT256;\n        transactionContext.ovmGASLIMIT = DEFAULT_UINT256;\n        transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256;\n        transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE;\n\n        transactionRecord.ovmGasRefund = DEFAULT_UINT256;\n\n        messageContext.ovmCALLER = DEFAULT_ADDRESS;\n        messageContext.ovmADDRESS = DEFAULT_ADDRESS;\n        messageContext.isStatic = false;\n\n        messageRecord.nuisanceGasLeft = DEFAULT_UINT256;\n\n        // Reset the ovmStateManager.\n        ovmStateManager = iOVM_StateManager(address(0));\n    }\n\n\n    /******************************************\n     * Internal Functions: Message Typechecks *\n     ******************************************/\n\n    /**\n     * Returns whether or not the given message type is a CREATE-type.\n     * @param _messageType the message type in question.\n     */\n    function _isCreateType(\n        MessageType _messageType\n    )\n        internal\n        pure\n        returns(\n            bool\n        )\n    {\n        return (\n            _messageType == MessageType.ovmCREATE\n            || _messageType == MessageType.ovmCREATE2\n        );\n    }\n\n    /**\n     * Returns whether or not the given message type (potentially) requires the transfer of ETH value along with the message.\n     * @param _messageType the message type in question.\n     */\n    function _isValueType(\n        MessageType _messageType\n    )\n        internal\n        pure\n        returns(\n            bool\n        )\n    {\n        // ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value.\n        return (\n            _messageType == MessageType.ovmCALL\n            || _messageType == MessageType.ovmCREATE\n            || _messageType == MessageType.ovmCREATE2\n        );\n    }\n\n\n    /*****************************\n     * L2-only Helper Functions *\n     *****************************/\n\n    /**\n     * Unreachable helper function for simulating eth_calls with an OVM message context.\n     * This function will throw an exception in all cases other than when used as a custom entrypoint in L2 Geth to simulate eth_call.\n     * @param _transaction the message transaction to simulate.\n     * @param _from the OVM account the simulated call should be from.\n     * @param _value the amount of ETH value to send.\n     * @param _ovmStateManager the address of the OVM_StateManager precompile in the L2 state.\n     */\n    function simulateMessage(\n        Lib_OVMCodec.Transaction memory _transaction,\n        address _from,\n        uint256 _value,\n        iOVM_StateManager _ovmStateManager\n    )\n        external\n        returns (\n            bytes memory\n        )\n    {\n        // Prevent this call from having any effect unless in a custom-set VM frame\n        require(msg.sender == address(0));\n\n        // Initialize the EM's internal state, ignoring nuisance gas.\n        ovmStateManager = _ovmStateManager;\n        _initContext(_transaction);\n        messageRecord.nuisanceGasLeft = uint(-1);\n\n        // Set the ovmADDRESS to the _from so that the subsequent call frame \"comes from\" them.\n        messageContext.ovmADDRESS = _from;\n\n        // Execute the desired message.\n        bool isCreate = _transaction.entrypoint == address(0);\n        if (isCreate) {\n            (address created, bytes memory revertData) = ovmCREATE(_transaction.data);\n            if (created == address(0)) {\n                return abi.encode(false, revertData);\n            } else {\n                // The eth_call RPC endpoint for to = undefined will return the deployed bytecode\n                // in the success case, differing from standard create messages.\n                return abi.encode(true, Lib_EthUtils.getCode(created));\n            }\n        } else {\n            (bool success, bytes memory returndata) = ovmCALL(\n                _transaction.gasLimit,\n                _transaction.entrypoint,\n                _value,\n                _transaction.data\n            );\n            return abi.encode(success, returndata);\n        }\n    }\n}\n"
    },
    "@openzeppelin/contracts/math/Math.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a >= b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow, so we distribute\n        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/execution/iOVM_SafetyChecker.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title iOVM_SafetyChecker\n */\ninterface iOVM_SafetyChecker {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool);\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_DeployerWhitelist.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Interface Imports */\nimport { iOVM_DeployerWhitelist } from \"../../iOVM/predeploys/iOVM_DeployerWhitelist.sol\";\n\n/**\n * @title OVM_DeployerWhitelist\n * @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the\n * initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts\n * which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an\n * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted.\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_DeployerWhitelist is iOVM_DeployerWhitelist {\n\n    /**********************\n     * Contract Constants *\n     **********************/\n\n    bool public initialized;\n    bool public allowArbitraryDeployment;\n    address override public owner;\n    mapping (address => bool) public whitelist;\n\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    /**\n     * Blocks functions to anyone except the contract owner.\n     */\n    modifier onlyOwner() {\n        require(\n            msg.sender == owner,\n            \"Function can only be called by the owner of this contract.\"\n        );\n        _;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Initializes the whitelist.\n     * @param _owner Address of the owner for this contract.\n     * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.\n     */\n    function initialize(\n        address _owner,\n        bool _allowArbitraryDeployment\n    )\n        override\n        external\n    {\n        if (initialized == true) {\n            return;\n        }\n\n        initialized = true;\n        allowArbitraryDeployment = _allowArbitraryDeployment;\n        owner = _owner;\n    }\n\n    /**\n     * Adds or removes an address from the deployment whitelist.\n     * @param _deployer Address to update permissions for.\n     * @param _isWhitelisted Whether or not the address is whitelisted.\n     */\n    function setWhitelistedDeployer(\n        address _deployer,\n        bool _isWhitelisted\n    )\n        override\n        external\n        onlyOwner\n    {\n        whitelist[_deployer] = _isWhitelisted;\n    }\n\n    /**\n     * Updates the owner of this contract.\n     * @param _owner Address of the new owner.\n     */\n    function setOwner(\n        address _owner\n    )\n        override\n        public\n        onlyOwner\n    {\n        owner = _owner;\n    }\n\n    /**\n     * Updates the arbitrary deployment flag.\n     * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.\n     */\n    function setAllowArbitraryDeployment(\n        bool _allowArbitraryDeployment\n    )\n        override\n        public\n        onlyOwner\n    {\n        allowArbitraryDeployment = _allowArbitraryDeployment;\n    }\n\n    /**\n     * Permanently enables arbitrary contract deployment and deletes the owner.\n     */\n    function enableArbitraryContractDeployment()\n        override\n        external\n        onlyOwner\n    {\n        setAllowArbitraryDeployment(true);\n        setOwner(address(0));\n    }\n\n    /**\n     * Checks whether an address is allowed to deploy contracts.\n     * @param _deployer Address to check.\n     * @return _allowed Whether or not the address can deploy contracts.\n     */\n    function isDeployerAllowed(\n        address _deployer\n    )\n        override\n        external\n        returns (\n            bool\n        )\n    {\n        return (\n            initialized == false\n            || allowArbitraryDeployment == true\n            || whitelist[_deployer]\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/predeploys/iOVM_DeployerWhitelist.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title iOVM_DeployerWhitelist\n */\ninterface iOVM_DeployerWhitelist {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function initialize(address _owner, bool _allowArbitraryDeployment) external;\n    function owner() external returns (address _owner);\n    function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external;\n    function setOwner(address _newOwner) external;\n    function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external;\n    function enableArbitraryContractDeployment() external;\n    function isDeployerAllowed(address _deployer) external returns (bool _allowed);\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/execution/OVM_SafetyChecker.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Interface Imports */\nimport { iOVM_SafetyChecker } from \"../../iOVM/execution/iOVM_SafetyChecker.sol\";\n\n/**\n * @title OVM_SafetyChecker\n * @dev  The Safety Checker verifies that contracts deployed on L2 do not contain any\n * \"unsafe\" operations. An operation is considered unsafe if it would access state variables which\n * are specific to the environment (ie. L1 or L2) in which it is executed, as this could be used\n * to \"escape the sandbox\" of the OVM, resulting in non-deterministic fraud proofs.\n * That is, an attacker would be able to \"prove fraud\" on an honestly applied transaction.\n * Note that a \"safe\" contract requires opcodes to appear in a particular pattern;\n * omission of \"unsafe\" opcodes is necessary, but not sufficient.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_SafetyChecker is iOVM_SafetyChecker {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Returns whether or not all of the provided bytecode is safe.\n     * @param _bytecode The bytecode to safety check.\n     * @return `true` if the bytecode is safe, `false` otherwise.\n     */\n    function isBytecodeSafe(\n        bytes memory _bytecode\n    )\n        override\n        external\n        pure\n        returns (\n            bool\n        )\n    {\n        // autogenerated by gen_safety_checker_constants.py\n        // number of bytes to skip for each opcode\n        uint256[8] memory opcodeSkippableBytes = [\n            uint256(0x0001010101010101010101010000000001010101010101010101010101010000),\n            uint256(0x0100000000000000000000000000000000000000010101010101000000010100),\n            uint256(0x0000000000000000000000000000000001010101000000010101010100000000),\n            uint256(0x0203040500000000000000000000000000000000000000000000000000000000),\n            uint256(0x0101010101010101010101010101010101010101010101010101010101010101),\n            uint256(0x0101010101000000000000000000000000000000000000000000000000000000),\n            uint256(0x0000000000000000000000000000000000000000000000000000000000000000),\n            uint256(0x0000000000000000000000000000000000000000000000000000000000000000)\n        ];\n        // Mask to gate opcode specific cases\n        uint256 opcodeGateMask = ~uint256(0xffffffffffffffffffffffe000000000fffffffff070ffff9c0ffffec000f001);\n        // Halting opcodes\n        uint256 opcodeHaltingMask = ~uint256(0x4008000000000000000000000000000000000000004000000000000000000001);\n        // PUSH opcodes\n        uint256 opcodePushMask = ~uint256(0xffffffff000000000000000000000000);\n\n        uint256 codeLength;\n        uint256 _pc;\n        assembly {\n            _pc := add(_bytecode, 0x20)\n        }\n        codeLength = _pc + _bytecode.length;\n        do {\n            // current opcode: 0x00...0xff\n            uint256 opNum;\n\n            // inline assembly removes the extra add + bounds check\n            assembly {\n                let word := mload(_pc) //load the next 32 bytes at pc into word\n\n                // Look up number of bytes to skip from opcodeSkippableBytes and then update indexInWord\n                // E.g. the 02030405 in opcodeSkippableBytes is the number of bytes to skip for PUSH1->4\n                // We repeat this 6 times, thus we can only skip bytes for up to PUSH4 ((1+4) * 6 = 30 < 32).\n                // If we see an opcode that is listed as 0 skippable bytes e.g. PUSH5,\n                // then we will get stuck on that indexInWord and then opNum will be set to the PUSH5 opcode.\n                let indexInWord := byte(0, mload(add(opcodeSkippableBytes, byte(0, word))))\n                indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))\n                indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))\n                indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))\n                indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))\n                indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))\n                _pc := add(_pc, indexInWord)\n\n                opNum := byte(indexInWord, word)\n            }\n\n            // + push opcodes\n            // + stop opcodes [STOP(0x00),JUMP(0x56),RETURN(0xf3),INVALID(0xfe)]\n            // + caller opcode CALLER(0x33)\n            // + blacklisted opcodes\n            uint256 opBit = 1 << opNum;\n            if (opBit & opcodeGateMask == 0) {\n                if (opBit & opcodePushMask == 0) {\n                    // all pushes are valid opcodes\n                    // subsequent bytes are not opcodes. Skip them.\n                    _pc += (opNum - 0x5e); // PUSH1 is 0x60, so opNum-0x5f = PUSHed bytes and we +1 to\n                    // skip the _pc++; line below in order to save gas ((-0x5f + 1) = -0x5e)\n                    continue;\n                } else if (opBit & opcodeHaltingMask == 0) {\n                    // STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not included here)\n                    // We are now inside unreachable code until we hit a JUMPDEST!\n                    do {\n                        _pc++;\n                        assembly {\n                            opNum := byte(0, mload(_pc))\n                        }\n                        // encountered a JUMPDEST\n                        if (opNum == 0x5b) break;\n                        // skip PUSHed bytes\n                        if ((1 << opNum) & opcodePushMask == 0) _pc += (opNum - 0x5f); // opNum-0x5f = PUSHed bytes (PUSH1 is 0x60)\n                    } while (_pc < codeLength);\n                    // opNum is 0x5b, so we don't continue here since the pc++ is fine\n                } else if (opNum == 0x33) { // Caller opcode\n                    uint256 firstOps; // next 32 bytes of bytecode\n                    uint256 secondOps; // following 32 bytes of bytecode\n\n                    assembly {\n                        firstOps := mload(_pc)\n                        // 37 bytes total, 5 left over --> 32 - 5 bytes = 27 bytes = 216 bits\n                        secondOps := shr(216, mload(add(_pc, 0x20)))\n                    }\n\n                    // Call identity precompile\n                    // CALLER POP PUSH1 0x00 PUSH1 0x04 GAS CALL\n                    // 32 - 8 bytes = 24 bytes = 192\n                    if ((firstOps >> 192) == 0x3350600060045af1) {\n                        _pc += 8;\n                    // Call EM and abort execution if instructed\n                    // CALLER PUSH1 0x00 SWAP1 GAS CALL PC PUSH1 0x0E ADD JUMPI RETURNDATASIZE PUSH1 0x00 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x00 REVERT JUMPDEST RETURNDATASIZE PUSH1 0x01 EQ ISZERO PC PUSH1 0x0a ADD JUMPI PUSH1 0x01 PUSH1 0x00 RETURN JUMPDEST\n                    } else if (firstOps == 0x336000905af158600e01573d6000803e3d6000fd5b3d6001141558600a015760 && secondOps == 0x016000f35b) {\n                        _pc += 37;\n                    } else {\n                        return false;\n                    }\n                    continue;\n                } else {\n                    // encountered a non-whitelisted opcode!\n                    return false;\n                }\n            }\n            _pc++;\n        } while (_pc < codeLength);\n        return true;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/execution/OVM_StateManagerFactory.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Interface Imports */\nimport { iOVM_StateManager } from \"../../iOVM/execution/iOVM_StateManager.sol\";\nimport { iOVM_StateManagerFactory } from \"../../iOVM/execution/iOVM_StateManagerFactory.sol\";\n\n/* Contract Imports */\nimport { OVM_StateManager } from \"./OVM_StateManager.sol\";\n\n/**\n * @title OVM_StateManagerFactory\n * @dev The State Manager Factory is called by a State Transitioner's init code, to create a new\n * State Manager for use in the Fraud Verification process.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_StateManagerFactory is iOVM_StateManagerFactory {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Creates a new OVM_StateManager\n     * @param _owner Owner of the created contract.\n     * @return New OVM_StateManager instance.\n     */\n    function create(\n        address _owner\n    )\n        override\n        public\n        returns (\n            iOVM_StateManager\n        )\n    {\n        return new OVM_StateManager(_owner);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/execution/OVM_StateManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../libraries/codec/Lib_OVMCodec.sol\";\n\n/* Interface Imports */\nimport { iOVM_StateManager } from \"../../iOVM/execution/iOVM_StateManager.sol\";\n\n/**\n * @title OVM_StateManager\n * @dev The State Manager contract holds all storage values for contracts in the OVM. It can only be written to by the\n * the Execution Manager and State Transitioner. It runs on L1 during the setup and execution of a fraud proof.\n * The same logic runs on L2, but has been implemented as a precompile in the L2 go-ethereum client\n * (see https://github.com/ethereum-optimism/go-ethereum/blob/master/core/vm/ovm_state_manager.go).\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_StateManager is iOVM_StateManager {\n\n    /*************\n     * Constants *\n     *************/\n\n    bytes32 constant internal EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;\n    bytes32 constant internal EMPTY_ACCOUNT_CODE_HASH =    0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n    bytes32 constant internal STORAGE_XOR_VALUE =          0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEF;\n\n\n    /*************\n     * Variables *\n     *************/\n\n    address override public owner;\n    address override public ovmExecutionManager;\n    mapping (address => Lib_OVMCodec.Account) internal accounts;\n    mapping (address => mapping (bytes32 => bytes32)) internal contractStorage;\n    mapping (address => mapping (bytes32 => bool)) internal verifiedContractStorage;\n    mapping (bytes32 => ItemState) internal itemStates;\n    uint256 internal totalUncommittedAccounts;\n    uint256 internal totalUncommittedContractStorage;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _owner Address of the owner of this contract.\n     */\n    constructor(\n        address _owner\n    )\n    {\n        owner = _owner;\n    }\n\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    /**\n     * Simple authentication, this contract should only be accessible to the owner (which is expected to be the State Transitioner during `PRE_EXECUTION`\n     * or the OVM_ExecutionManager during transaction execution.\n     */\n    modifier authenticated() {\n        // owner is the State Transitioner\n        require(\n            msg.sender == owner || msg.sender == ovmExecutionManager,\n            \"Function can only be called by authenticated addresses\"\n        );\n        _;\n    }\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Checks whether a given address is allowed to modify this contract.\n     * @param _address Address to check.\n     * @return Whether or not the address can modify this contract.\n     */\n    function isAuthenticated(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        return (_address == owner || _address == ovmExecutionManager);\n    }\n\n    /**\n     * Sets the address of the OVM_ExecutionManager.\n     * @param _ovmExecutionManager Address of the OVM_ExecutionManager.\n     */\n    function setExecutionManager(\n        address _ovmExecutionManager\n    )\n        override\n        public\n        authenticated\n    {\n        ovmExecutionManager = _ovmExecutionManager;\n    }\n\n    /**\n     * Inserts an account into the state.\n     * @param _address Address of the account to insert.\n     * @param _account Account to insert for the given address.\n     */\n    function putAccount(\n        address _address,\n        Lib_OVMCodec.Account memory _account\n    )\n        override\n        public\n        authenticated\n    {\n        accounts[_address] = _account;\n    }\n\n    /**\n     * Marks an account as empty.\n     * @param _address Address of the account to mark.\n     */\n    function putEmptyAccount(\n        address _address\n    )\n        override\n        public\n        authenticated\n    {\n        Lib_OVMCodec.Account storage account = accounts[_address];\n        account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;\n        account.codeHash = EMPTY_ACCOUNT_CODE_HASH;\n    }\n\n    /**\n     * Retrieves an account from the state.\n     * @param _address Address of the account to retrieve.\n     * @return Account for the given address.\n     */\n    function getAccount(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            Lib_OVMCodec.Account memory\n        )\n    {\n        return accounts[_address];\n    }\n\n    /**\n     * Checks whether the state has a given account.\n     * @param _address Address of the account to check.\n     * @return Whether or not the state has the account.\n     */\n    function hasAccount(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        return accounts[_address].codeHash != bytes32(0);\n    }\n\n    /**\n     * Checks whether the state has a given known empty account.\n     * @param _address Address of the account to check.\n     * @return Whether or not the state has the empty account.\n     */\n    function hasEmptyAccount(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        return (\n            accounts[_address].codeHash == EMPTY_ACCOUNT_CODE_HASH\n            && accounts[_address].nonce == 0\n        );\n    }\n\n    /**\n     * Sets the nonce of an account.\n     * @param _address Address of the account to modify.\n     * @param _nonce New account nonce.\n     */\n    function setAccountNonce(\n        address _address,\n        uint256 _nonce\n    )\n        override\n        public\n        authenticated\n    {\n        accounts[_address].nonce = _nonce;\n    }\n\n    /**\n     * Gets the nonce of an account.\n     * @param _address Address of the account to access.\n     * @return Nonce of the account.\n     */\n    function getAccountNonce(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            uint256\n        )\n    {\n        return accounts[_address].nonce;\n    }\n\n    /**\n     * Retrieves the Ethereum address of an account.\n     * @param _address Address of the account to access.\n     * @return Corresponding Ethereum address.\n     */\n    function getAccountEthAddress(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            address\n        )\n    {\n        return accounts[_address].ethAddress;\n    }\n\n    /**\n     * Retrieves the storage root of an account.\n     * @param _address Address of the account to access.\n     * @return Corresponding storage root.\n     */\n    function getAccountStorageRoot(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            bytes32\n        )\n    {\n        return accounts[_address].storageRoot;\n    }\n\n    /**\n     * Initializes a pending account (during CREATE or CREATE2) with the default values.\n     * @param _address Address of the account to initialize.\n     */\n    function initPendingAccount(\n        address _address\n    )\n        override\n        public\n        authenticated\n    {\n        Lib_OVMCodec.Account storage account = accounts[_address];\n        account.nonce = 1;\n        account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;\n        account.codeHash = EMPTY_ACCOUNT_CODE_HASH;\n        account.isFresh = true;\n    }\n\n    /**\n     * Finalizes the creation of a pending account (during CREATE or CREATE2).\n     * @param _address Address of the account to finalize.\n     * @param _ethAddress Address of the account's associated contract on Ethereum.\n     * @param _codeHash Hash of the account's code.\n     */\n    function commitPendingAccount(\n        address _address,\n        address _ethAddress,\n        bytes32 _codeHash\n    )\n        override\n        public\n        authenticated\n    {\n        Lib_OVMCodec.Account storage account = accounts[_address];\n        account.ethAddress = _ethAddress;\n        account.codeHash = _codeHash;\n    }\n\n    /**\n     * Checks whether an account has already been retrieved, and marks it as retrieved if not.\n     * @param _address Address of the account to check.\n     * @return Whether or not the account was already loaded.\n     */\n    function testAndSetAccountLoaded(\n        address _address\n    )\n        override\n        public\n        authenticated\n        returns (\n            bool\n        )\n    {\n        return _testAndSetItemState(\n            _getItemHash(_address),\n            ItemState.ITEM_LOADED\n        );\n    }\n\n    /**\n     * Checks whether an account has already been modified, and marks it as modified if not.\n     * @param _address Address of the account to check.\n     * @return Whether or not the account was already modified.\n     */\n    function testAndSetAccountChanged(\n        address _address\n    )\n        override\n        public\n        authenticated\n        returns (\n            bool\n        )\n    {\n        return _testAndSetItemState(\n            _getItemHash(_address),\n            ItemState.ITEM_CHANGED\n        );\n    }\n\n    /**\n     * Attempts to mark an account as committed.\n     * @param _address Address of the account to commit.\n     * @return Whether or not the account was committed.\n     */\n    function commitAccount(\n        address _address\n    )\n        override\n        public\n        authenticated\n        returns (\n            bool\n        )\n    {\n        bytes32 item = _getItemHash(_address);\n        if (itemStates[item] != ItemState.ITEM_CHANGED) {\n            return false;\n        }\n\n        itemStates[item] = ItemState.ITEM_COMMITTED;\n        totalUncommittedAccounts -= 1;\n\n        return true;\n    }\n\n    /**\n     * Increments the total number of uncommitted accounts.\n     */\n    function incrementTotalUncommittedAccounts()\n        override\n        public\n        authenticated\n    {\n        totalUncommittedAccounts += 1;\n    }\n\n    /**\n     * Gets the total number of uncommitted accounts.\n     * @return Total uncommitted accounts.\n     */\n    function getTotalUncommittedAccounts()\n        override\n        public\n        view\n        returns (\n            uint256\n        )\n    {\n        return totalUncommittedAccounts;\n    }\n\n    /**\n     * Checks whether a given account was changed during execution.\n     * @param _address Address to check.\n     * @return Whether or not the account was changed.\n     */\n    function wasAccountChanged(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        bytes32 item = _getItemHash(_address);\n        return itemStates[item] >= ItemState.ITEM_CHANGED;\n    }\n\n    /**\n     * Checks whether a given account was committed after execution.\n     * @param _address Address to check.\n     * @return Whether or not the account was committed.\n     */\n    function wasAccountCommitted(\n        address _address\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        bytes32 item = _getItemHash(_address);\n        return itemStates[item] >= ItemState.ITEM_COMMITTED;\n    }\n\n\n    /************************************\n     * Public Functions: Storage Access *\n     ************************************/\n\n    /**\n     * Changes a contract storage slot value.\n     * @param _contract Address of the contract to modify.\n     * @param _key 32 byte storage slot key.\n     * @param _value 32 byte storage slot value.\n     */\n    function putContractStorage(\n        address _contract,\n        bytes32 _key,\n        bytes32 _value\n    )\n        override\n        public\n        authenticated\n    {\n        // A hilarious optimization. `SSTORE`ing a value of `bytes32(0)` is common enough that it's\n        // worth populating this with a non-zero value in advance (during the fraud proof\n        // initialization phase) to cut the execution-time cost down to 5000 gas.\n        contractStorage[_contract][_key] = _value ^ STORAGE_XOR_VALUE;\n\n        // Only used when initially populating the contract storage. OVM_ExecutionManager will\n        // perform a `hasContractStorage` INVALID_STATE_ACCESS check before putting any contract\n        // storage because writing to zero when the actual value is nonzero causes a gas\n        // discrepancy. Could be moved into a new `putVerifiedContractStorage` function, or\n        // something along those lines.\n        if (verifiedContractStorage[_contract][_key] == false) {\n            verifiedContractStorage[_contract][_key] = true;\n        }\n    }\n\n    /**\n     * Retrieves a contract storage slot value.\n     * @param _contract Address of the contract to access.\n     * @param _key 32 byte storage slot key.\n     * @return 32 byte storage slot value.\n     */\n    function getContractStorage(\n        address _contract,\n        bytes32 _key\n    )\n        override\n        public\n        view\n        returns (\n            bytes32\n        )\n    {\n        // Storage XOR system doesn't work for newly created contracts that haven't set this\n        // storage slot value yet.\n        if (\n            verifiedContractStorage[_contract][_key] == false\n            && accounts[_contract].isFresh\n        ) {\n            return bytes32(0);\n        }\n\n        // See `putContractStorage` for more information about the XOR here.\n        return contractStorage[_contract][_key] ^ STORAGE_XOR_VALUE;\n    }\n\n    /**\n     * Checks whether a contract storage slot exists in the state.\n     * @param _contract Address of the contract to access.\n     * @param _key 32 byte storage slot key.\n     * @return Whether or not the key was set in the state.\n     */\n    function hasContractStorage(\n        address _contract,\n        bytes32 _key\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        return verifiedContractStorage[_contract][_key] || accounts[_contract].isFresh;\n    }\n\n    /**\n     * Checks whether a storage slot has already been retrieved, and marks it as retrieved if not.\n     * @param _contract Address of the contract to check.\n     * @param _key 32 byte storage slot key.\n     * @return Whether or not the slot was already loaded.\n     */\n    function testAndSetContractStorageLoaded(\n        address _contract,\n        bytes32 _key\n    )\n        override\n        public\n        authenticated\n        returns (\n            bool\n        )\n    {\n        return _testAndSetItemState(\n            _getItemHash(_contract, _key),\n            ItemState.ITEM_LOADED\n        );\n    }\n\n    /**\n     * Checks whether a storage slot has already been modified, and marks it as modified if not.\n     * @param _contract Address of the contract to check.\n     * @param _key 32 byte storage slot key.\n     * @return Whether or not the slot was already modified.\n     */\n    function testAndSetContractStorageChanged(\n        address _contract,\n        bytes32 _key\n    )\n        override\n        public\n        authenticated\n        returns (\n            bool\n        )\n    {\n        return _testAndSetItemState(\n            _getItemHash(_contract, _key),\n            ItemState.ITEM_CHANGED\n        );\n    }\n\n    /**\n     * Attempts to mark a storage slot as committed.\n     * @param _contract Address of the account to commit.\n     * @param _key 32 byte slot key to commit.\n     * @return Whether or not the slot was committed.\n     */\n    function commitContractStorage(\n        address _contract,\n        bytes32 _key\n    )\n        override\n        public\n        authenticated\n        returns (\n            bool\n        )\n    {\n        bytes32 item = _getItemHash(_contract, _key);\n        if (itemStates[item] != ItemState.ITEM_CHANGED) {\n            return false;\n        }\n\n        itemStates[item] = ItemState.ITEM_COMMITTED;\n        totalUncommittedContractStorage -= 1;\n\n        return true;\n    }\n\n    /**\n     * Increments the total number of uncommitted storage slots.\n     */\n    function incrementTotalUncommittedContractStorage()\n        override\n        public\n        authenticated\n    {\n        totalUncommittedContractStorage += 1;\n    }\n\n    /**\n     * Gets the total number of uncommitted storage slots.\n     * @return Total uncommitted storage slots.\n     */\n    function getTotalUncommittedContractStorage()\n        override\n        public\n        view\n        returns (\n            uint256\n        )\n    {\n        return totalUncommittedContractStorage;\n    }\n\n    /**\n     * Checks whether a given storage slot was changed during execution.\n     * @param _contract Address to check.\n     * @param _key Key of the storage slot to check.\n     * @return Whether or not the storage slot was changed.\n     */\n    function wasContractStorageChanged(\n        address _contract,\n        bytes32 _key\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        bytes32 item = _getItemHash(_contract, _key);\n        return itemStates[item] >= ItemState.ITEM_CHANGED;\n    }\n\n    /**\n     * Checks whether a given storage slot was committed after execution.\n     * @param _contract Address to check.\n     * @param _key Key of the storage slot to check.\n     * @return Whether or not the storage slot was committed.\n     */\n    function wasContractStorageCommitted(\n        address _contract,\n        bytes32 _key\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        bytes32 item = _getItemHash(_contract, _key);\n        return itemStates[item] >= ItemState.ITEM_COMMITTED;\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Generates a unique hash for an address.\n     * @param _address Address to generate a hash for.\n     * @return Unique hash for the given address.\n     */\n    function _getItemHash(\n        address _address\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return keccak256(abi.encodePacked(_address));\n    }\n\n    /**\n     * Generates a unique hash for an address/key pair.\n     * @param _contract Address to generate a hash for.\n     * @param _key Key to generate a hash for.\n     * @return Unique hash for the given pair.\n     */\n    function _getItemHash(\n        address _contract,\n        bytes32 _key\n    )\n        internal\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return keccak256(abi.encodePacked(\n            _contract,\n            _key\n        ));\n    }\n\n    /**\n     * Checks whether an item is in a particular state (ITEM_LOADED or ITEM_CHANGED) and sets the\n     * item to the provided state if not.\n     * @param _item 32 byte item ID to check.\n     * @param _minItemState Minimum state that must be satisfied by the item.\n     * @return Whether or not the item was already in the state.\n     */\n    function _testAndSetItemState(\n        bytes32 _item,\n        ItemState _minItemState\n    )\n        internal\n        returns (\n            bool\n        )\n    {\n        bool wasItemState = itemStates[_item] >= _minItemState;\n\n        if (wasItemState == false) {\n            itemStates[_item] = _minItemState;\n        }\n\n        return wasItemState;\n    }\n}\n"
    },
    "contracts/test-libraries/codec/TestLib_OVMCodec.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../optimistic-ethereum/libraries/codec/Lib_OVMCodec.sol\";\n\n/**\n * @title TestLib_OVMCodec\n */\ncontract TestLib_OVMCodec {\n    function encodeTransaction(\n        Lib_OVMCodec.Transaction memory _transaction\n    )\n        public\n        pure\n        returns (\n            bytes memory _encoded\n        )\n    {\n        return Lib_OVMCodec.encodeTransaction(_transaction);\n    }\n\n    function hashTransaction(\n        Lib_OVMCodec.Transaction memory _transaction\n    )\n        public\n        pure\n        returns (\n            bytes32 _hash\n        )\n    {\n        return Lib_OVMCodec.hashTransaction(_transaction);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1CrossDomainMessenger.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_AddressResolver } from \"../../../libraries/resolver/Lib_AddressResolver.sol\";\nimport { Lib_OVMCodec } from \"../../../libraries/codec/Lib_OVMCodec.sol\";\nimport { Lib_AddressManager } from \"../../../libraries/resolver/Lib_AddressManager.sol\";\nimport { Lib_SecureMerkleTrie } from \"../../../libraries/trie/Lib_SecureMerkleTrie.sol\";\nimport { Lib_PredeployAddresses } from \"../../../libraries/constants/Lib_PredeployAddresses.sol\";\nimport { Lib_CrossDomainUtils } from \"../../../libraries/bridge/Lib_CrossDomainUtils.sol\";\n\n/* Interface Imports */\nimport { iOVM_L1CrossDomainMessenger } from \"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol\";\nimport { iOVM_CanonicalTransactionChain } from \"../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol\";\nimport { iOVM_StateCommitmentChain } from \"../../../iOVM/chain/iOVM_StateCommitmentChain.sol\";\n\n/* External Imports */\nimport { OwnableUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { PausableUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\n\n/**\n * @title OVM_L1CrossDomainMessenger\n * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages\n * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2\n * epoch gas limit, it can be resubmitted via this contract's replay function.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_L1CrossDomainMessenger is\n        iOVM_L1CrossDomainMessenger,\n        Lib_AddressResolver,\n        OwnableUpgradeable,\n        PausableUpgradeable,\n        ReentrancyGuardUpgradeable\n{\n\n    /**********\n     * Events *\n     **********/\n\n    event MessageBlocked(\n        bytes32 indexed _xDomainCalldataHash\n    );\n\n    event MessageAllowed(\n        bytes32 indexed _xDomainCalldataHash\n    );\n\n    /*************\n     * Constants *\n     *************/\n\n    // The default x-domain message sender being set to a non-zero value makes\n    // deployment a bit more expensive, but in exchange the refund on every call to\n    // `relayMessage` by the L1 and L2 messengers will be higher.\n    address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;\n\n    /**********************\n     * Contract Variables *\n     **********************/\n\n    mapping (bytes32 => bool) public blockedMessages;\n    mapping (bytes32 => bool) public relayedMessages;\n    mapping (bytes32 => bool) public successfulMessages;\n\n    address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * This contract is intended to be behind a delegate proxy.\n     * We pass the zero address to the address resolver just to satisfy the constructor.\n     * We still need to set this value in initialize().\n     */\n    constructor()\n        Lib_AddressResolver(address(0))\n    {}\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    /**\n     * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may\n     * successfully call a method.\n     */\n    modifier onlyRelayer() {\n        address relayer = resolve(\"OVM_L2MessageRelayer\");\n        if (relayer != address(0)) {\n            require(\n                msg.sender == relayer,\n                \"Only OVM_L2MessageRelayer can relay L2-to-L1 messages.\"\n            );\n        }\n        _;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     */\n    function initialize(\n        address _libAddressManager\n    )\n        public\n        initializer\n    {\n        require(\n            address(libAddressManager) == address(0),\n            \"L1CrossDomainMessenger already intialized.\"\n        );\n        libAddressManager = Lib_AddressManager(_libAddressManager);\n        xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;\n\n        // Initialize upgradable OZ contracts\n        __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable\n        __Ownable_init_unchained();\n        __Pausable_init_unchained();\n        __ReentrancyGuard_init_unchained();\n    }\n\n    /**\n     * Pause relaying.\n     */\n    function pause()\n        external\n        onlyOwner\n    {\n        _pause();\n    }\n\n    /**\n     * Block a message.\n     * @param _xDomainCalldataHash Hash of the message to block.\n     */\n    function blockMessage(\n        bytes32 _xDomainCalldataHash\n    )\n        external\n        onlyOwner\n    {\n        blockedMessages[_xDomainCalldataHash] = true;\n        emit MessageBlocked(_xDomainCalldataHash);\n    }\n\n    /**\n     * Allow a message.\n     * @param _xDomainCalldataHash Hash of the message to block.\n     */\n    function allowMessage(\n        bytes32 _xDomainCalldataHash\n    )\n        external\n        onlyOwner\n    {\n        blockedMessages[_xDomainCalldataHash] = false;\n        emit MessageAllowed(_xDomainCalldataHash);\n    }\n\n    function xDomainMessageSender()\n        public\n        override\n        view\n        returns (\n            address\n        )\n    {\n        require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, \"xDomainMessageSender is not set\");\n        return xDomainMsgSender;\n    }\n\n    /**\n     * Sends a cross domain message to the target messenger.\n     * @param _target Target contract address.\n     * @param _message Message to send to the target.\n     * @param _gasLimit Gas limit for the provided message.\n     */\n    function sendMessage(\n        address _target,\n        bytes memory _message,\n        uint32 _gasLimit\n    )\n        override\n        public\n    {\n        address ovmCanonicalTransactionChain = resolve(\"OVM_CanonicalTransactionChain\");\n        // Use the CTC queue length as nonce\n        uint40 nonce = iOVM_CanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength();\n\n        bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(\n            _target,\n            msg.sender,\n            _message,\n            nonce\n        );\n\n        address l2CrossDomainMessenger = resolve(\"OVM_L2CrossDomainMessenger\");\n        _sendXDomainMessage(ovmCanonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit);\n        emit SentMessage(xDomainCalldata);\n    }\n\n    /**\n     * Relays a cross domain message to a contract.\n     * @inheritdoc iOVM_L1CrossDomainMessenger\n     */\n    function relayMessage(\n        address _target,\n        address _sender,\n        bytes memory _message,\n        uint256 _messageNonce,\n        L2MessageInclusionProof memory _proof\n    )\n        override\n        public\n        nonReentrant\n        onlyRelayer\n        whenNotPaused\n    {\n        bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(\n            _target,\n            _sender,\n            _message,\n            _messageNonce\n        );\n\n        require(\n            _verifyXDomainMessage(\n                xDomainCalldata,\n                _proof\n            ) == true,\n            \"Provided message could not be verified.\"\n        );\n\n        bytes32 xDomainCalldataHash = keccak256(xDomainCalldata);\n\n        require(\n            successfulMessages[xDomainCalldataHash] == false,\n            \"Provided message has already been received.\"\n        );\n\n        require(\n            blockedMessages[xDomainCalldataHash] == false,\n            \"Provided message has been blocked.\"\n        );\n\n        require(\n            _target != resolve(\"OVM_CanonicalTransactionChain\"),\n            \"Cannot send L2->L1 messages to L1 system contracts.\"\n        );\n\n        xDomainMsgSender = _sender;\n        (bool success, ) = _target.call(_message);\n        xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;\n\n        // Mark the message as received if the call was successful. Ensures that a message can be\n        // relayed multiple times in the case that the call reverted.\n        if (success == true) {\n            successfulMessages[xDomainCalldataHash] = true;\n            emit RelayedMessage(xDomainCalldataHash);\n        } else {\n            emit FailedRelayedMessage(xDomainCalldataHash);\n        }\n\n        // Store an identifier that can be used to prove that the given message was relayed by some\n        // user. Gives us an easy way to pay relayers for their work.\n        bytes32 relayId = keccak256(\n            abi.encodePacked(\n                xDomainCalldata,\n                msg.sender,\n                block.number\n            )\n        );\n        relayedMessages[relayId] = true;\n    }\n\n    /**\n     * Replays a cross domain message to the target messenger.\n     * @inheritdoc iOVM_L1CrossDomainMessenger\n     */\n    function replayMessage(\n        address _target,\n        address _sender,\n        bytes memory _message,\n        uint256 _queueIndex,\n        uint32 _gasLimit\n    )\n        override\n        public\n    {\n        // Verify that the message is in the queue:\n        address canonicalTransactionChain = resolve(\"OVM_CanonicalTransactionChain\");\n        Lib_OVMCodec.QueueElement memory element = iOVM_CanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex);\n\n        address l2CrossDomainMessenger = resolve(\"OVM_L2CrossDomainMessenger\");\n        // Compute the transactionHash\n        bytes32 transactionHash = keccak256(\n            abi.encode(\n                address(this),\n                l2CrossDomainMessenger,\n                _gasLimit,\n                _message\n            )\n        );\n\n        require(\n            transactionHash == element.transactionHash,\n            \"Provided message has not been enqueued.\"\n        );\n\n        bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(\n            _target,\n            _sender,\n            _message,\n            _queueIndex\n        );\n\n        _sendXDomainMessage(canonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit);\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Verifies that the given message is valid.\n     * @param _xDomainCalldata Calldata to verify.\n     * @param _proof Inclusion proof for the message.\n     * @return Whether or not the provided message is valid.\n     */\n    function _verifyXDomainMessage(\n        bytes memory _xDomainCalldata,\n        L2MessageInclusionProof memory _proof\n    )\n        internal\n        view\n        returns (\n            bool\n        )\n    {\n        return (\n            _verifyStateRootProof(_proof)\n            && _verifyStorageProof(_xDomainCalldata, _proof)\n        );\n    }\n\n    /**\n     * Verifies that the state root within an inclusion proof is valid.\n     * @param _proof Message inclusion proof.\n     * @return Whether or not the provided proof is valid.\n     */\n    function _verifyStateRootProof(\n        L2MessageInclusionProof memory _proof\n    )\n        internal\n        view\n        returns (\n            bool\n        )\n    {\n        iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(\n            resolve(\"OVM_StateCommitmentChain\")\n        );\n\n        return (\n            ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false\n            && ovmStateCommitmentChain.verifyStateCommitment(\n                _proof.stateRoot,\n                _proof.stateRootBatchHeader,\n                _proof.stateRootProof\n            )\n        );\n    }\n\n    /**\n     * Verifies that the storage proof within an inclusion proof is valid.\n     * @param _xDomainCalldata Encoded message calldata.\n     * @param _proof Message inclusion proof.\n     * @return Whether or not the provided proof is valid.\n     */\n    function _verifyStorageProof(\n        bytes memory _xDomainCalldata,\n        L2MessageInclusionProof memory _proof\n    )\n        internal\n        view\n        returns (\n            bool\n        )\n    {\n        bytes32 storageKey = keccak256(\n            abi.encodePacked(\n                keccak256(\n                    abi.encodePacked(\n                        _xDomainCalldata,\n                        resolve(\"OVM_L2CrossDomainMessenger\")\n                    )\n                ),\n                uint256(0)\n            )\n        );\n\n        (\n            bool exists,\n            bytes memory encodedMessagePassingAccount\n        ) = Lib_SecureMerkleTrie.get(\n            abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER),\n            _proof.stateTrieWitness,\n            _proof.stateRoot\n        );\n\n        require(\n            exists == true,\n            \"Message passing predeploy has not been initialized or invalid proof provided.\"\n        );\n\n        Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(\n            encodedMessagePassingAccount\n        );\n\n        return Lib_SecureMerkleTrie.verifyInclusionProof(\n            abi.encodePacked(storageKey),\n            abi.encodePacked(uint8(1)),\n            _proof.storageTrieWitness,\n            account.storageRoot\n        );\n    }\n\n    /**\n     * Sends a cross domain message.\n     * @param _canonicalTransactionChain Address of the OVM_CanonicalTransactionChain instance.\n     * @param _l2CrossDomainMessenger Address of the OVM_L2CrossDomainMessenger instance.\n     * @param _message Message to send.\n     * @param _gasLimit OVM gas limit for the message.\n     */\n    function _sendXDomainMessage(\n        address _canonicalTransactionChain,\n        address _l2CrossDomainMessenger,\n        bytes memory _message,\n        uint256 _gasLimit\n    )\n        internal\n    {\n        iOVM_CanonicalTransactionChain(_canonicalTransactionChain).enqueue(\n            _l2CrossDomainMessenger,\n            _gasLimit,\n            _message\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/bridge/Lib_CrossDomainUtils.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_RLPReader } from \"../rlp/Lib_RLPReader.sol\";\n\n/**\n * @title Lib_CrossDomainUtils\n */\nlibrary Lib_CrossDomainUtils {\n    /**\n     * Generates the correct cross domain calldata for a message.\n     * @param _target Target contract address.\n     * @param _sender Message sender address.\n     * @param _message Message to send to the target.\n     * @param _messageNonce Nonce for the provided message.\n     * @return ABI encoded cross domain calldata.\n     */\n    function encodeXDomainCalldata(\n        address _target,\n        address _sender,\n        bytes memory _message,\n        uint256 _messageNonce\n    )\n        internal\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return abi.encodeWithSignature(\n            \"relayMessage(address,address,bytes,uint256)\",\n            _target,\n            _sender,\n            _message,\n            _messageNonce\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_OVMCodec } from \"../../../libraries/codec/Lib_OVMCodec.sol\";\n\n/* Interface Imports */\nimport { iOVM_CrossDomainMessenger } from \"./iOVM_CrossDomainMessenger.sol\";\n\n/**\n * @title iOVM_L1CrossDomainMessenger\n */\ninterface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger {\n\n    /*******************\n     * Data Structures *\n     *******************/\n\n    struct L2MessageInclusionProof {\n        bytes32 stateRoot;\n        Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader;\n        Lib_OVMCodec.ChainInclusionProof stateRootProof;\n        bytes stateTrieWitness;\n        bytes storageTrieWitness;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Relays a cross domain message to a contract.\n     * @param _target Target contract address.\n     * @param _sender Message sender address.\n     * @param _message Message to send to the target.\n     * @param _messageNonce Nonce for the provided message.\n     * @param _proof Inclusion proof for the given message.\n     */\n    function relayMessage(\n        address _target,\n        address _sender,\n        bytes memory _message,\n        uint256 _messageNonce,\n        L2MessageInclusionProof memory _proof\n    ) external;\n\n    /**\n     * Replays a cross domain message to the target messenger.\n     * @param _target Target contract address.\n     * @param _sender Original sender address.\n     * @param _message Message to send to the target.\n     * @param _queueIndex CTC Queue index for the message to replay.\n     * @param _gasLimit Gas limit for the provided message.\n     */\n    function replayMessage(\n        address _target,\n        address _sender,\n        bytes memory _message,\n        uint256 _queueIndex,\n        uint32 _gasLimit\n    ) external;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/Initializable.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal initializer {\n        __Context_init_unchained();\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal initializer {\n        address msgSender = _msgSender();\n        _owner = msgSender;\n        emit OwnershipTransferred(address(0), msgSender);\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        _;\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        emit OwnershipTransferred(_owner, address(0));\n        _owner = address(0);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        emit OwnershipTransferred(_owner, newOwner);\n        _owner = newOwner;\n    }\n    uint256[49] private __gap;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./ContextUpgradeable.sol\";\nimport \"../proxy/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    bool private _paused;\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    function __Pausable_init() internal initializer {\n        __Context_init_unchained();\n        __Pausable_init_unchained();\n    }\n\n    function __Pausable_init_unchained() internal initializer {\n        _paused = false;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        return _paused;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        require(!paused(), \"Pausable: paused\");\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        require(paused(), \"Pausable: not paused\");\n        _;\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        _paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        _paused = false;\n        emit Unpaused(_msgSender());\n    }\n    uint256[49] private __gap;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\nimport \"../proxy/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    function __ReentrancyGuard_init() internal initializer {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal initializer {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and make it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n    uint256[49] private __gap;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\nimport \"../proxy/Initializable.sol\";\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal initializer {\n        __Context_init_unchained();\n    }\n\n    function __Context_init_unchained() internal initializer {\n    }\n    function _msgSender() internal view virtual returns (address payable) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes memory) {\n        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n        return msg.data;\n    }\n    uint256[50] private __gap;\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.4.24 <0.8.0;\n\nimport \"../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n */\nabstract contract Initializable {\n\n    /**\n     * @dev Indicates that the contract has been initialized.\n     */\n    bool private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Modifier to protect an initializer function from being invoked twice.\n     */\n    modifier initializer() {\n        require(_initializing || _isConstructor() || !_initialized, \"Initializable: contract is already initialized\");\n\n        bool isTopLevelCall = !_initializing;\n        if (isTopLevelCall) {\n            _initializing = true;\n            _initialized = true;\n        }\n\n        _;\n\n        if (isTopLevelCall) {\n            _initializing = false;\n        }\n    }\n\n    /// @dev Returns true if and only if the function is running in the constructor\n    function _isConstructor() private view returns (bool) {\n        return !AddressUpgradeable.isContract(address(this));\n    }\n}\n"
    },
    "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n        (bool success, ) = recipient.call{ value: amount }(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain`call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n      return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.call{ value: value }(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L1MultiMessageRelayer.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Interface Imports */\nimport { iOVM_L1CrossDomainMessenger } from \"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol\";\nimport { iOVM_L1MultiMessageRelayer } from \"../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol\";\n\n/* Library Imports */\nimport { Lib_AddressResolver } from \"../../../libraries/resolver/Lib_AddressResolver.sol\";\n\n/**\n * @title OVM_L1MultiMessageRelayer\n * @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the\n * relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain\n * Message Sender.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver {\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     */\n    constructor(\n        address _libAddressManager\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {}\n\n\n    /**********************\n     * Function Modifiers *\n     **********************/\n\n    modifier onlyBatchRelayer() {\n        require(\n            msg.sender == resolve(\"OVM_L2BatchMessageRelayer\"),\n            \"OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer\"\n        );\n        _;\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying\n     * @param _messages An array of L2 to L1 messages\n     */\n    function batchRelayMessages(\n        L2ToL1Message[] calldata _messages\n    ) \n        override\n        external\n        onlyBatchRelayer\n    {\n        iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger(\n            resolve(\"Proxy__OVM_L1CrossDomainMessenger\")\n        );\n\n        for (uint256 i = 0; i < _messages.length; i++) {\n            L2ToL1Message memory message = _messages[i];\n            messenger.relayMessage(\n                message.target,\n                message.sender,\n                message.message,\n                message.messageNonce,\n                message.proof\n            );\n        }\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Interface Imports */\nimport { iOVM_L1CrossDomainMessenger } from \"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol\";\ninterface iOVM_L1MultiMessageRelayer {\n\n    struct L2ToL1Message {\n        address target;\n        address sender;\n        bytes message;\n        uint256 messageNonce;\n        iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof;\n    }\n\n    function batchRelayMessages(L2ToL1Message[] calldata _messages) external;\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/bridge/messaging/OVM_L2CrossDomainMessenger.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_AddressResolver } from \"../../../libraries/resolver/Lib_AddressResolver.sol\";\nimport { Lib_CrossDomainUtils } from \"../../../libraries/bridge/Lib_CrossDomainUtils.sol\";\n\n/* Interface Imports */\nimport { iOVM_L2CrossDomainMessenger } from \"../../../iOVM/bridge/messaging/iOVM_L2CrossDomainMessenger.sol\";\nimport { iOVM_L1MessageSender } from \"../../../iOVM/predeploys/iOVM_L1MessageSender.sol\";\nimport { iOVM_L2ToL1MessagePasser } from \"../../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol\";\n\n/* External Imports */\nimport { ReentrancyGuard } from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\n/* External Imports */\nimport { ReentrancyGuard } from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\n\n/**\n * @title OVM_L2CrossDomainMessenger\n * @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point\n * for L2 messages sent via the L1 Cross Domain Messenger.\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n  */\ncontract OVM_L2CrossDomainMessenger is\n    iOVM_L2CrossDomainMessenger,\n    Lib_AddressResolver,\n    ReentrancyGuard\n{\n\n    /*************\n     * Constants *\n     *************/\n\n    // The default x-domain message sender being set to a non-zero value makes\n    // deployment a bit more expensive, but in exchange the refund on every call to\n    // `relayMessage` by the L1 and L2 messengers will be higher.\n    address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;\n\n    /*************\n     * Variables *\n     *************/\n\n    mapping (bytes32 => bool) public relayedMessages;\n    mapping (bytes32 => bool) public successfulMessages;\n    mapping (bytes32 => bool) public sentMessages;\n    uint256 public messageNonce;\n    address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Address Manager.\n     */\n    constructor(address _libAddressManager) Lib_AddressResolver(_libAddressManager) ReentrancyGuard() {}\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function xDomainMessageSender()\n        public\n        override\n        view\n        returns (\n            address\n        )\n    {\n        require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, \"xDomainMessageSender is not set\");\n        return xDomainMsgSender;\n    }\n\n    /**\n     * Sends a cross domain message to the target messenger.\n     * @param _target Target contract address.\n     * @param _message Message to send to the target.\n     * @param _gasLimit Gas limit for the provided message.\n     */\n    function sendMessage(\n        address _target,\n        bytes memory _message,\n        uint32 _gasLimit\n    )\n        override\n        public\n    {\n        bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(\n            _target,\n            msg.sender,\n            _message,\n            messageNonce\n        );\n\n        messageNonce += 1;\n        sentMessages[keccak256(xDomainCalldata)] = true;\n\n        _sendXDomainMessage(xDomainCalldata, _gasLimit);\n        emit SentMessage(xDomainCalldata);\n    }\n\n    /**\n     * Relays a cross domain message to a contract.\n     * @inheritdoc iOVM_L2CrossDomainMessenger\n     */\n    function relayMessage(\n        address _target,\n        address _sender,\n        bytes memory _message,\n        uint256 _messageNonce\n    )\n        override\n        nonReentrant\n        public\n    {\n        require(\n            _verifyXDomainMessage() == true,\n            \"Provided message could not be verified.\"\n        );\n\n        bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(\n            _target,\n            _sender,\n            _message,\n            _messageNonce\n        );\n\n        bytes32 xDomainCalldataHash = keccak256(xDomainCalldata);\n\n        require(\n            successfulMessages[xDomainCalldataHash] == false,\n            \"Provided message has already been received.\"\n        );\n\n        // Prevent calls to OVM_L2ToL1MessagePasser, which would enable\n        // an attacker to maliciously craft the _message to spoof\n        // a call from any L2 account.\n        if(_target == resolve(\"OVM_L2ToL1MessagePasser\")){\n            // Write to the successfulMessages mapping and return immediately.\n            successfulMessages[xDomainCalldataHash] = true;\n            return;\n        }\n\n        xDomainMsgSender = _sender;\n        (bool success, ) = _target.call(_message);\n        xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;\n\n        // Mark the message as received if the call was successful. Ensures that a message can be\n        // relayed multiple times in the case that the call reverted.\n        if (success == true) {\n            successfulMessages[xDomainCalldataHash] = true;\n            emit RelayedMessage(xDomainCalldataHash);\n        } else {\n            emit FailedRelayedMessage(xDomainCalldataHash);\n        }\n\n        // Store an identifier that can be used to prove that the given message was relayed by some\n        // user. Gives us an easy way to pay relayers for their work.\n        bytes32 relayId = keccak256(\n            abi.encodePacked(\n                xDomainCalldata,\n                msg.sender,\n                block.number\n            )\n        );\n\n        relayedMessages[relayId] = true;\n    }\n\n\n    /**********************\n     * Internal Functions *\n     **********************/\n\n    /**\n     * Verifies that a received cross domain message is valid.\n     * @return _valid Whether or not the message is valid.\n     */\n    function _verifyXDomainMessage()\n        view\n        internal\n        returns (\n            bool _valid\n        )\n    {\n        return (\n            iOVM_L1MessageSender(\n                resolve(\"OVM_L1MessageSender\")\n            ).getL1MessageSender() == resolve(\"OVM_L1CrossDomainMessenger\")\n        );\n    }\n\n    /**\n     * Sends a cross domain message.\n     * @param _message Message to send.\n     * param _gasLimit Gas limit for the provided message.\n     */\n    function _sendXDomainMessage(\n        bytes memory _message,\n        uint256 // _gasLimit\n    )\n        internal\n    {\n        iOVM_L2ToL1MessagePasser(resolve(\"OVM_L2ToL1MessagePasser\")).passMessageToL1(_message);\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/bridge/messaging/iOVM_L2CrossDomainMessenger.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Interface Imports */\nimport { iOVM_CrossDomainMessenger } from \"./iOVM_CrossDomainMessenger.sol\";\n\n/**\n * @title iOVM_L2CrossDomainMessenger\n */\ninterface iOVM_L2CrossDomainMessenger is iOVM_CrossDomainMessenger {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Relays a cross domain message to a contract.\n     * @param _target Target contract address.\n     * @param _sender Message sender address.\n     * @param _message Message to send to the target.\n     * @param _messageNonce Nonce for the provided message.\n     */\n    function relayMessage(\n        address _target,\n        address _sender,\n        bytes memory _message,\n        uint256 _messageNonce\n    ) external;\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/predeploys/iOVM_L1MessageSender.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title iOVM_L1MessageSender\n */\ninterface iOVM_L1MessageSender {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function getL1MessageSender() external view returns (address _l1MessageSender);\n}\n"
    },
    "contracts/optimistic-ethereum/iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/**\n * @title iOVM_L2ToL1MessagePasser\n */\ninterface iOVM_L2ToL1MessagePasser {\n\n    /**********\n     * Events *\n     **********/\n\n    event L2ToL1Message(\n        uint256 _nonce,\n        address _sender,\n        bytes _data\n    );\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    function passMessageToL1(bytes calldata _message) external;\n}\n"
    },
    "@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor () internal {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and make it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_L2ToL1MessagePasser.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Interface Imports */\nimport { iOVM_L2ToL1MessagePasser } from \"../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol\";\n\n/**\n * @title OVM_L2ToL1MessagePasser\n * @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the\n * of a message on L2. The L1 Cross Domain Messenger performs this proof in its\n * _verifyStorageProof function, which verifies the existence of the transaction hash in this\n * contract's `sentMessages` mapping.\n *\n * Compiler used: solc\n * Runtime target: EVM\n */\ncontract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser {\n\n    /**********************\n     * Contract Variables *\n     **********************/\n\n    mapping (bytes32 => bool) public sentMessages;\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Passes a message to L1.\n     * @param _message Message to pass to L1.\n     */\n    function passMessageToL1(\n        bytes memory _message\n    )\n        override\n        public\n    {\n        // Note: although this function is public, only messages sent from the OVM_L2CrossDomainMessenger\n        // will be relayed by the OVM_L1CrossDomainMessenger. This is enforced by a check in\n        // OVM_L1CrossDomainMessenger._verifyStorageProof().\n        sentMessages[keccak256(\n            abi.encodePacked(\n                _message,\n                msg.sender\n            )\n        )] = true;\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_L1MessageSender.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Interface Imports */\nimport { iOVM_L1MessageSender } from \"../../iOVM/predeploys/iOVM_L1MessageSender.sol\";\nimport { iOVM_ExecutionManager } from \"../../iOVM/execution/iOVM_ExecutionManager.sol\";\n\n/**\n * @title OVM_L1MessageSender\n * @dev The L1MessageSender is a predeploy contract running on L2. During the execution of cross\n * domain transaction from L1 to L2, it returns the address of the L1 account (either an EOA or\n * contract) which sent the message to L2 via the Canonical Transaction Chain's `enqueue()`\n * function.\n *\n * This contract exclusively serves as a getter for the ovmL1TXORIGIN operation. This is necessary\n * because there is no corresponding operation in the EVM which the the optimistic solidity compiler\n * can be replaced with a call to the ExecutionManager's ovmL1TXORIGIN() function.\n *\n *\n * Compiler used: solc\n * Runtime target: OVM\n */\ncontract OVM_L1MessageSender is iOVM_L1MessageSender {\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * @return _l1MessageSender L1 message sender address (msg.sender).\n     */\n    function getL1MessageSender()\n        override\n        public\n        view\n        returns (\n            address _l1MessageSender\n        )\n    {\n        // Note that on L2 msg.sender (ie. evmCALLER) will always be the Execution Manager\n        return iOVM_ExecutionManager(msg.sender).ovmL1TXORIGIN();\n    }\n}\n"
    },
    "contracts/test-libraries/rlp/TestLib_RLPReader.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_RLPReader } from \"../../optimistic-ethereum/libraries/rlp/Lib_RLPReader.sol\";\n\n/**\n * @title TestLib_RLPReader\n */\ncontract TestLib_RLPReader {\n\n    function readList(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            bytes[] memory\n        )\n    {\n        Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in);\n        bytes[] memory out = new bytes[](decoded.length);\n        for (uint256 i = 0; i < out.length; i++) {\n            out[i] = Lib_RLPReader.readRawBytes(decoded[i]);\n        }\n        return out;\n    }\n\n    function readString(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            string memory\n        )\n    {\n        return Lib_RLPReader.readString(_in);\n    }\n\n    function readBytes(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            bytes memory\n        )\n    {\n        return Lib_RLPReader.readBytes(_in);\n    }\n\n    function readBytes32(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return Lib_RLPReader.readBytes32(_in);\n    }\n\n    function readUint256(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            uint256\n        )\n    {\n        return Lib_RLPReader.readUint256(_in);\n    }\n\n    function readBool(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            bool\n        )\n    {\n        return Lib_RLPReader.readBool(_in);\n    }\n\n    function readAddress(\n        bytes memory _in\n    )\n        public\n        pure\n        returns (\n            address\n        )\n    {\n        return Lib_RLPReader.readAddress(_in);\n    }\n}\n"
    },
    "contracts/test-libraries/trie/TestLib_MerkleTrie.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_MerkleTrie } from \"../../optimistic-ethereum/libraries/trie/Lib_MerkleTrie.sol\";\n\n/**\n * @title TestLib_MerkleTrie\n */\ncontract TestLib_MerkleTrie {\n\n    function verifyInclusionProof(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        public\n        pure\n        returns (\n            bool\n        )\n    {\n        return Lib_MerkleTrie.verifyInclusionProof(\n            _key,\n            _value,\n            _proof,\n            _root\n        );\n    }\n\n    function update(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        public\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return Lib_MerkleTrie.update(\n            _key,\n            _value,\n            _proof,\n            _root\n        );\n    }\n\n    function get(\n        bytes memory _key,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        public\n        pure\n        returns (\n            bool,\n            bytes memory\n        )\n    {\n        return Lib_MerkleTrie.get(\n            _key,\n            _proof,\n            _root\n        );\n    }\n\n    function getSingleNodeRootHash(\n        bytes memory _key,\n        bytes memory _value\n    )\n        public\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return Lib_MerkleTrie.getSingleNodeRootHash(\n            _key,\n            _value\n        );\n    }\n}\n"
    },
    "contracts/test-libraries/trie/TestLib_SecureMerkleTrie.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_SecureMerkleTrie } from \"../../optimistic-ethereum/libraries/trie/Lib_SecureMerkleTrie.sol\";\n\n/**\n * @title TestLib_SecureMerkleTrie\n */\ncontract TestLib_SecureMerkleTrie {\n\n    function verifyInclusionProof(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        public\n        pure\n        returns (\n            bool\n        )\n    {\n        return Lib_SecureMerkleTrie.verifyInclusionProof(\n            _key,\n            _value,\n            _proof,\n            _root\n        );\n    }\n\n    function update(\n        bytes memory _key,\n        bytes memory _value,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        public\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return Lib_SecureMerkleTrie.update(\n            _key,\n            _value,\n            _proof,\n            _root\n        );\n    }\n\n    function get(\n        bytes memory _key,\n        bytes memory _proof,\n        bytes32 _root\n    )\n        public\n        pure\n        returns (\n            bool,\n            bytes memory\n        )\n    {\n        return Lib_SecureMerkleTrie.get(\n            _key,\n            _proof,\n            _root\n        );\n    }\n\n    function getSingleNodeRootHash(\n        bytes memory _key,\n        bytes memory _value\n    )\n        public\n        pure\n        returns (\n            bytes32\n        )\n    {\n        return Lib_SecureMerkleTrie.getSingleNodeRootHash(\n            _key,\n            _value\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/libraries/resolver/Lib_ResolvedDelegateProxy.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_AddressManager } from \"./Lib_AddressManager.sol\";\n\n/**\n * @title Lib_ResolvedDelegateProxy\n */\ncontract Lib_ResolvedDelegateProxy {\n\n    /*************\n     * Variables *\n     *************/\n\n    // Using mappings to store fields to avoid overwriting storage slots in the\n    // implementation contract. For example, instead of storing these fields at\n    // storage slot `0` & `1`, they are stored at `keccak256(key + slot)`.\n    // See: https://solidity.readthedocs.io/en/v0.7.0/internals/layout_in_storage.html\n    // NOTE: Do not use this code in your own contract system.\n    //      There is a known flaw in this contract, and we will remove it from the repository\n    //      in the near future. Due to the very limited way that we are using it, this flaw is\n    //      not an issue in our system.\n    mapping (address => string) private implementationName;\n    mapping (address => Lib_AddressManager) private addressManager;\n\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _libAddressManager Address of the Lib_AddressManager.\n     * @param _implementationName implementationName of the contract to proxy to.\n     */\n    constructor(\n        address _libAddressManager,\n        string memory _implementationName\n    ) {\n        addressManager[address(this)] = Lib_AddressManager(_libAddressManager);\n        implementationName[address(this)] = _implementationName;\n    }\n\n\n    /*********************\n     * Fallback Function *\n     *********************/\n\n    fallback()\n        external\n        payable\n    {\n        address target = addressManager[address(this)].getAddress(\n            (implementationName[address(this)])\n        );\n\n        require(\n            target != address(0),\n            \"Target address must be initialized.\"\n        );\n\n        (bool success, bytes memory returndata) = target.delegatecall(msg.data);\n\n        if (success == true) {\n            assembly {\n                return(add(returndata, 0x20), mload(returndata))\n            }\n        } else {\n            assembly {\n                revert(add(returndata, 0x20), mload(returndata))\n            }\n        }\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/OVM/predeploys/OVM_GasPriceOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* External Imports */\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/**\n * @title OVM_GasPriceOracle\n * @dev This contract exposes the current l2 gas price, a measure of how congested the network\n * currently is. This measure is used by the Sequencer to determine what fee to charge for\n * transactions. When the system is more congested, the l2 gas price will increase and fees\n * will also increase as a result.\n *\n * Compiler used: optimistic-solc\n * Runtime target: OVM\n */\ncontract OVM_GasPriceOracle is Ownable {\n\n    /*************\n     * Variables *\n     *************/\n\n    // Current l2 gas price\n    uint256 public gasPrice;\n\n    /***************\n     * Constructor *\n     ***************/\n\n    /**\n     * @param _owner Address that will initially own this contract.\n     */\n    constructor(\n        address _owner,\n        uint256 _initialGasPrice\n    )\n        Ownable()\n    {\n        setGasPrice(_initialGasPrice);\n        transferOwnership(_owner);\n    }\n\n\n    /********************\n     * Public Functions *\n     ********************/\n\n    /**\n     * Allows the owner to modify the l2 gas price.\n     * @param _gasPrice New l2 gas price.\n     */\n    function setGasPrice(\n        uint256 _gasPrice\n    )\n        public\n        onlyOwner\n    {\n        gasPrice = _gasPrice;\n    }\n}\n"
    },
    "contracts/test-libraries/utils/TestLib_Bytes32Utils.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Library Imports */\nimport { Lib_Bytes32Utils } from \"../../optimistic-ethereum/libraries/utils/Lib_Bytes32Utils.sol\";\n\n/**\n * @title TestLib_Byte32Utils\n */\ncontract TestLib_Bytes32Utils {\n\n    function toBool(\n        bytes32 _in\n    )\n        public\n        pure\n        returns (\n            bool _out\n        )\n    {\n        return Lib_Bytes32Utils.toBool(_in);\n    }\n\n    function fromBool(\n        bool _in\n    )\n        public\n        pure\n        returns (\n            bytes32 _out\n        )\n    {\n        return Lib_Bytes32Utils.fromBool(_in);\n    }\n\n    function toAddress(\n        bytes32 _in\n    )\n        public\n        pure\n        returns (\n            address _out\n        )\n    {\n        return Lib_Bytes32Utils.toAddress(_in);\n    }\n\n    function fromAddress(\n        address _in\n    )\n        public\n        pure\n        returns (\n            bytes32 _out\n        )\n    {\n        return Lib_Bytes32Utils.fromAddress(_in);\n    }\n}\n"
    },
    "contracts/test-libraries/utils/TestLib_EthUtils.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// @unsupported: ovm\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_EthUtils } from \"../../optimistic-ethereum/libraries/utils/Lib_EthUtils.sol\";\n\n/**\n * @title TestLib_EthUtils\n */\ncontract TestLib_EthUtils {\n\n    function getCode(\n        address _address,\n        uint256 _offset,\n        uint256 _length\n    )\n        public\n        view\n        returns (\n            bytes memory _code\n        )\n    {\n        return Lib_EthUtils.getCode(\n            _address,\n            _offset,\n            _length\n        );\n    }\n\n    function getCode(\n        address _address\n    )\n        public\n        view\n        returns (\n            bytes memory _code\n        )\n    {\n        return Lib_EthUtils.getCode(\n            _address\n        );\n    }\n\n    function getCodeSize(\n        address _address\n    )\n        public\n        view\n        returns (\n            uint256 _codeSize\n        )\n    {\n        return Lib_EthUtils.getCodeSize(\n            _address\n        );\n    }\n\n    function getCodeHash(\n        address _address\n    )\n        public\n        view\n        returns (\n            bytes32 _codeHash\n        )\n    {\n        return Lib_EthUtils.getCodeHash(\n            _address\n        );\n    }\n\n    function createContract(\n        bytes memory _code\n    )\n        public\n        returns (\n            address _created\n        )\n    {\n        return Lib_EthUtils.createContract(\n            _code\n        );\n    }\n\n    function getAddressForCREATE(\n        address _creator,\n        uint256 _nonce\n    )\n        public\n        pure\n        returns (\n            address _address\n        )\n    {\n        return Lib_EthUtils.getAddressForCREATE(\n            _creator,\n            _nonce\n        );\n    }\n\n    function getAddressForCREATE2(\n        address _creator,\n        bytes memory _bytecode,\n        bytes32 _salt\n    )\n        public\n        pure\n        returns (address _address)\n    {\n        return Lib_EthUtils.getAddressForCREATE2(\n            _creator,\n            _bytecode,\n            _salt\n        );\n    }\n}\n"
    },
    "contracts/test-libraries/utils/TestLib_MerkleTree.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\npragma experimental ABIEncoderV2;\n\n/* Library Imports */\nimport { Lib_MerkleTree } from \"../../optimistic-ethereum/libraries/utils/Lib_MerkleTree.sol\";\n\n/**\n * @title TestLib_MerkleTree\n */\ncontract TestLib_MerkleTree {\n\n    function getMerkleRoot(\n        bytes32[] memory _elements\n    )\n        public\n       pure\n        returns (\n            bytes32\n        )\n    {\n        return Lib_MerkleTree.getMerkleRoot(\n            _elements\n        );\n    }\n\n    function verify(\n        bytes32 _root,\n        bytes32 _leaf,\n        uint256 _index,\n        bytes32[] memory _siblings,\n        uint256 _totalLeaves\n    )\n        public\n        pure\n        returns (\n            bool\n        )\n    {\n        return Lib_MerkleTree.verify(\n            _root,\n            _leaf,\n            _index,\n            _siblings,\n            _totalLeaves\n        );\n    }\n}\n"
    },
    "contracts/optimistic-ethereum/mockOVM/verification/mockOVM_BondManager.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity >0.5.0 <0.8.0;\n\n/* Interface Imports */\nimport { iOVM_BondManager } from \"../../iOVM/verification/iOVM_BondManager.sol\";\n\n/* Contract Imports */\nimport { Lib_AddressResolver } from \"../../libraries/resolver/Lib_AddressResolver.sol\";\n\n/**\n * @title mockOVM_BondManager\n */\ncontract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver {\n    constructor(\n        address _libAddressManager\n    )\n        Lib_AddressResolver(_libAddressManager)\n    {}\n\n    function recordGasSpent(\n        bytes32 _preStateRoot,\n        bytes32 _txHash,\n        address _who,\n        uint256 _gasSpent\n    )\n        override\n        public\n    {}\n\n    function finalize(\n        bytes32 _preStateRoot,\n        address _publisher,\n        uint256 _timestamp\n    )\n        override\n        public\n    {}\n\n    function deposit()\n        override\n        public\n    {}\n\n    function startWithdrawal()\n        override\n        public\n    {}\n\n    function finalizeWithdrawal()\n        override\n        public\n    {}\n\n    function claim(\n        address _who\n    )\n        override\n        public\n    {}\n\n    function isCollateralized(\n        address _who\n    )\n        override\n        public\n        view\n        returns (\n            bool\n        )\n    {\n        // Only authenticate sequencer to submit state root batches.\n        return _who == resolve(\"OVM_Proposer\");\n    }\n\n    function getGasSpent(\n        bytes32, // _preStateRoot,\n        address // _who\n    )\n        override\n        public\n        pure\n        returns (\n            uint256\n        )\n    {\n        return 0;\n    }\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "outputSelection": {
      "*": {
        "*": [
          "storageLayout",
          "abi",
          "evm.bytecode",
          "evm.deployedBytecode",
          "evm.methodIdentifiers",
          "metadata",
          "devdoc",
          "userdoc",
          "evm.gasEstimates"
        ],
        "": [
          "ast"
        ]
      }
    },
    "metadata": {
      "useLiteralContent": true
    }
  }
}