creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^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 proxied contracts do not make use of 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 {ERC1967Proxy-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 *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the\n * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() initializer {}\n * ```\n * ====\n */\nabstract contract Initializable {\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        // If the contract is initializing we ignore whether _initialized is set in order to support multiple\n        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the\n        // contract may have been reentered.\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    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} modifier, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    function _isConstructor() private view returns (bool) {\n        return !AddressUpgradeable.isContract(address(this));\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/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 onlyInitializing {\n        __Pausable_init_unchained();\n    }\n\n    function __Pausable_init_unchained() internal onlyInitializing {\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\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\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 `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, 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 `from` to `to` 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(\n        address from,\n        address to,\n        uint256 amount\n    ) 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-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\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     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 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        (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(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) 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(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) 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(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) 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        (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(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal 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                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"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/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 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 onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts/interfaces/draft-IERC1822.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n    /**\n     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n     * address.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy.\n     */\n    function proxiableUUID() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {BeaconProxy} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"
      },
      "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n    // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n     * validated in the constructor.\n     */\n    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function _getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Perform implementation upgrade\n     *\n     * Emits an {Upgraded} event.\n     */\n    function _upgradeTo(address newImplementation) internal {\n        _setImplementation(newImplementation);\n        emit Upgraded(newImplementation);\n    }\n\n    /**\n     * @dev Perform implementation upgrade with additional setup call.\n     *\n     * Emits an {Upgraded} event.\n     */\n    function _upgradeToAndCall(\n        address newImplementation,\n        bytes memory data,\n        bool forceCall\n    ) internal {\n        _upgradeTo(newImplementation);\n        if (data.length > 0 || forceCall) {\n            Address.functionDelegateCall(newImplementation, data);\n        }\n    }\n\n    /**\n     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n     *\n     * Emits an {Upgraded} event.\n     */\n    function _upgradeToAndCallUUPS(\n        address newImplementation,\n        bytes memory data,\n        bool forceCall\n    ) internal {\n        // Upgrades from old implementations will perform a rollback test. This test requires the new\n        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n        // this special case will break upgrade paths from old UUPS implementation to new ones.\n        if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n            _setImplementation(newImplementation);\n        } else {\n            try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n                require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n            } catch {\n                revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n            }\n            _upgradeToAndCall(newImplementation, data, forceCall);\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n     * validated in the constructor.\n     */\n    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Returns the current admin.\n     */\n    function _getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {AdminChanged} event.\n     */\n    function _changeAdmin(address newAdmin) internal {\n        emit AdminChanged(_getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n     */\n    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Emitted when the beacon is upgraded.\n     */\n    event BeaconUpgraded(address indexed beacon);\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function _getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the EIP1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n        require(\n            Address.isContract(IBeacon(newBeacon).implementation()),\n            \"ERC1967: beacon implementation is not a contract\"\n        );\n        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n    }\n\n    /**\n     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n     *\n     * Emits a {BeaconUpgraded} event.\n     */\n    function _upgradeBeaconToAndCall(\n        address newBeacon,\n        bytes memory data,\n        bool forceCall\n    ) internal {\n        _setBeacon(newBeacon);\n        emit BeaconUpgraded(newBeacon);\n        if (data.length > 0 || forceCall) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/proxy/Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n    /**\n     * @dev Delegates the current call to `implementation`.\n     *\n     * This function does not return to its internal call site, it will return directly to the external caller.\n     */\n    function _delegate(address implementation) internal virtual {\n        assembly {\n            // Copy msg.data. We take full control of memory in this inline assembly\n            // block because it will not return to Solidity code. We overwrite the\n            // Solidity scratch pad at memory position 0.\n            calldatacopy(0, 0, calldatasize())\n\n            // Call the implementation.\n            // out and outsize are 0 because we don't know the size yet.\n            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n            // Copy the returned data.\n            returndatacopy(0, 0, returndatasize())\n\n            switch result\n            // delegatecall returns 0 on error.\n            case 0 {\n                revert(0, returndatasize())\n            }\n            default {\n                return(0, returndatasize())\n            }\n        }\n    }\n\n    /**\n     * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function\n     * and {_fallback} should delegate.\n     */\n    function _implementation() internal view virtual returns (address);\n\n    /**\n     * @dev Delegates the current call to the address returned by `_implementation()`.\n     *\n     * This function does not return to its internall call site, it will return directly to the external caller.\n     */\n    function _fallback() internal virtual {\n        _beforeFallback();\n        _delegate(_implementation());\n    }\n\n    /**\n     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n     * function in the contract matches the call data.\n     */\n    fallback() external payable virtual {\n        _fallback();\n    }\n\n    /**\n     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n     * is empty.\n     */\n    receive() external payable virtual {\n        _fallback();\n    }\n\n    /**\n     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n     * call, or as part of the Solidity `fallback` or `receive` functions.\n     *\n     * If overriden should call `super._beforeFallback()`.\n     */\n    function _beforeFallback() internal virtual {}\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\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     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 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        (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(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) 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(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) 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(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) 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        (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(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\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(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal 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                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"
      },
      "@openzeppelin/contracts/utils/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly {\n            r.slot := slot\n        }\n    }\n}\n"
      },
      "src/bridge/IBridge.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.6.9 <0.9.0;\n\nimport \"./IOwnable.sol\";\n\ninterface IBridge {\n    /// @dev This is an instruction to offchain readers to inform them where to look\n    ///      for sequencer inbox batch data. This is not the type of data (eg. das, brotli encoded, or blob versioned hash)\n    ///      and this enum is not used in the state transition function, rather it informs an offchain\n    ///      reader where to find the data so that they can supply it to the replay binary\n    enum BatchDataLocation {\n        /// @notice The data can be found in the transaction call data\n        TxInput,\n        /// @notice The data can be found in an event emitted during the transaction\n        SeparateBatchEvent,\n        /// @notice This batch contains no data\n        NoData,\n        /// @notice The data can be found in the 4844 data blobs on this transaction\n        Blob\n    }\n\n    struct TimeBounds {\n        uint64 minTimestamp;\n        uint64 maxTimestamp;\n        uint64 minBlockNumber;\n        uint64 maxBlockNumber;\n    }\n\n    event MessageDelivered(\n        uint256 indexed messageIndex,\n        bytes32 indexed beforeInboxAcc,\n        address inbox,\n        uint8 kind,\n        address sender,\n        bytes32 messageDataHash,\n        uint256 baseFeeL1,\n        uint64 timestamp\n    );\n\n    event DepositMessageDelivered(address indexed sender);\n\n    event BridgeCallTriggered(\n        address indexed outbox,\n        address indexed to,\n        uint256 value,\n        bytes data\n    );\n\n    event InboxToggle(address indexed inbox, bool enabled);\n\n    event OutboxToggle(address indexed outbox, bool enabled);\n\n    event SequencerInboxUpdated(address newSequencerInbox);\n\n    event RollupUpdated(address rollup);\n\n    function allowedDelayedInboxList(uint256) external returns (address);\n\n    function allowedOutboxList(uint256) external returns (address);\n\n    /// @dev Accumulator for delayed inbox messages; tail represents hash of the current state; each element represents the inclusion of a new message.\n    function delayedInboxAccs(uint256) external view returns (bytes32);\n\n    /// @dev Accumulator for sequencer inbox messages; tail represents hash of the current state; each element represents the inclusion of a new message.\n    function sequencerInboxAccs(uint256) external view returns (bytes32);\n\n    function rollup() external view returns (IOwnable);\n\n    function sequencerInbox() external view returns (address);\n\n    function activeOutbox() external view returns (address);\n\n    function allowedDelayedInboxes(address inbox) external view returns (bool);\n\n    function allowedOutboxes(address outbox) external view returns (bool);\n\n    function sequencerReportedSubMessageCount() external view returns (uint256);\n\n    function executeCall(\n        address to,\n        uint256 value,\n        bytes calldata data\n    ) external returns (bool success, bytes memory returnData);\n\n    function delayedMessageCount() external view returns (uint256);\n\n    function sequencerMessageCount() external view returns (uint256);\n\n    // ---------- onlySequencerInbox functions ----------\n\n    function enqueueSequencerMessage(\n        bytes32 dataHash,\n        uint256 afterDelayedMessagesRead,\n        uint256 prevMessageCount,\n        uint256 newMessageCount\n    )\n        external\n        returns (\n            uint256 seqMessageIndex,\n            bytes32 beforeAcc,\n            bytes32 delayedAcc,\n            bytes32 acc\n        );\n\n    /**\n     * @dev Allows the sequencer inbox to submit a delayed message of the batchPostingReport type\n     *      This is done through a separate function entrypoint instead of allowing the sequencer inbox\n     *      to call `enqueueDelayedMessage` to avoid the gas overhead of an extra SLOAD in either\n     *      every delayed inbox or every sequencer inbox call.\n     */\n    function submitBatchSpendingReport(address batchPoster, bytes32 dataHash)\n        external\n        returns (uint256 msgNum);\n\n    // ---------- onlyRollupOrOwner functions ----------\n\n    function setSequencerInbox(address _sequencerInbox) external;\n\n    function setDelayedInbox(address inbox, bool enabled) external;\n\n    function setOutbox(address inbox, bool enabled) external;\n\n    function updateRollupAddress(IOwnable _rollup) external;\n}\n"
      },
      "src/bridge/IDelayedMessageProvider.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.6.9 <0.9.0;\n\ninterface IDelayedMessageProvider {\n    /// @dev event emitted when a inbox message is added to the Bridge's delayed accumulator\n    event InboxMessageDelivered(uint256 indexed messageNum, bytes data);\n\n    /// @dev event emitted when a inbox message is added to the Bridge's delayed accumulator\n    /// same as InboxMessageDelivered but the batch data is available in tx.input\n    event InboxMessageDeliveredFromOrigin(uint256 indexed messageNum);\n}\n"
      },
      "src/bridge/IInboxBase.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.6.9 <0.9.0;\n\nimport \"./IBridge.sol\";\nimport \"./IDelayedMessageProvider.sol\";\nimport \"./ISequencerInbox.sol\";\n\ninterface IInboxBase is IDelayedMessageProvider {\n    function bridge() external view returns (IBridge);\n\n    function sequencerInbox() external view returns (ISequencerInbox);\n\n    function maxDataSize() external view returns (uint256);\n\n    /**\n     * @notice Send a generic L2 message to the chain\n     * @dev This method is an optimization to avoid having to emit the entirety of the messageData in a log. Instead validators are expected to be able to parse the data from the transaction's input\n     * @param messageData Data of the message being sent\n     */\n    function sendL2MessageFromOrigin(bytes calldata messageData) external returns (uint256);\n\n    /**\n     * @notice Send a generic L2 message to the chain\n     * @dev This method can be used to send any type of message that doesn't require L1 validation\n     * @param messageData Data of the message being sent\n     */\n    function sendL2Message(bytes calldata messageData) external returns (uint256);\n\n    function sendUnsignedTransaction(\n        uint256 gasLimit,\n        uint256 maxFeePerGas,\n        uint256 nonce,\n        address to,\n        uint256 value,\n        bytes calldata data\n    ) external returns (uint256);\n\n    function sendContractTransaction(\n        uint256 gasLimit,\n        uint256 maxFeePerGas,\n        address to,\n        uint256 value,\n        bytes calldata data\n    ) external returns (uint256);\n\n    /**\n     * @notice Get the L1 fee for submitting a retryable\n     * @dev This fee can be paid by funds already in the L2 aliased address or by the current message value\n     * @dev This formula may change in the future, to future proof your code query this method instead of inlining!!\n     * @param dataLength The length of the retryable's calldata, in bytes\n     * @param baseFee The block basefee when the retryable is included in the chain, if 0 current block.basefee will be used\n     */\n    function calculateRetryableSubmissionFee(uint256 dataLength, uint256 baseFee)\n        external\n        view\n        returns (uint256);\n\n    // ---------- onlyRollupOrOwner functions ----------\n\n    /// @notice pauses all inbox functionality\n    function pause() external;\n\n    /// @notice unpauses all inbox functionality\n    function unpause() external;\n\n    /// @notice add or remove users from allowList\n    function setAllowList(address[] memory user, bool[] memory val) external;\n\n    /// @notice enable or disable allowList\n    function setAllowListEnabled(bool _allowListEnabled) external;\n\n    /// @notice check if user is in allowList\n    function isAllowed(address user) external view returns (bool);\n\n    /// @notice check if allowList is enabled\n    function allowListEnabled() external view returns (bool);\n\n    function initialize(IBridge _bridge, ISequencerInbox _sequencerInbox) external;\n\n    /// @notice returns the current admin\n    function getProxyAdmin() external view returns (address);\n}\n"
      },
      "src/bridge/IOutbox.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.6.9 <0.9.0;\n\nimport \"./IBridge.sol\";\n\ninterface IOutbox {\n    event SendRootUpdated(bytes32 indexed outputRoot, bytes32 indexed l2BlockHash);\n    event OutBoxTransactionExecuted(\n        address indexed to,\n        address indexed l2Sender,\n        uint256 indexed zero,\n        uint256 transactionIndex\n    );\n\n    function initialize(IBridge _bridge) external;\n\n    function rollup() external view returns (address); // the rollup contract\n\n    function bridge() external view returns (IBridge); // the bridge contract\n\n    function spent(uint256) external view returns (bytes32); // packed spent bitmap\n\n    function roots(bytes32) external view returns (bytes32); // maps root hashes => L2 block hash\n\n    // solhint-disable-next-line func-name-mixedcase\n    function OUTBOX_VERSION() external view returns (uint128); // the outbox version\n\n    function updateSendRoot(bytes32 sendRoot, bytes32 l2BlockHash) external;\n\n    function updateRollupAddress() external;\n\n    /// @notice When l2ToL1Sender returns a nonzero address, the message was originated by an L2 account\n    ///         When the return value is zero, that means this is a system message\n    /// @dev the l2ToL1Sender behaves as the tx.origin, the msg.sender should be validated to protect against reentrancies\n    function l2ToL1Sender() external view returns (address);\n\n    /// @return l2Block return L2 block when the L2 tx was initiated or 0 if no L2 to L1 transaction is active\n    function l2ToL1Block() external view returns (uint256);\n\n    /// @return l1Block return L1 block when the L2 tx was initiated or 0 if no L2 to L1 transaction is active\n    function l2ToL1EthBlock() external view returns (uint256);\n\n    /// @return timestamp return L2 timestamp when the L2 tx was initiated or 0 if no L2 to L1 transaction is active\n    function l2ToL1Timestamp() external view returns (uint256);\n\n    /// @return outputId returns the unique output identifier of the L2 to L1 tx or 0 if no L2 to L1 transaction is active\n    function l2ToL1OutputId() external view returns (bytes32);\n\n    /**\n     * @notice Executes a messages in an Outbox entry.\n     * @dev Reverts if dispute period hasn't expired, since the outbox entry\n     *      is only created once the rollup confirms the respective assertion.\n     * @dev it is not possible to execute any L2-to-L1 transaction which contains data\n     *      to a contract address without any code (as enforced by the Bridge contract).\n     * @param proof Merkle proof of message inclusion in send root\n     * @param index Merkle path to message\n     * @param l2Sender sender if original message (i.e., caller of ArbSys.sendTxToL1)\n     * @param to destination address for L1 contract call\n     * @param l2Block l2 block number at which sendTxToL1 call was made\n     * @param l1Block l1 block number at which sendTxToL1 call was made\n     * @param l2Timestamp l2 Timestamp at which sendTxToL1 call was made\n     * @param value wei in L1 message\n     * @param data abi-encoded L1 message data\n     */\n    function executeTransaction(\n        bytes32[] calldata proof,\n        uint256 index,\n        address l2Sender,\n        address to,\n        uint256 l2Block,\n        uint256 l1Block,\n        uint256 l2Timestamp,\n        uint256 value,\n        bytes calldata data\n    ) external;\n\n    /**\n     *  @dev function used to simulate the result of a particular function call from the outbox\n     *       it is useful for things such as gas estimates. This function includes all costs except for\n     *       proof validation (which can be considered offchain as a somewhat of a fixed cost - it's\n     *       not really a fixed cost, but can be treated as so with a fixed overhead for gas estimation).\n     *       We can't include the cost of proof validation since this is intended to be used to simulate txs\n     *       that are included in yet-to-be confirmed merkle roots. The simulation entrypoint could instead pretend\n     *       to confirm a pending merkle root, but that would be less practical for integrating with tooling.\n     *       It is only possible to trigger it when the msg sender is address zero, which should be impossible\n     *       unless under simulation in an eth_call or eth_estimateGas\n     */\n    function executeTransactionSimulation(\n        uint256 index,\n        address l2Sender,\n        address to,\n        uint256 l2Block,\n        uint256 l1Block,\n        uint256 l2Timestamp,\n        uint256 value,\n        bytes calldata data\n    ) external;\n\n    /**\n     * @param index Merkle path to message\n     * @return true if the message has been spent\n     */\n    function isSpent(uint256 index) external view returns (bool);\n\n    function calculateItemHash(\n        address l2Sender,\n        address to,\n        uint256 l2Block,\n        uint256 l1Block,\n        uint256 l2Timestamp,\n        uint256 value,\n        bytes calldata data\n    ) external pure returns (bytes32);\n\n    function calculateMerkleRoot(\n        bytes32[] memory proof,\n        uint256 path,\n        bytes32 item\n    ) external pure returns (bytes32);\n\n    /**\n     * @dev function to be called one time during the outbox upgrade process\n     *      this is used to fix the storage slots\n     */\n    function postUpgradeInit() external;\n}\n"
      },
      "src/bridge/IOwnable.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.4.21 <0.9.0;\n\ninterface IOwnable {\n    function owner() external view returns (address);\n}\n"
      },
      "src/bridge/ISequencerInbox.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.6.9 <0.9.0;\npragma experimental ABIEncoderV2;\n\nimport \"../libraries/IGasRefunder.sol\";\nimport \"./IDelayedMessageProvider.sol\";\nimport \"./IBridge.sol\";\n\ninterface ISequencerInbox is IDelayedMessageProvider {\n    struct MaxTimeVariation {\n        uint256 delayBlocks;\n        uint256 futureBlocks;\n        uint256 delaySeconds;\n        uint256 futureSeconds;\n    }\n\n    event SequencerBatchDelivered(\n        uint256 indexed batchSequenceNumber,\n        bytes32 indexed beforeAcc,\n        bytes32 indexed afterAcc,\n        bytes32 delayedAcc,\n        uint256 afterDelayedMessagesRead,\n        IBridge.TimeBounds timeBounds,\n        IBridge.BatchDataLocation dataLocation\n    );\n\n    event OwnerFunctionCalled(uint256 indexed id);\n\n    /// @dev a separate event that emits batch data when this isn't easily accessible in the tx.input\n    event SequencerBatchData(uint256 indexed batchSequenceNumber, bytes data);\n\n    /// @dev a valid keyset was added\n    event SetValidKeyset(bytes32 indexed keysetHash, bytes keysetBytes);\n\n    /// @dev a keyset was invalidated\n    event InvalidateKeyset(bytes32 indexed keysetHash);\n\n    function totalDelayedMessagesRead() external view returns (uint256);\n\n    function bridge() external view returns (IBridge);\n\n    /// @dev The size of the batch header\n    // solhint-disable-next-line func-name-mixedcase\n    function HEADER_LENGTH() external view returns (uint256);\n\n    /// @dev If the first batch data byte after the header has this bit set,\n    ///      the sequencer inbox has authenticated the data. Currently only used for 4844 blob support.\n    ///      See: https://github.com/OffchainLabs/nitro/blob/69de0603abf6f900a4128cab7933df60cad54ded/arbstate/das_reader.go\n    // solhint-disable-next-line func-name-mixedcase\n    function DATA_AUTHENTICATED_FLAG() external view returns (bytes1);\n\n    /// @dev If the first data byte after the header has this bit set,\n    ///      then the batch data is to be found in 4844 data blobs\n    ///      See: https://github.com/OffchainLabs/nitro/blob/69de0603abf6f900a4128cab7933df60cad54ded/arbstate/das_reader.go\n    // solhint-disable-next-line func-name-mixedcase\n    function DATA_BLOB_HEADER_FLAG() external view returns (bytes1);\n\n    /// @dev If the first data byte after the header has this bit set,\n    ///      then the batch data is a das message\n    ///      See: https://github.com/OffchainLabs/nitro/blob/69de0603abf6f900a4128cab7933df60cad54ded/arbstate/das_reader.go\n    // solhint-disable-next-line func-name-mixedcase\n    function DAS_MESSAGE_HEADER_FLAG() external view returns (bytes1);\n\n    /// @dev If the first data byte after the header has this bit set,\n    ///      then the batch data is a das message that employs a merklesization strategy\n    ///      See: https://github.com/OffchainLabs/nitro/blob/69de0603abf6f900a4128cab7933df60cad54ded/arbstate/das_reader.go\n    // solhint-disable-next-line func-name-mixedcase\n    function TREE_DAS_MESSAGE_HEADER_FLAG() external view returns (bytes1);\n\n    /// @dev If the first data byte after the header has this bit set,\n    ///      then the batch data has been brotli compressed\n    ///      See: https://github.com/OffchainLabs/nitro/blob/69de0603abf6f900a4128cab7933df60cad54ded/arbstate/das_reader.go\n    // solhint-disable-next-line func-name-mixedcase\n    function BROTLI_MESSAGE_HEADER_FLAG() external view returns (bytes1);\n\n    /// @dev If the first data byte after the header has this bit set,\n    ///      then the batch data uses a zero heavy encoding\n    ///      See: https://github.com/OffchainLabs/nitro/blob/69de0603abf6f900a4128cab7933df60cad54ded/arbstate/das_reader.go\n    // solhint-disable-next-line func-name-mixedcase\n    function ZERO_HEAVY_MESSAGE_HEADER_FLAG() external view returns (bytes1);\n\n    function rollup() external view returns (IOwnable);\n\n    function isBatchPoster(address) external view returns (bool);\n\n    function isSequencer(address) external view returns (bool);\n\n    function maxDataSize() external view returns (uint256);\n\n    /// @notice The batch poster manager has the ability to change the batch poster addresses\n    ///         This enables the batch poster to do key rotation\n    function batchPosterManager() external view returns (address);\n\n    struct DasKeySetInfo {\n        bool isValidKeyset;\n        uint64 creationBlock;\n    }\n\n    /// @dev returns 4 uint256 to be compatible with older version\n    function maxTimeVariation()\n        external\n        view\n        returns (\n            uint256 delayBlocks,\n            uint256 futureBlocks,\n            uint256 delaySeconds,\n            uint256 futureSeconds\n        );\n\n    function dasKeySetInfo(bytes32) external view returns (bool, uint64);\n\n    /// @notice Remove force inclusion delay after a L1 chainId fork\n    function removeDelayAfterFork() external;\n\n    /// @notice Force messages from the delayed inbox to be included in the chain\n    ///         Callable by any address, but message can only be force-included after maxTimeVariation.delayBlocks and\n    ///         maxTimeVariation.delaySeconds has elapsed. As part of normal behaviour the sequencer will include these\n    ///         messages so it's only necessary to call this if the sequencer is down, or not including any delayed messages.\n    /// @param _totalDelayedMessagesRead The total number of messages to read up to\n    /// @param kind The kind of the last message to be included\n    /// @param l1BlockAndTime The l1 block and the l1 timestamp of the last message to be included\n    /// @param baseFeeL1 The l1 gas price of the last message to be included\n    /// @param sender The sender of the last message to be included\n    /// @param messageDataHash The messageDataHash of the last message to be included\n    function forceInclusion(\n        uint256 _totalDelayedMessagesRead,\n        uint8 kind,\n        uint64[2] calldata l1BlockAndTime,\n        uint256 baseFeeL1,\n        address sender,\n        bytes32 messageDataHash\n    ) external;\n\n    function inboxAccs(uint256 index) external view returns (bytes32);\n\n    function batchCount() external view returns (uint256);\n\n    function isValidKeysetHash(bytes32 ksHash) external view returns (bool);\n\n    /// @notice the creation block is intended to still be available after a keyset is deleted\n    function getKeysetCreationBlock(bytes32 ksHash) external view returns (uint256);\n\n    // ---------- BatchPoster functions ----------\n\n    function addSequencerL2BatchFromOrigin(\n        uint256 sequenceNumber,\n        bytes calldata data,\n        uint256 afterDelayedMessagesRead,\n        IGasRefunder gasRefunder\n    ) external;\n\n    function addSequencerL2BatchFromOrigin(\n        uint256 sequenceNumber,\n        bytes calldata data,\n        uint256 afterDelayedMessagesRead,\n        IGasRefunder gasRefunder,\n        uint256 prevMessageCount,\n        uint256 newMessageCount\n    ) external;\n\n    function addSequencerL2Batch(\n        uint256 sequenceNumber,\n        bytes calldata data,\n        uint256 afterDelayedMessagesRead,\n        IGasRefunder gasRefunder,\n        uint256 prevMessageCount,\n        uint256 newMessageCount\n    ) external;\n\n    function addSequencerL2BatchFromBlobs(\n        uint256 sequenceNumber,\n        uint256 afterDelayedMessagesRead,\n        IGasRefunder gasRefunder,\n        uint256 prevMessageCount,\n        uint256 newMessageCount\n    ) external;\n\n    // ---------- onlyRollupOrOwner functions ----------\n\n    /**\n     * @notice Set max delay for sequencer inbox\n     * @param maxTimeVariation_ the maximum time variation parameters\n     */\n    function setMaxTimeVariation(MaxTimeVariation memory maxTimeVariation_) external;\n\n    /**\n     * @notice Updates whether an address is authorized to be a batch poster at the sequencer inbox\n     * @param addr the address\n     * @param isBatchPoster_ if the specified address should be authorized as a batch poster\n     */\n    function setIsBatchPoster(address addr, bool isBatchPoster_) external;\n\n    /**\n     * @notice Makes Data Availability Service keyset valid\n     * @param keysetBytes bytes of the serialized keyset\n     */\n    function setValidKeyset(bytes calldata keysetBytes) external;\n\n    /**\n     * @notice Invalidates a Data Availability Service keyset\n     * @param ksHash hash of the keyset\n     */\n    function invalidateKeysetHash(bytes32 ksHash) external;\n\n    /**\n     * @notice Updates whether an address is authorized to be a sequencer.\n     * @dev The IsSequencer information is used only off-chain by the nitro node to validate sequencer feed signer.\n     * @param addr the address\n     * @param isSequencer_ if the specified address should be authorized as a sequencer\n     */\n    function setIsSequencer(address addr, bool isSequencer_) external;\n\n    /**\n     * @notice Updates the batch poster manager, the address which has the ability to rotate batch poster keys\n     * @param newBatchPosterManager The new batch poster manager to be set\n     */\n    function setBatchPosterManager(address newBatchPosterManager) external;\n\n    /// @notice Allows the rollup owner to sync the rollup address\n    function updateRollupAddress() external;\n\n    // ---------- initializer ----------\n\n    function initialize(IBridge bridge_, MaxTimeVariation calldata maxTimeVariation_) external;\n}\n"
      },
      "src/challenge/ChallengeLib.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"../state/Machine.sol\";\nimport \"../state/GlobalState.sol\";\n\nlibrary ChallengeLib {\n    using MachineLib for Machine;\n    using ChallengeLib for Challenge;\n\n    /// @dev It's assumed that that uninitialzed challenges have mode NONE\n    enum ChallengeMode {\n        NONE,\n        BLOCK,\n        EXECUTION\n    }\n\n    struct Participant {\n        address addr;\n        uint256 timeLeft;\n    }\n\n    struct Challenge {\n        Participant current;\n        Participant next;\n        uint256 lastMoveTimestamp;\n        bytes32 wasmModuleRoot;\n        bytes32 challengeStateHash;\n        uint64 maxInboxMessages;\n        ChallengeMode mode;\n    }\n\n    struct SegmentSelection {\n        uint256 oldSegmentsStart;\n        uint256 oldSegmentsLength;\n        bytes32[] oldSegments;\n        uint256 challengePosition;\n    }\n\n    function timeUsedSinceLastMove(Challenge storage challenge) internal view returns (uint256) {\n        return block.timestamp - challenge.lastMoveTimestamp;\n    }\n\n    function isTimedOut(Challenge storage challenge) internal view returns (bool) {\n        return challenge.timeUsedSinceLastMove() > challenge.current.timeLeft;\n    }\n\n    function getStartMachineHash(bytes32 globalStateHash, bytes32 wasmModuleRoot)\n        internal\n        pure\n        returns (bytes32)\n    {\n        // Start the value stack with the function call ABI for the entrypoint\n        Value[] memory startingValues = new Value[](3);\n        startingValues[0] = ValueLib.newRefNull();\n        startingValues[1] = ValueLib.newI32(0);\n        startingValues[2] = ValueLib.newI32(0);\n        ValueArray memory valuesArray = ValueArray({inner: startingValues});\n        ValueStack memory values = ValueStack({proved: valuesArray, remainingHash: 0});\n        ValueStack memory internalStack;\n        StackFrameWindow memory frameStack;\n\n        Machine memory mach = Machine({\n            status: MachineStatus.RUNNING,\n            valueStack: values,\n            internalStack: internalStack,\n            frameStack: frameStack,\n            globalStateHash: globalStateHash,\n            moduleIdx: 0,\n            functionIdx: 0,\n            functionPc: 0,\n            modulesRoot: wasmModuleRoot\n        });\n        return mach.hash();\n    }\n\n    function getEndMachineHash(MachineStatus status, bytes32 globalStateHash)\n        internal\n        pure\n        returns (bytes32)\n    {\n        if (status == MachineStatus.FINISHED) {\n            return keccak256(abi.encodePacked(\"Machine finished:\", globalStateHash));\n        } else if (status == MachineStatus.ERRORED) {\n            return keccak256(abi.encodePacked(\"Machine errored:\"));\n        } else if (status == MachineStatus.TOO_FAR) {\n            return keccak256(abi.encodePacked(\"Machine too far:\"));\n        } else {\n            revert(\"BAD_BLOCK_STATUS\");\n        }\n    }\n\n    function extractChallengeSegment(SegmentSelection calldata selection)\n        internal\n        pure\n        returns (uint256 segmentStart, uint256 segmentLength)\n    {\n        uint256 oldChallengeDegree = selection.oldSegments.length - 1;\n        segmentLength = selection.oldSegmentsLength / oldChallengeDegree;\n        // Intentionally done before challengeLength is potentially added to for the final segment\n        segmentStart = selection.oldSegmentsStart + segmentLength * selection.challengePosition;\n        if (selection.challengePosition == selection.oldSegments.length - 2) {\n            segmentLength += selection.oldSegmentsLength % oldChallengeDegree;\n        }\n    }\n\n    function hashChallengeState(\n        uint256 segmentsStart,\n        uint256 segmentsLength,\n        bytes32[] memory segments\n    ) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(segmentsStart, segmentsLength, segments));\n    }\n\n    function blockStateHash(MachineStatus status, bytes32 globalStateHash)\n        internal\n        pure\n        returns (bytes32)\n    {\n        if (status == MachineStatus.FINISHED) {\n            return keccak256(abi.encodePacked(\"Block state:\", globalStateHash));\n        } else if (status == MachineStatus.ERRORED) {\n            return keccak256(abi.encodePacked(\"Block state, errored:\", globalStateHash));\n        } else if (status == MachineStatus.TOO_FAR) {\n            return keccak256(abi.encodePacked(\"Block state, too far:\"));\n        } else {\n            revert(\"BAD_BLOCK_STATUS\");\n        }\n    }\n}\n"
      },
      "src/challenge/IChallengeManager.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"../state/Machine.sol\";\nimport \"../bridge/IBridge.sol\";\nimport \"../bridge/ISequencerInbox.sol\";\nimport \"../osp/IOneStepProofEntry.sol\";\n\nimport \"./IChallengeResultReceiver.sol\";\n\nimport \"./ChallengeLib.sol\";\n\ninterface IChallengeManager {\n    enum ChallengeTerminationType {\n        TIMEOUT,\n        BLOCK_PROOF,\n        EXECUTION_PROOF,\n        CLEARED\n    }\n\n    event InitiatedChallenge(\n        uint64 indexed challengeIndex,\n        GlobalState startState,\n        GlobalState endState\n    );\n\n    event Bisected(\n        uint64 indexed challengeIndex,\n        bytes32 indexed challengeRoot,\n        uint256 challengedSegmentStart,\n        uint256 challengedSegmentLength,\n        bytes32[] chainHashes\n    );\n\n    event ExecutionChallengeBegun(uint64 indexed challengeIndex, uint256 blockSteps);\n    event OneStepProofCompleted(uint64 indexed challengeIndex);\n\n    event ChallengeEnded(uint64 indexed challengeIndex, ChallengeTerminationType kind);\n\n    function initialize(\n        IChallengeResultReceiver resultReceiver_,\n        ISequencerInbox sequencerInbox_,\n        IBridge bridge_,\n        IOneStepProofEntry osp_\n    ) external;\n\n    function createChallenge(\n        bytes32 wasmModuleRoot_,\n        MachineStatus[2] calldata startAndEndMachineStatuses_,\n        GlobalState[2] calldata startAndEndGlobalStates_,\n        uint64 numBlocks,\n        address asserter_,\n        address challenger_,\n        uint256 asserterTimeLeft_,\n        uint256 challengerTimeLeft_\n    ) external returns (uint64);\n\n    function challengeInfo(uint64 challengeIndex_)\n        external\n        view\n        returns (ChallengeLib.Challenge memory);\n\n    function currentResponder(uint64 challengeIndex) external view returns (address);\n\n    function isTimedOut(uint64 challengeIndex) external view returns (bool);\n\n    function clearChallenge(uint64 challengeIndex_) external;\n\n    function timeout(uint64 challengeIndex_) external;\n}\n"
      },
      "src/challenge/IChallengeResultReceiver.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\ninterface IChallengeResultReceiver {\n    function completeChallenge(\n        uint256 challengeIndex,\n        address winner,\n        address loser\n    ) external;\n}\n"
      },
      "src/libraries/AdminFallbackProxy.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/proxy/Proxy.sol\";\nimport \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/StorageSlot.sol\";\n\n/// @notice An extension to OZ's ERC1967Upgrade implementation to support two logic contracts\nabstract contract DoubleLogicERC1967Upgrade is ERC1967Upgrade {\n    // This is the keccak-256 hash of \"eip1967.proxy.implementation.secondary\" subtracted by 1\n    bytes32 internal constant _IMPLEMENTATION_SECONDARY_SLOT =\n        0x2b1dbce74324248c222f0ec2d5ed7bd323cfc425b336f0253c5ccfda7265546d;\n\n    // This is the keccak-256 hash of \"eip1967.proxy.rollback.secondary\" subtracted by 1\n    bytes32 private constant _ROLLBACK_SECONDARY_SLOT =\n        0x49bd798cd84788856140a4cd5030756b4d08a9e4d55db725ec195f232d262a89;\n\n    /**\n     * @dev Emitted when the secondary implementation is upgraded.\n     */\n    event UpgradedSecondary(address indexed implementation);\n\n    /**\n     * @dev Returns the current secondary implementation address.\n     */\n    function _getSecondaryImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SECONDARY_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 implementation slot.\n     */\n    function _setSecondaryImplementation(address newImplementation) private {\n        require(\n            Address.isContract(newImplementation),\n            \"ERC1967: new secondary implementation is not a contract\"\n        );\n        StorageSlot.getAddressSlot(_IMPLEMENTATION_SECONDARY_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Perform secondary implementation upgrade\n     *\n     * Emits an {UpgradedSecondary} event.\n     */\n    function _upgradeSecondaryTo(address newImplementation) internal {\n        _setSecondaryImplementation(newImplementation);\n        emit UpgradedSecondary(newImplementation);\n    }\n\n    /**\n     * @dev Perform secondary implementation upgrade with additional setup call.\n     *\n     * Emits an {UpgradedSecondary} event.\n     */\n    function _upgradeSecondaryToAndCall(\n        address newImplementation,\n        bytes memory data,\n        bool forceCall\n    ) internal {\n        _upgradeSecondaryTo(newImplementation);\n        if (data.length > 0 || forceCall) {\n            Address.functionDelegateCall(newImplementation, data);\n        }\n    }\n\n    /**\n     * @dev Perform secondary implementation upgrade with security checks for UUPS proxies, and additional setup call.\n     *\n     * Emits an {UpgradedSecondary} event.\n     */\n    function _upgradeSecondaryToAndCallUUPS(\n        address newImplementation,\n        bytes memory data,\n        bool forceCall\n    ) internal {\n        // Upgrades from old implementations will perform a rollback test. This test requires the new\n        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n        // this special case will break upgrade paths from old UUPS implementation to new ones.\n        if (StorageSlot.getBooleanSlot(_ROLLBACK_SECONDARY_SLOT).value) {\n            _setSecondaryImplementation(newImplementation);\n        } else {\n            try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n                require(\n                    slot == _IMPLEMENTATION_SECONDARY_SLOT,\n                    \"ERC1967Upgrade: unsupported secondary proxiableUUID\"\n                );\n            } catch {\n                revert(\"ERC1967Upgrade: new secondary implementation is not UUPS\");\n            }\n            _upgradeSecondaryToAndCall(newImplementation, data, forceCall);\n        }\n    }\n}\n\n/// @notice similar to TransparentUpgradeableProxy but allows the admin to fallback to a separate logic contract using DoubleLogicERC1967Upgrade\n/// @dev this follows the UUPS pattern for upgradeability - read more at https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v4.5.0/contracts/proxy#transparent-vs-uups-proxies\ncontract AdminFallbackProxy is Proxy, DoubleLogicERC1967Upgrade {\n    /**\n     * @dev Initializes the upgradeable proxy with an initial implementation specified by `adminLogic` and a secondary\n     * logic implementation specified by `userLogic`\n     *\n     * Only the `adminAddr` is able to use the `adminLogic` functions\n     * All other addresses can interact with the `userLogic` functions\n     */\n    function _initialize(\n        address adminLogic,\n        bytes memory adminData,\n        address userLogic,\n        bytes memory userData,\n        address adminAddr\n    ) internal {\n        assert(_ADMIN_SLOT == bytes32(uint256(keccak256(\"eip1967.proxy.admin\")) - 1));\n        assert(\n            _IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\"eip1967.proxy.implementation\")) - 1)\n        );\n        assert(\n            _IMPLEMENTATION_SECONDARY_SLOT ==\n                bytes32(uint256(keccak256(\"eip1967.proxy.implementation.secondary\")) - 1)\n        );\n        _changeAdmin(adminAddr);\n        _upgradeToAndCall(adminLogic, adminData, false);\n        _upgradeSecondaryToAndCall(userLogic, userData, false);\n    }\n\n    /// @inheritdoc Proxy\n    function _implementation() internal view override returns (address) {\n        require(msg.data.length >= 4, \"NO_FUNC_SIG\");\n        // if the sender is the proxy's admin, delegate to admin logic\n        // if the admin is disabled, all calls will be forwarded to user logic\n        // admin affordances can be disabled by setting to a no-op smart contract\n        // since there is a check for contract code before updating the value\n        address target = _getAdmin() != msg.sender\n            ? DoubleLogicERC1967Upgrade._getSecondaryImplementation()\n            : ERC1967Upgrade._getImplementation();\n        // implementation setters do an existence check, but we protect against selfdestructs this way\n        require(Address.isContract(target), \"TARGET_NOT_CONTRACT\");\n        return target;\n    }\n\n    /**\n     * @dev unlike transparent upgradeable proxies, this does allow the admin to fallback to a logic contract\n     * the admin is expected to interact only with the primary logic contract, which handles contract\n     * upgrades using the UUPS approach\n     */\n    function _beforeFallback() internal override {\n        super._beforeFallback();\n    }\n}\n"
      },
      "src/libraries/ArbitrumChecker.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/nitro/blob/master/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"../precompiles/ArbSys.sol\";\n\nlibrary ArbitrumChecker {\n    function runningOnArbitrum() internal view returns (bool) {\n        (bool ok, bytes memory data) = address(100).staticcall(\n            abi.encodeWithSelector(ArbSys.arbOSVersion.selector)\n        );\n        return ok && data.length == 32;\n    }\n}\n"
      },
      "src/libraries/Constants.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.4;\n\nuint64 constant NO_CHAL_INDEX = 0;\n\n// Expected seconds per block in Ethereum PoS\nuint256 constant ETH_POS_BLOCK_TIME = 12;\n"
      },
      "src/libraries/IGasRefunder.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.6.9 <0.9.0;\n\ninterface IGasRefunder {\n    function onGasSpent(\n        address payable spender,\n        uint256 gasUsed,\n        uint256 calldataSize\n    ) external returns (bool success);\n}\n"
      },
      "src/libraries/UUPSNotUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/interfaces/draft-IERC1822.sol\";\nimport {DoubleLogicERC1967Upgrade} from \"./AdminFallbackProxy.sol\";\n\n/**\n * @dev UUPSUpgradeable by OpenZeppelin but not upgradeable. This is expected to be used on the secondary\n * logic slot behind a DoubleLogicERC1967Upgrade proxy\n */\nabstract contract UUPSNotUpgradeable is IERC1822Proxiable, DoubleLogicERC1967Upgrade {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment\n    address private immutable __self = address(this);\n\n    /**\n     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case\n     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n     * fail.\n     */\n    modifier onlyProxy() {\n        require(address(this) != __self, \"Function must be called through delegatecall\");\n        require(\n            _getSecondaryImplementation() == __self,\n            \"Function must be called through active proxy\"\n        );\n        _;\n    }\n\n    /**\n     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n     * callable on the implementing contract but not through proxies.\n     */\n    modifier notDelegated() {\n        require(\n            address(this) == __self,\n            \"UUPSNotUpgradeable: must not be called through delegatecall\"\n        );\n        _;\n    }\n\n    /**\n     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the\n     * implementation. It is used to validate that the this implementation remains valid after an upgrade.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n     */\n    function proxiableUUID() external view virtual override notDelegated returns (bytes32) {\n        return _IMPLEMENTATION_SECONDARY_SLOT;\n    }\n}\n"
      },
      "src/osp/IOneStepProofEntry.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./IOneStepProver.sol\";\n\nlibrary OneStepProofEntryLib {\n    uint256 internal constant MAX_STEPS = 1 << 43;\n}\n\ninterface IOneStepProofEntry {\n    function proveOneStep(\n        ExecutionContext calldata execCtx,\n        uint256 machineStep,\n        bytes32 beforeHash,\n        bytes calldata proof\n    ) external view returns (bytes32 afterHash);\n}\n"
      },
      "src/osp/IOneStepProver.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"../state/Machine.sol\";\nimport \"../state/Module.sol\";\nimport \"../state/Instructions.sol\";\nimport \"../state/GlobalState.sol\";\nimport \"../bridge/ISequencerInbox.sol\";\nimport \"../bridge/IBridge.sol\";\n\nstruct ExecutionContext {\n    uint256 maxInboxMessagesRead;\n    IBridge bridge;\n}\n\nabstract contract IOneStepProver {\n    function executeOneStep(\n        ExecutionContext memory execCtx,\n        Machine calldata mach,\n        Module calldata mod,\n        Instruction calldata instruction,\n        bytes calldata proof\n    ) external view virtual returns (Machine memory result, Module memory resultMod);\n}\n"
      },
      "src/precompiles/ArbSys.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity >=0.4.21 <0.9.0;\n\n/**\n * @title System level functionality\n * @notice For use by contracts to interact with core L2-specific functionality.\n * Precompiled contract that exists in every Arbitrum chain at address(100), 0x0000000000000000000000000000000000000064.\n */\ninterface ArbSys {\n    /**\n     * @notice Get Arbitrum block number (distinct from L1 block number; Arbitrum genesis block has block number 0)\n     * @return block number as int\n     */\n    function arbBlockNumber() external view returns (uint256);\n\n    /**\n     * @notice Get Arbitrum block hash (reverts unless currentBlockNum-256 <= arbBlockNum < currentBlockNum)\n     * @return block hash\n     */\n    function arbBlockHash(uint256 arbBlockNum) external view returns (bytes32);\n\n    /**\n     * @notice Gets the rollup's unique chain identifier\n     * @return Chain identifier as int\n     */\n    function arbChainID() external view returns (uint256);\n\n    /**\n     * @notice Get internal version number identifying an ArbOS build\n     * @return version number as int\n     */\n    function arbOSVersion() external view returns (uint256);\n\n    /**\n     * @notice Returns 0 since Nitro has no concept of storage gas\n     * @return uint 0\n     */\n    function getStorageGasAvailable() external view returns (uint256);\n\n    /**\n     * @notice (deprecated) check if current call is top level (meaning it was triggered by an EoA or a L1 contract)\n     * @dev this call has been deprecated and may be removed in a future release\n     * @return true if current execution frame is not a call by another L2 contract\n     */\n    function isTopLevelCall() external view returns (bool);\n\n    /**\n     * @notice map L1 sender contract address to its L2 alias\n     * @param sender sender address\n     * @param unused argument no longer used\n     * @return aliased sender address\n     */\n    function mapL1SenderContractAddressToL2Alias(address sender, address unused)\n        external\n        pure\n        returns (address);\n\n    /**\n     * @notice check if the caller (of this caller of this) is an aliased L1 contract address\n     * @return true iff the caller's address is an alias for an L1 contract address\n     */\n    function wasMyCallersAddressAliased() external view returns (bool);\n\n    /**\n     * @notice return the address of the caller (of this caller of this), without applying L1 contract address aliasing\n     * @return address of the caller's caller, without applying L1 contract address aliasing\n     */\n    function myCallersAddressWithoutAliasing() external view returns (address);\n\n    /**\n     * @notice Send given amount of Eth to dest from sender.\n     * This is a convenience function, which is equivalent to calling sendTxToL1 with empty data.\n     * @param destination recipient address on L1\n     * @return unique identifier for this L2-to-L1 transaction.\n     */\n    function withdrawEth(address destination) external payable returns (uint256);\n\n    /**\n     * @notice Send a transaction to L1\n     * @dev it is not possible to execute on the L1 any L2-to-L1 transaction which contains data\n     * to a contract address without any code (as enforced by the Bridge contract).\n     * @param destination recipient address on L1\n     * @param data (optional) calldata for L1 contract call\n     * @return a unique identifier for this L2-to-L1 transaction.\n     */\n    function sendTxToL1(address destination, bytes calldata data)\n        external\n        payable\n        returns (uint256);\n\n    /**\n     * @notice Get send Merkle tree state\n     * @return size number of sends in the history\n     * @return root root hash of the send history\n     * @return partials hashes of partial subtrees in the send history tree\n     */\n    function sendMerkleTreeState()\n        external\n        view\n        returns (\n            uint256 size,\n            bytes32 root,\n            bytes32[] memory partials\n        );\n\n    /**\n     * @notice creates a send txn from L2 to L1\n     * @param position = (level << 192) + leaf = (0 << 192) + leaf = leaf\n     */\n    event L2ToL1Tx(\n        address caller,\n        address indexed destination,\n        uint256 indexed hash,\n        uint256 indexed position,\n        uint256 arbBlockNum,\n        uint256 ethBlockNum,\n        uint256 timestamp,\n        uint256 callvalue,\n        bytes data\n    );\n\n    /// @dev DEPRECATED in favour of the new L2ToL1Tx event above after the nitro upgrade\n    event L2ToL1Transaction(\n        address caller,\n        address indexed destination,\n        uint256 indexed uniqueId,\n        uint256 indexed batchNumber,\n        uint256 indexInBatch,\n        uint256 arbBlockNum,\n        uint256 ethBlockNum,\n        uint256 timestamp,\n        uint256 callvalue,\n        bytes data\n    );\n\n    /**\n     * @notice logs a merkle branch for proof synthesis\n     * @param reserved an index meant only to align the 4th index with L2ToL1Transaction's 4th event\n     * @param hash the merkle hash\n     * @param position = (level << 192) + leaf\n     */\n    event SendMerkleUpdate(\n        uint256 indexed reserved,\n        bytes32 indexed hash,\n        uint256 indexed position\n    );\n\n    error InvalidBlockNumber(uint256 requested, uint256 current);\n}\n"
      },
      "src/rollup/IRollupCore.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./Node.sol\";\nimport \"../bridge/IBridge.sol\";\nimport \"../bridge/IOutbox.sol\";\nimport \"../bridge/IInboxBase.sol\";\nimport \"./IRollupEventInbox.sol\";\nimport \"../challenge/IChallengeManager.sol\";\n\ninterface IRollupCore {\n    struct Staker {\n        uint256 amountStaked;\n        uint64 index;\n        uint64 latestStakedNode;\n        // currentChallenge is 0 if staker is not in a challenge\n        uint64 currentChallenge;\n        bool isStaked;\n    }\n\n    event RollupInitialized(bytes32 machineHash, uint256 chainId);\n\n    event NodeCreated(\n        uint64 indexed nodeNum,\n        bytes32 indexed parentNodeHash,\n        bytes32 indexed nodeHash,\n        bytes32 executionHash,\n        Assertion assertion,\n        bytes32 afterInboxBatchAcc,\n        bytes32 wasmModuleRoot,\n        uint256 inboxMaxCount\n    );\n\n    event NodeConfirmed(uint64 indexed nodeNum, bytes32 blockHash, bytes32 sendRoot);\n\n    event NodeRejected(uint64 indexed nodeNum);\n\n    event RollupChallengeStarted(\n        uint64 indexed challengeIndex,\n        address asserter,\n        address challenger,\n        uint64 challengedNode\n    );\n\n    event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance);\n\n    event UserWithdrawableFundsUpdated(\n        address indexed user,\n        uint256 initialBalance,\n        uint256 finalBalance\n    );\n\n    function confirmPeriodBlocks() external view returns (uint64);\n\n    function extraChallengeTimeBlocks() external view returns (uint64);\n\n    function chainId() external view returns (uint256);\n\n    function baseStake() external view returns (uint256);\n\n    function wasmModuleRoot() external view returns (bytes32);\n\n    function bridge() external view returns (IBridge);\n\n    function sequencerInbox() external view returns (ISequencerInbox);\n\n    function outbox() external view returns (IOutbox);\n\n    function rollupEventInbox() external view returns (IRollupEventInbox);\n\n    function challengeManager() external view returns (IChallengeManager);\n\n    function loserStakeEscrow() external view returns (address);\n\n    function stakeToken() external view returns (address);\n\n    function minimumAssertionPeriod() external view returns (uint256);\n\n    function isValidator(address) external view returns (bool);\n\n    function validatorWhitelistDisabled() external view returns (bool);\n\n    /**\n     * @notice Get the Node for the given index.\n     */\n    function getNode(uint64 nodeNum) external view returns (Node memory);\n\n    /**\n     * @notice Returns the block in which the given node was created for looking up its creation event.\n     * Unlike the Node's createdAtBlock field, this will be the ArbSys blockNumber if the host chain is an Arbitrum chain.\n     * That means that the block number returned for this is usable for event queries.\n     * This function will revert if the given node number does not exist.\n     * @dev This function is meant for internal use only and has no stability guarantees.\n     */\n    function getNodeCreationBlockForLogLookup(uint64 nodeNum) external view returns (uint256);\n\n    /**\n     * @notice Check if the specified node has been staked on by the provided staker.\n     * Only accurate at the latest confirmed node and afterwards.\n     */\n    function nodeHasStaker(uint64 nodeNum, address staker) external view returns (bool);\n\n    /**\n     * @notice Get the address of the staker at the given index\n     * @param stakerNum Index of the staker\n     * @return Address of the staker\n     */\n    function getStakerAddress(uint64 stakerNum) external view returns (address);\n\n    /**\n     * @notice Check whether the given staker is staked\n     * @param staker Staker address to check\n     * @return True or False for whether the staker was staked\n     */\n    function isStaked(address staker) external view returns (bool);\n\n    /**\n     * @notice Get the latest staked node of the given staker\n     * @param staker Staker address to lookup\n     * @return Latest node staked of the staker\n     */\n    function latestStakedNode(address staker) external view returns (uint64);\n\n    /**\n     * @notice Get the current challenge of the given staker\n     * @param staker Staker address to lookup\n     * @return Current challenge of the staker\n     */\n    function currentChallenge(address staker) external view returns (uint64);\n\n    /**\n     * @notice Get the amount staked of the given staker\n     * @param staker Staker address to lookup\n     * @return Amount staked of the staker\n     */\n    function amountStaked(address staker) external view returns (uint256);\n\n    /**\n     * @notice Retrieves stored information about a requested staker\n     * @param staker Staker address to retrieve\n     * @return A structure with information about the requested staker\n     */\n    function getStaker(address staker) external view returns (Staker memory);\n\n    /**\n     * @notice Get the original staker address of the zombie at the given index\n     * @param zombieNum Index of the zombie to lookup\n     * @return Original staker address of the zombie\n     */\n    function zombieAddress(uint256 zombieNum) external view returns (address);\n\n    /**\n     * @notice Get Latest node that the given zombie at the given index is staked on\n     * @param zombieNum Index of the zombie to lookup\n     * @return Latest node that the given zombie is staked on\n     */\n    function zombieLatestStakedNode(uint256 zombieNum) external view returns (uint64);\n\n    /// @return Current number of un-removed zombies\n    function zombieCount() external view returns (uint256);\n\n    function isZombie(address staker) external view returns (bool);\n\n    /**\n     * @notice Get the amount of funds withdrawable by the given address\n     * @param owner Address to check the funds of\n     * @return Amount of funds withdrawable by owner\n     */\n    function withdrawableFunds(address owner) external view returns (uint256);\n\n    /**\n     * @return Index of the first unresolved node\n     * @dev If all nodes have been resolved, this will be latestNodeCreated + 1\n     */\n    function firstUnresolvedNode() external view returns (uint64);\n\n    /// @return Index of the latest confirmed node\n    function latestConfirmed() external view returns (uint64);\n\n    /// @return Index of the latest rollup node created\n    function latestNodeCreated() external view returns (uint64);\n\n    /// @return Ethereum block that the most recent stake was created\n    function lastStakeBlock() external view returns (uint64);\n\n    /// @return Number of active stakers currently staked\n    function stakerCount() external view returns (uint64);\n}\n"
      },
      "src/rollup/IRollupEventInbox.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"../bridge/IBridge.sol\";\n\ninterface IRollupEventInbox {\n    function bridge() external view returns (IBridge);\n\n    function initialize(IBridge _bridge) external;\n\n    function rollup() external view returns (address);\n\n    function updateRollupAddress() external;\n\n    function rollupInitialized(uint256 chainId, string calldata chainConfig) external;\n}\n"
      },
      "src/rollup/IRollupLogic.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./IRollupCore.sol\";\nimport \"../bridge/ISequencerInbox.sol\";\nimport \"../bridge/IOutbox.sol\";\nimport \"../bridge/IOwnable.sol\";\n\ninterface IRollupUserAbs is IRollupCore, IOwnable {\n    /// @dev the user logic just validated configuration and shouldn't write to state during init\n    /// this allows the admin logic to ensure consistency on parameters.\n    function initialize(address stakeToken) external view;\n\n    function removeWhitelistAfterFork() external;\n\n    function removeWhitelistAfterValidatorAfk() external;\n\n    function isERC20Enabled() external view returns (bool);\n\n    function rejectNextNode(address stakerAddress) external;\n\n    function confirmNextNode(bytes32 blockHash, bytes32 sendRoot) external;\n\n    function stakeOnExistingNode(uint64 nodeNum, bytes32 nodeHash) external;\n\n    function stakeOnNewNode(\n        Assertion memory assertion,\n        bytes32 expectedNodeHash,\n        uint256 prevNodeInboxMaxCount\n    ) external;\n\n    function returnOldDeposit(address stakerAddress) external;\n\n    function reduceDeposit(uint256 target) external;\n\n    function removeZombie(uint256 zombieNum, uint256 maxNodes) external;\n\n    function removeOldZombies(uint256 startIndex) external;\n\n    function requiredStake(\n        uint256 blockNumber,\n        uint64 firstUnresolvedNodeNum,\n        uint64 latestCreatedNode\n    ) external view returns (uint256);\n\n    function currentRequiredStake() external view returns (uint256);\n\n    function countStakedZombies(uint64 nodeNum) external view returns (uint256);\n\n    function countZombiesStakedOnChildren(uint64 nodeNum) external view returns (uint256);\n\n    function requireUnresolvedExists() external view;\n\n    function requireUnresolved(uint256 nodeNum) external view;\n\n    function withdrawStakerFunds() external returns (uint256);\n\n    function createChallenge(\n        address[2] calldata stakers,\n        uint64[2] calldata nodeNums,\n        MachineStatus[2] calldata machineStatuses,\n        GlobalState[2] calldata globalStates,\n        uint64 numBlocks,\n        bytes32 secondExecutionHash,\n        uint256[2] calldata proposedTimes,\n        bytes32[2] calldata wasmModuleRoots\n    ) external;\n}\n\ninterface IRollupUser is IRollupUserAbs {\n    function newStakeOnExistingNode(uint64 nodeNum, bytes32 nodeHash) external payable;\n\n    function newStakeOnNewNode(\n        Assertion calldata assertion,\n        bytes32 expectedNodeHash,\n        uint256 prevNodeInboxMaxCount\n    ) external payable;\n\n    function addToDeposit(address stakerAddress) external payable;\n}\n\ninterface IRollupUserERC20 is IRollupUserAbs {\n    function newStakeOnExistingNode(\n        uint256 tokenAmount,\n        uint64 nodeNum,\n        bytes32 nodeHash\n    ) external;\n\n    function newStakeOnNewNode(\n        uint256 tokenAmount,\n        Assertion calldata assertion,\n        bytes32 expectedNodeHash,\n        uint256 prevNodeInboxMaxCount\n    ) external;\n\n    function addToDeposit(address stakerAddress, uint256 tokenAmount) external;\n}\n"
      },
      "src/rollup/Node.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"../state/GlobalState.sol\";\nimport \"../state/Machine.sol\";\n\nstruct ExecutionState {\n    GlobalState globalState;\n    MachineStatus machineStatus;\n}\n\nstruct Assertion {\n    ExecutionState beforeState;\n    ExecutionState afterState;\n    uint64 numBlocks;\n}\n\nstruct Node {\n    // Hash of the state of the chain as of this node\n    bytes32 stateHash;\n    // Hash of the data that can be challenged\n    bytes32 challengeHash;\n    // Hash of the data that will be committed if this node is confirmed\n    bytes32 confirmData;\n    // Index of the node previous to this one\n    uint64 prevNum;\n    // Deadline at which this node can be confirmed\n    uint64 deadlineBlock;\n    // Deadline at which a child of this node can be confirmed\n    uint64 noChildConfirmedBeforeBlock;\n    // Number of stakers staked on this node. This includes real stakers and zombies\n    uint64 stakerCount;\n    // Number of stakers staked on a child node. This includes real stakers and zombies\n    uint64 childStakerCount;\n    // This value starts at zero and is set to a value when the first child is created. After that it is constant until the node is destroyed or the owner destroys pending nodes\n    uint64 firstChildBlock;\n    // The number of the latest child of this node to be created\n    uint64 latestChildNumber;\n    // The block number when this node was created\n    uint64 createdAtBlock;\n    // A hash of all the data needed to determine this node's validity, to protect against reorgs\n    bytes32 nodeHash;\n}\n\n/**\n * @notice Utility functions for Node\n */\nlibrary NodeLib {\n    /**\n     * @notice Initialize a Node\n     * @param _stateHash Initial value of stateHash\n     * @param _challengeHash Initial value of challengeHash\n     * @param _confirmData Initial value of confirmData\n     * @param _prevNum Initial value of prevNum\n     * @param _deadlineBlock Initial value of deadlineBlock\n     * @param _nodeHash Initial value of nodeHash\n     */\n    function createNode(\n        bytes32 _stateHash,\n        bytes32 _challengeHash,\n        bytes32 _confirmData,\n        uint64 _prevNum,\n        uint64 _deadlineBlock,\n        bytes32 _nodeHash\n    ) internal view returns (Node memory) {\n        Node memory node;\n        node.stateHash = _stateHash;\n        node.challengeHash = _challengeHash;\n        node.confirmData = _confirmData;\n        node.prevNum = _prevNum;\n        node.deadlineBlock = _deadlineBlock;\n        node.noChildConfirmedBeforeBlock = _deadlineBlock;\n        node.createdAtBlock = uint64(block.number);\n        node.nodeHash = _nodeHash;\n        return node;\n    }\n\n    /**\n     * @notice Update child properties\n     * @param number The child number to set\n     */\n    function childCreated(Node storage self, uint64 number) internal {\n        if (self.firstChildBlock == 0) {\n            self.firstChildBlock = uint64(block.number);\n        }\n        self.latestChildNumber = number;\n    }\n\n    /**\n     * @notice Update the child confirmed deadline\n     * @param deadline The new deadline to set\n     */\n    function newChildConfirmDeadline(Node storage self, uint64 deadline) internal {\n        self.noChildConfirmedBeforeBlock = deadline;\n    }\n\n    /**\n     * @notice Check whether the current block number has met or passed the node's deadline\n     */\n    function requirePastDeadline(Node memory self) internal view {\n        require(block.number >= self.deadlineBlock, \"BEFORE_DEADLINE\");\n    }\n\n    /**\n     * @notice Check whether the current block number has met or passed deadline for children of this node to be confirmed\n     */\n    function requirePastChildConfirmDeadline(Node memory self) internal view {\n        require(block.number >= self.noChildConfirmedBeforeBlock, \"CHILD_TOO_RECENT\");\n    }\n}\n"
      },
      "src/rollup/RollupCore.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n\nimport \"./Node.sol\";\nimport \"./RollupLib.sol\";\nimport \"./IRollupEventInbox.sol\";\nimport \"./IRollupCore.sol\";\n\nimport \"../challenge/IChallengeManager.sol\";\n\nimport \"../bridge/ISequencerInbox.sol\";\nimport \"../bridge/IBridge.sol\";\nimport \"../bridge/IOutbox.sol\";\n\nimport \"../precompiles/ArbSys.sol\";\n\nimport \"../libraries/ArbitrumChecker.sol\";\nimport {NO_CHAL_INDEX} from \"../libraries/Constants.sol\";\n\nabstract contract RollupCore is IRollupCore, PausableUpgradeable {\n    using NodeLib for Node;\n    using GlobalStateLib for GlobalState;\n\n    // Rollup Config\n    uint64 public confirmPeriodBlocks;\n    uint64 public extraChallengeTimeBlocks;\n    uint256 public chainId;\n    uint256 public baseStake;\n    bytes32 public wasmModuleRoot;\n\n    IInboxBase public inbox;\n    IBridge public bridge;\n    IOutbox public outbox;\n    ISequencerInbox public sequencerInbox;\n    IRollupEventInbox public rollupEventInbox;\n    IChallengeManager public override challengeManager;\n\n    // misc useful contracts when interacting with the rollup\n    address public validatorUtils;\n    address public validatorWalletCreator;\n\n    // when a staker loses a challenge, half of their funds get escrowed in this address\n    address public loserStakeEscrow;\n    address public stakeToken;\n    uint256 public minimumAssertionPeriod;\n\n    mapping(address => bool) public isValidator;\n\n    // Stakers become Zombies after losing a challenge\n    struct Zombie {\n        address stakerAddress;\n        uint64 latestStakedNode;\n    }\n\n    uint64 private _latestConfirmed;\n    uint64 private _firstUnresolvedNode;\n    uint64 private _latestNodeCreated;\n    uint64 private _lastStakeBlock;\n    mapping(uint64 => Node) private _nodes;\n    mapping(uint64 => mapping(address => bool)) private _nodeStakers;\n\n    address[] private _stakerList;\n    mapping(address => Staker) public _stakerMap;\n\n    Zombie[] private _zombies;\n\n    mapping(address => uint256) private _withdrawableFunds;\n    uint256 public totalWithdrawableFunds;\n    uint256 public rollupDeploymentBlock;\n\n    // The node number of the initial node\n    uint64 internal constant GENESIS_NODE = 0;\n\n    bool public validatorWhitelistDisabled;\n\n    // If the chain this RollupCore is deployed on is an Arbitrum chain.\n    bool internal immutable _hostChainIsArbitrum = ArbitrumChecker.runningOnArbitrum();\n    // If the chain RollupCore is deployed on, this will contain the ArbSys.blockNumber() at each node's creation.\n    mapping(uint64 => uint256) internal _nodeCreatedAtArbSysBlock;\n\n    /**\n     * @notice Get a storage reference to the Node for the given node index\n     * @param nodeNum Index of the node\n     * @return Node struct\n     */\n    function getNodeStorage(uint64 nodeNum) internal view returns (Node storage) {\n        return _nodes[nodeNum];\n    }\n\n    /**\n     * @notice Get the Node for the given index.\n     */\n    function getNode(uint64 nodeNum) public view override returns (Node memory) {\n        return getNodeStorage(nodeNum);\n    }\n\n    /**\n     * @notice Returns the block in which the given node was created for looking up its creation event.\n     * Unlike the Node's createdAtBlock field, this will be the ArbSys blockNumber if the host chain is an Arbitrum chain.\n     * That means that the block number returned for this is usable for event queries.\n     * This function will revert if the given node number does not exist.\n     * @dev This function is meant for internal use only and has no stability guarantees.\n     */\n    function getNodeCreationBlockForLogLookup(uint64 nodeNum)\n        external\n        view\n        override\n        returns (uint256)\n    {\n        if (_hostChainIsArbitrum) {\n            uint256 blockNum = _nodeCreatedAtArbSysBlock[nodeNum];\n            require(blockNum > 0, \"NO_NODE\");\n            return blockNum;\n        } else {\n            Node storage node = getNodeStorage(nodeNum);\n            require(node.deadlineBlock != 0, \"NO_NODE\");\n            return node.createdAtBlock;\n        }\n    }\n\n    /**\n     * @notice Check if the specified node has been staked on by the provided staker.\n     * Only accurate at the latest confirmed node and afterwards.\n     */\n    function nodeHasStaker(uint64 nodeNum, address staker) public view override returns (bool) {\n        return _nodeStakers[nodeNum][staker];\n    }\n\n    /**\n     * @notice Get the address of the staker at the given index\n     * @param stakerNum Index of the staker\n     * @return Address of the staker\n     */\n    function getStakerAddress(uint64 stakerNum) external view override returns (address) {\n        return _stakerList[stakerNum];\n    }\n\n    /**\n     * @notice Check whether the given staker is staked\n     * @param staker Staker address to check\n     * @return True or False for whether the staker was staked\n     */\n    function isStaked(address staker) public view override returns (bool) {\n        return _stakerMap[staker].isStaked;\n    }\n\n    /**\n     * @notice Check whether the given staker is staked on the latest confirmed node,\n     * which includes if the staker is staked on a descendent of the latest confirmed node.\n     * @param staker Staker address to check\n     * @return True or False for whether the staker was staked\n     */\n    function isStakedOnLatestConfirmed(address staker) public view returns (bool) {\n        return _stakerMap[staker].isStaked && nodeHasStaker(_latestConfirmed, staker);\n    }\n\n    /**\n     * @notice Get the latest staked node of the given staker\n     * @param staker Staker address to lookup\n     * @return Latest node staked of the staker\n     */\n    function latestStakedNode(address staker) public view override returns (uint64) {\n        return _stakerMap[staker].latestStakedNode;\n    }\n\n    /**\n     * @notice Get the current challenge of the given staker\n     * @param staker Staker address to lookup\n     * @return Current challenge of the staker\n     */\n    function currentChallenge(address staker) public view override returns (uint64) {\n        return _stakerMap[staker].currentChallenge;\n    }\n\n    /**\n     * @notice Get the amount staked of the given staker\n     * @param staker Staker address to lookup\n     * @return Amount staked of the staker\n     */\n    function amountStaked(address staker) public view override returns (uint256) {\n        return _stakerMap[staker].amountStaked;\n    }\n\n    /**\n     * @notice Retrieves stored information about a requested staker\n     * @param staker Staker address to retrieve\n     * @return A structure with information about the requested staker\n     */\n    function getStaker(address staker) external view override returns (Staker memory) {\n        return _stakerMap[staker];\n    }\n\n    /**\n     * @notice Get the original staker address of the zombie at the given index\n     * @param zombieNum Index of the zombie to lookup\n     * @return Original staker address of the zombie\n     */\n    function zombieAddress(uint256 zombieNum) public view override returns (address) {\n        return _zombies[zombieNum].stakerAddress;\n    }\n\n    /**\n     * @notice Get Latest node that the given zombie at the given index is staked on\n     * @param zombieNum Index of the zombie to lookup\n     * @return Latest node that the given zombie is staked on\n     */\n    function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint64) {\n        return _zombies[zombieNum].latestStakedNode;\n    }\n\n    /**\n     * @notice Retrieves stored information about a requested zombie\n     * @param zombieNum Index of the zombie to lookup\n     * @return A structure with information about the requested staker\n     */\n    function getZombieStorage(uint256 zombieNum) internal view returns (Zombie storage) {\n        return _zombies[zombieNum];\n    }\n\n    /// @return Current number of un-removed zombies\n    function zombieCount() public view override returns (uint256) {\n        return _zombies.length;\n    }\n\n    function isZombie(address staker) public view override returns (bool) {\n        for (uint256 i = 0; i < _zombies.length; i++) {\n            if (staker == _zombies[i].stakerAddress) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    /**\n     * @notice Get the amount of funds withdrawable by the given address\n     * @param user Address to check the funds of\n     * @return Amount of funds withdrawable by user\n     */\n    function withdrawableFunds(address user) external view override returns (uint256) {\n        return _withdrawableFunds[user];\n    }\n\n    /**\n     * @return Index of the first unresolved node\n     * @dev If all nodes have been resolved, this will be latestNodeCreated + 1\n     */\n    function firstUnresolvedNode() public view override returns (uint64) {\n        return _firstUnresolvedNode;\n    }\n\n    /// @return Index of the latest confirmed node\n    function latestConfirmed() public view override returns (uint64) {\n        return _latestConfirmed;\n    }\n\n    /// @return Index of the latest rollup node created\n    function latestNodeCreated() public view override returns (uint64) {\n        return _latestNodeCreated;\n    }\n\n    /// @return Ethereum block that the most recent stake was created\n    function lastStakeBlock() external view override returns (uint64) {\n        return _lastStakeBlock;\n    }\n\n    /// @return Number of active stakers currently staked\n    function stakerCount() public view override returns (uint64) {\n        return uint64(_stakerList.length);\n    }\n\n    /**\n     * @notice Initialize the core with an initial node\n     * @param initialNode Initial node to start the chain with\n     */\n    function initializeCore(Node memory initialNode) internal {\n        __Pausable_init();\n        _nodes[GENESIS_NODE] = initialNode;\n        _firstUnresolvedNode = GENESIS_NODE + 1;\n        if (_hostChainIsArbitrum) {\n            _nodeCreatedAtArbSysBlock[GENESIS_NODE] = ArbSys(address(100)).arbBlockNumber();\n        }\n    }\n\n    /**\n     * @notice React to a new node being created by storing it an incrementing the latest node counter\n     * @param node Node that was newly created\n     */\n    function nodeCreated(Node memory node) internal {\n        _latestNodeCreated++;\n        _nodes[_latestNodeCreated] = node;\n        if (_hostChainIsArbitrum) {\n            _nodeCreatedAtArbSysBlock[_latestNodeCreated] = ArbSys(address(100)).arbBlockNumber();\n        }\n    }\n\n    /// @notice Reject the next unresolved node\n    function _rejectNextNode() internal {\n        _firstUnresolvedNode++;\n    }\n\n    function confirmNode(\n        uint64 nodeNum,\n        bytes32 blockHash,\n        bytes32 sendRoot\n    ) internal {\n        Node storage node = getNodeStorage(nodeNum);\n        // Authenticate data against node's confirm data pre-image\n        require(node.confirmData == RollupLib.confirmHash(blockHash, sendRoot), \"CONFIRM_DATA\");\n\n        // trusted external call to outbox\n        outbox.updateSendRoot(sendRoot, blockHash);\n\n        _latestConfirmed = nodeNum;\n        _firstUnresolvedNode = nodeNum + 1;\n\n        emit NodeConfirmed(nodeNum, blockHash, sendRoot);\n    }\n\n    /**\n     * @notice Create a new stake at latest confirmed node\n     * @param stakerAddress Address of the new staker\n     * @param depositAmount Stake amount of the new staker\n     */\n    function createNewStake(address stakerAddress, uint256 depositAmount) internal {\n        uint64 stakerIndex = uint64(_stakerList.length);\n        _stakerList.push(stakerAddress);\n        _stakerMap[stakerAddress] = Staker(\n            depositAmount,\n            stakerIndex,\n            _latestConfirmed,\n            NO_CHAL_INDEX, // new staker is not in challenge\n            true\n        );\n        _nodeStakers[_latestConfirmed][stakerAddress] = true;\n        _lastStakeBlock = uint64(block.number);\n        emit UserStakeUpdated(stakerAddress, 0, depositAmount);\n    }\n\n    /**\n     * @notice Check to see whether the two stakers are in the same challenge\n     * @param stakerAddress1 Address of the first staker\n     * @param stakerAddress2 Address of the second staker\n     * @return Address of the challenge that the two stakers are in\n     */\n    function inChallenge(address stakerAddress1, address stakerAddress2)\n        internal\n        view\n        returns (uint64)\n    {\n        Staker storage staker1 = _stakerMap[stakerAddress1];\n        Staker storage staker2 = _stakerMap[stakerAddress2];\n        uint64 challenge = staker1.currentChallenge;\n        require(challenge != NO_CHAL_INDEX, \"NO_CHAL\");\n        require(challenge == staker2.currentChallenge, \"DIFF_IN_CHAL\");\n        return challenge;\n    }\n\n    /**\n     * @notice Make the given staker as not being in a challenge\n     * @param stakerAddress Address of the staker to remove from a challenge\n     */\n    function clearChallenge(address stakerAddress) internal {\n        Staker storage staker = _stakerMap[stakerAddress];\n        staker.currentChallenge = NO_CHAL_INDEX;\n    }\n\n    /**\n     * @notice Mark both the given stakers as engaged in the challenge\n     * @param staker1 Address of the first staker\n     * @param staker2 Address of the second staker\n     * @param challenge Address of the challenge both stakers are now in\n     */\n    function challengeStarted(\n        address staker1,\n        address staker2,\n        uint64 challenge\n    ) internal {\n        _stakerMap[staker1].currentChallenge = challenge;\n        _stakerMap[staker2].currentChallenge = challenge;\n    }\n\n    /**\n     * @notice Add to the stake of the given staker by the given amount\n     * @param stakerAddress Address of the staker to increase the stake of\n     * @param amountAdded Amount of stake to add to the staker\n     */\n    function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal {\n        Staker storage staker = _stakerMap[stakerAddress];\n        uint256 initialStaked = staker.amountStaked;\n        uint256 finalStaked = initialStaked + amountAdded;\n        staker.amountStaked = finalStaked;\n        emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked);\n    }\n\n    /**\n     * @notice Reduce the stake of the given staker to the given target\n     * @param stakerAddress Address of the staker to reduce the stake of\n     * @param target Amount of stake to leave with the staker\n     * @return Amount of value released from the stake\n     */\n    function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) {\n        Staker storage staker = _stakerMap[stakerAddress];\n        uint256 current = staker.amountStaked;\n        require(target <= current, \"TOO_LITTLE_STAKE\");\n        uint256 amountWithdrawn = current - target;\n        staker.amountStaked = target;\n        increaseWithdrawableFunds(stakerAddress, amountWithdrawn);\n        emit UserStakeUpdated(stakerAddress, current, target);\n        return amountWithdrawn;\n    }\n\n    /**\n     * @notice Remove the given staker and turn them into a zombie\n     * @param stakerAddress Address of the staker to remove\n     */\n    function turnIntoZombie(address stakerAddress) internal {\n        Staker storage staker = _stakerMap[stakerAddress];\n        _zombies.push(Zombie(stakerAddress, staker.latestStakedNode));\n        deleteStaker(stakerAddress);\n    }\n\n    /**\n     * @notice Update the latest staked node of the zombie at the given index\n     * @param zombieNum Index of the zombie to move\n     * @param latest New latest node the zombie is staked on\n     */\n    function zombieUpdateLatestStakedNode(uint256 zombieNum, uint64 latest) internal {\n        _zombies[zombieNum].latestStakedNode = latest;\n    }\n\n    /**\n     * @notice Remove the zombie at the given index\n     * @param zombieNum Index of the zombie to remove\n     */\n    function removeZombie(uint256 zombieNum) internal {\n        _zombies[zombieNum] = _zombies[_zombies.length - 1];\n        _zombies.pop();\n    }\n\n    /**\n     * @notice Mark the given staker as staked on this node\n     * @param staker Address of the staker to mark\n     */\n    function addStaker(uint64 nodeNum, address staker) internal {\n        require(!_nodeStakers[nodeNum][staker], \"ALREADY_STAKED\");\n        _nodeStakers[nodeNum][staker] = true;\n        Node storage node = getNodeStorage(nodeNum);\n        require(node.deadlineBlock != 0, \"NO_NODE\");\n\n        uint64 prevCount = node.stakerCount;\n        node.stakerCount = prevCount + 1;\n\n        if (nodeNum > GENESIS_NODE) {\n            Node storage parent = getNodeStorage(node.prevNum);\n            parent.childStakerCount++;\n            if (prevCount == 0) {\n                parent.newChildConfirmDeadline(uint64(block.number) + confirmPeriodBlocks);\n            }\n        }\n    }\n\n    /**\n     * @notice Remove the given staker from this node\n     * @param staker Address of the staker to remove\n     */\n    function removeStaker(uint64 nodeNum, address staker) internal {\n        require(_nodeStakers[nodeNum][staker], \"NOT_STAKED\");\n        _nodeStakers[nodeNum][staker] = false;\n\n        Node storage node = getNodeStorage(nodeNum);\n        node.stakerCount--;\n\n        if (nodeNum > GENESIS_NODE) {\n            getNodeStorage(node.prevNum).childStakerCount--;\n        }\n    }\n\n    /**\n     * @notice Remove the given staker and return their stake\n     * This should not be called if the staker is staked on a descendent of the latest confirmed node\n     * @param stakerAddress Address of the staker withdrawing their stake\n     */\n    function withdrawStaker(address stakerAddress) internal {\n        Staker storage staker = _stakerMap[stakerAddress];\n        uint64 latestConfirmedNum = latestConfirmed();\n        if (nodeHasStaker(latestConfirmedNum, stakerAddress)) {\n            // Withdrawing a staker whose latest staked node isn't resolved should be impossible\n            assert(staker.latestStakedNode == latestConfirmedNum);\n            removeStaker(latestConfirmedNum, stakerAddress);\n        }\n        uint256 initialStaked = staker.amountStaked;\n        increaseWithdrawableFunds(stakerAddress, initialStaked);\n        deleteStaker(stakerAddress);\n        emit UserStakeUpdated(stakerAddress, initialStaked, 0);\n    }\n\n    /**\n     * @notice Advance the given staker to the given node\n     * @param stakerAddress Address of the staker adding their stake\n     * @param nodeNum Index of the node to stake on\n     */\n    function stakeOnNode(address stakerAddress, uint64 nodeNum) internal {\n        Staker storage staker = _stakerMap[stakerAddress];\n        addStaker(nodeNum, stakerAddress);\n        staker.latestStakedNode = nodeNum;\n    }\n\n    /**\n     * @notice Clear the withdrawable funds for the given address\n     * @param account Address of the account to remove funds from\n     * @return Amount of funds removed from account\n     */\n    function withdrawFunds(address account) internal returns (uint256) {\n        uint256 amount = _withdrawableFunds[account];\n        _withdrawableFunds[account] = 0;\n        totalWithdrawableFunds -= amount;\n        emit UserWithdrawableFundsUpdated(account, amount, 0);\n        return amount;\n    }\n\n    /**\n     * @notice Increase the withdrawable funds for the given address\n     * @param account Address of the account to add withdrawable funds to\n     */\n    function increaseWithdrawableFunds(address account, uint256 amount) internal {\n        uint256 initialWithdrawable = _withdrawableFunds[account];\n        uint256 finalWithdrawable = initialWithdrawable + amount;\n        _withdrawableFunds[account] = finalWithdrawable;\n        totalWithdrawableFunds += amount;\n        emit UserWithdrawableFundsUpdated(account, initialWithdrawable, finalWithdrawable);\n    }\n\n    /**\n     * @notice Remove the given staker\n     * @param stakerAddress Address of the staker to remove\n     */\n    function deleteStaker(address stakerAddress) private {\n        Staker storage staker = _stakerMap[stakerAddress];\n        require(staker.isStaked, \"NOT_STAKED\");\n        uint64 stakerIndex = staker.index;\n        _stakerList[stakerIndex] = _stakerList[_stakerList.length - 1];\n        _stakerMap[_stakerList[stakerIndex]].index = stakerIndex;\n        _stakerList.pop();\n        delete _stakerMap[stakerAddress];\n    }\n\n    struct StakeOnNewNodeFrame {\n        uint256 currentInboxSize;\n        Node node;\n        bytes32 executionHash;\n        Node prevNode;\n        bytes32 lastHash;\n        bool hasSibling;\n        uint64 deadlineBlock;\n        bytes32 sequencerBatchAcc;\n    }\n\n    function createNewNode(\n        Assertion calldata assertion,\n        uint64 prevNodeNum,\n        uint256 prevNodeInboxMaxCount,\n        bytes32 expectedNodeHash\n    ) internal returns (bytes32 newNodeHash) {\n        require(\n            assertion.afterState.machineStatus == MachineStatus.FINISHED ||\n                assertion.afterState.machineStatus == MachineStatus.ERRORED,\n            \"BAD_AFTER_STATUS\"\n        );\n\n        StakeOnNewNodeFrame memory memoryFrame;\n        {\n            // validate data\n            memoryFrame.prevNode = getNode(prevNodeNum);\n            memoryFrame.currentInboxSize = bridge.sequencerMessageCount();\n\n            // Make sure the previous state is correct against the node being built on\n            require(\n                RollupLib.stateHash(assertion.beforeState, prevNodeInboxMaxCount) ==\n                    memoryFrame.prevNode.stateHash,\n                \"PREV_STATE_HASH\"\n            );\n\n            // Ensure that the assertion doesn't read past the end of the current inbox\n            uint64 afterInboxCount = assertion.afterState.globalState.getInboxPosition();\n            uint64 prevInboxPosition = assertion.beforeState.globalState.getInboxPosition();\n            require(afterInboxCount >= prevInboxPosition, \"INBOX_BACKWARDS\");\n            if (afterInboxCount == prevInboxPosition) {\n                require(\n                    assertion.afterState.globalState.getPositionInMessage() >=\n                        assertion.beforeState.globalState.getPositionInMessage(),\n                    \"INBOX_POS_IN_MSG_BACKWARDS\"\n                );\n            }\n            // See validator/assertion.go ExecutionState RequiredBatches() for reasoning\n            if (\n                assertion.afterState.machineStatus == MachineStatus.ERRORED ||\n                assertion.afterState.globalState.getPositionInMessage() > 0\n            ) {\n                // The current inbox message was read\n                afterInboxCount++;\n            }\n            require(afterInboxCount <= memoryFrame.currentInboxSize, \"INBOX_PAST_END\");\n            // This gives replay protection against the state of the inbox\n            if (afterInboxCount > 0) {\n                memoryFrame.sequencerBatchAcc = bridge.sequencerInboxAccs(afterInboxCount - 1);\n            }\n        }\n\n        {\n            memoryFrame.executionHash = RollupLib.executionHash(assertion);\n\n            memoryFrame.deadlineBlock = uint64(block.number) + confirmPeriodBlocks;\n\n            memoryFrame.hasSibling = memoryFrame.prevNode.latestChildNumber > 0;\n            // here we don't use ternacy operator to remain compatible with slither\n            if (memoryFrame.hasSibling) {\n                memoryFrame.lastHash = getNodeStorage(memoryFrame.prevNode.latestChildNumber)\n                    .nodeHash;\n            } else {\n                memoryFrame.lastHash = memoryFrame.prevNode.nodeHash;\n            }\n\n            newNodeHash = RollupLib.nodeHash(\n                memoryFrame.hasSibling,\n                memoryFrame.lastHash,\n                memoryFrame.executionHash,\n                memoryFrame.sequencerBatchAcc,\n                wasmModuleRoot\n            );\n            require(\n                newNodeHash == expectedNodeHash || expectedNodeHash == bytes32(0),\n                \"UNEXPECTED_NODE_HASH\"\n            );\n\n            memoryFrame.node = NodeLib.createNode(\n                RollupLib.stateHash(assertion.afterState, memoryFrame.currentInboxSize),\n                RollupLib.challengeRootHash(\n                    memoryFrame.executionHash,\n                    block.number,\n                    wasmModuleRoot\n                ),\n                RollupLib.confirmHash(assertion),\n                prevNodeNum,\n                memoryFrame.deadlineBlock,\n                newNodeHash\n            );\n        }\n\n        {\n            uint64 nodeNum = latestNodeCreated() + 1;\n\n            // Fetch a storage reference to prevNode since we copied our other one into memory\n            // and we don't have enough stack available to keep to keep the previous storage reference around\n            Node storage prevNode = getNodeStorage(prevNodeNum);\n            prevNode.childCreated(nodeNum);\n\n            nodeCreated(memoryFrame.node);\n        }\n\n        emit NodeCreated(\n            latestNodeCreated(),\n            memoryFrame.prevNode.nodeHash,\n            newNodeHash,\n            memoryFrame.executionHash,\n            assertion,\n            memoryFrame.sequencerBatchAcc,\n            wasmModuleRoot,\n            memoryFrame.currentInboxSize\n        );\n\n        return newNodeHash;\n    }\n}\n"
      },
      "src/rollup/RollupLib.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"../challenge/IChallengeManager.sol\";\nimport \"../challenge/ChallengeLib.sol\";\nimport \"../state/GlobalState.sol\";\nimport \"../bridge/ISequencerInbox.sol\";\n\nimport \"../bridge/IBridge.sol\";\nimport \"../bridge/IOutbox.sol\";\nimport \"../bridge/IInboxBase.sol\";\nimport \"./Node.sol\";\nimport \"./IRollupEventInbox.sol\";\n\nlibrary RollupLib {\n    using GlobalStateLib for GlobalState;\n\n    function stateHash(ExecutionState calldata execState, uint256 inboxMaxCount)\n        internal\n        pure\n        returns (bytes32)\n    {\n        return\n            keccak256(\n                abi.encodePacked(\n                    execState.globalState.hash(),\n                    inboxMaxCount,\n                    execState.machineStatus\n                )\n            );\n    }\n\n    /// @dev same as stateHash but expects execState in memory instead of calldata\n    function stateHashMem(ExecutionState memory execState, uint256 inboxMaxCount)\n        internal\n        pure\n        returns (bytes32)\n    {\n        return\n            keccak256(\n                abi.encodePacked(\n                    execState.globalState.hash(),\n                    inboxMaxCount,\n                    execState.machineStatus\n                )\n            );\n    }\n\n    function executionHash(Assertion memory assertion) internal pure returns (bytes32) {\n        MachineStatus[2] memory statuses;\n        statuses[0] = assertion.beforeState.machineStatus;\n        statuses[1] = assertion.afterState.machineStatus;\n        GlobalState[2] memory globalStates;\n        globalStates[0] = assertion.beforeState.globalState;\n        globalStates[1] = assertion.afterState.globalState;\n        // TODO: benchmark how much this abstraction adds of gas overhead\n        return executionHash(statuses, globalStates, assertion.numBlocks);\n    }\n\n    function executionHash(\n        MachineStatus[2] memory statuses,\n        GlobalState[2] memory globalStates,\n        uint64 numBlocks\n    ) internal pure returns (bytes32) {\n        bytes32[] memory segments = new bytes32[](2);\n        segments[0] = ChallengeLib.blockStateHash(statuses[0], globalStates[0].hash());\n        segments[1] = ChallengeLib.blockStateHash(statuses[1], globalStates[1].hash());\n        return ChallengeLib.hashChallengeState(0, numBlocks, segments);\n    }\n\n    function challengeRootHash(\n        bytes32 execution,\n        uint256 proposedTime,\n        bytes32 wasmModuleRoot\n    ) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(execution, proposedTime, wasmModuleRoot));\n    }\n\n    function confirmHash(Assertion memory assertion) internal pure returns (bytes32) {\n        return\n            confirmHash(\n                assertion.afterState.globalState.getBlockHash(),\n                assertion.afterState.globalState.getSendRoot()\n            );\n    }\n\n    function confirmHash(bytes32 blockHash, bytes32 sendRoot) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(blockHash, sendRoot));\n    }\n\n    function nodeHash(\n        bool hasSibling,\n        bytes32 lastHash,\n        bytes32 assertionExecHash,\n        bytes32 inboxAcc,\n        bytes32 wasmModuleRoot\n    ) internal pure returns (bytes32) {\n        uint8 hasSiblingInt = hasSibling ? 1 : 0;\n        return\n            keccak256(\n                abi.encodePacked(\n                    hasSiblingInt,\n                    lastHash,\n                    assertionExecHash,\n                    inboxAcc,\n                    wasmModuleRoot\n                )\n            );\n    }\n}\n"
      },
      "src/rollup/RollupUserLogic.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\nimport {IRollupUser} from \"./IRollupLogic.sol\";\nimport \"../libraries/UUPSNotUpgradeable.sol\";\nimport \"./RollupCore.sol\";\nimport \"./IRollupLogic.sol\";\n\nimport {ETH_POS_BLOCK_TIME} from \"../libraries/Constants.sol\";\n\nabstract contract AbsRollupUserLogic is\n    RollupCore,\n    UUPSNotUpgradeable,\n    IRollupUserAbs,\n    IChallengeResultReceiver\n{\n    using NodeLib for Node;\n    using GlobalStateLib for GlobalState;\n\n    modifier onlyValidator() {\n        require(isValidator[msg.sender] || validatorWhitelistDisabled, \"NOT_VALIDATOR\");\n        _;\n    }\n\n    modifier whenNotPausedOrDeprecated() {\n        require(!paused() || address(bridge.rollup()) != address(this), \"PAUSED_AND_ACTIVE\");\n        _;\n    }\n\n    uint256 internal immutable deployTimeChainId = block.chainid;\n\n    function _chainIdChanged() internal view returns (bool) {\n        return deployTimeChainId != block.chainid;\n    }\n\n    /**\n     * @notice Extra number of blocks the validator can remain inactive before considered inactive\n     *         This is 7 days assuming a 13.2 seconds block time\n     */\n    uint256 public constant VALIDATOR_AFK_BLOCKS = 45818;\n\n    function _validatorIsAfk() internal view returns (bool) {\n        Node memory latestNode = getNodeStorage(latestNodeCreated());\n        if (latestNode.createdAtBlock == 0) return false;\n        if (latestNode.createdAtBlock + confirmPeriodBlocks + VALIDATOR_AFK_BLOCKS < block.number) {\n            return true;\n        }\n        return false;\n    }\n\n    function removeWhitelistAfterFork() external {\n        require(!validatorWhitelistDisabled, \"WHITELIST_DISABLED\");\n        require(_chainIdChanged(), \"CHAIN_ID_NOT_CHANGED\");\n        validatorWhitelistDisabled = true;\n    }\n\n    function removeWhitelistAfterValidatorAfk() external {\n        require(!validatorWhitelistDisabled, \"WHITELIST_DISABLED\");\n        require(_validatorIsAfk(), \"VALIDATOR_NOT_AFK\");\n        validatorWhitelistDisabled = true;\n    }\n\n    function isERC20Enabled() public view override returns (bool) {\n        return stakeToken != address(0);\n    }\n\n    /**\n     * @notice Reject the next unresolved node\n     * @param stakerAddress Example staker staked on sibling, used to prove a node is on an unconfirmable branch and can be rejected\n     */\n    function rejectNextNode(address stakerAddress) external onlyValidator whenNotPaused {\n        requireUnresolvedExists();\n        uint64 latestConfirmedNodeNum = latestConfirmed();\n        uint64 firstUnresolvedNodeNum = firstUnresolvedNode();\n        Node storage firstUnresolvedNode_ = getNodeStorage(firstUnresolvedNodeNum);\n\n        if (firstUnresolvedNode_.prevNum == latestConfirmedNodeNum) {\n            /**If the first unresolved node is a child of the latest confirmed node, to prove it can be rejected, we show:\n             * a) Its deadline has expired\n             * b) *Some* staker is staked on a sibling\n\n             * The following three checks are sufficient to prove b:\n            */\n\n            // 1.  StakerAddress is indeed a staker\n            require(isStakedOnLatestConfirmed(stakerAddress), \"NOT_STAKED\");\n\n            // 2. Staker's latest staked node hasn't been resolved; this proves that staker's latest staked node can't be a parent of firstUnresolvedNode\n            requireUnresolved(latestStakedNode(stakerAddress));\n\n            // 3. staker isn't staked on first unresolved node; this proves staker's latest staked can't be a child of firstUnresolvedNode (recall staking on node requires staking on all of its parents)\n            require(!nodeHasStaker(firstUnresolvedNodeNum, stakerAddress), \"STAKED_ON_TARGET\");\n            // If a staker is staked on a node that is neither a child nor a parent of firstUnresolvedNode, it must be a sibling, QED\n\n            // Verify the block's deadline has passed\n            firstUnresolvedNode_.requirePastDeadline();\n\n            getNodeStorage(latestConfirmedNodeNum).requirePastChildConfirmDeadline();\n\n            removeOldZombies(0);\n\n            // Verify that no staker is staked on this node\n            require(\n                firstUnresolvedNode_.stakerCount == countStakedZombies(firstUnresolvedNodeNum),\n                \"HAS_STAKERS\"\n            );\n        }\n        // Simpler case: if the first unreseolved node doesn't point to the last confirmed node, another branch was confirmed and can simply reject it outright\n        _rejectNextNode();\n\n        emit NodeRejected(firstUnresolvedNodeNum);\n    }\n\n    /**\n     * @notice Confirm the next unresolved node\n     * @param blockHash The block hash at the end of the assertion\n     * @param sendRoot The send root at the end of the assertion\n     */\n    function confirmNextNode(bytes32 blockHash, bytes32 sendRoot)\n        external\n        onlyValidator\n        whenNotPaused\n    {\n        requireUnresolvedExists();\n\n        uint64 nodeNum = firstUnresolvedNode();\n        Node storage node = getNodeStorage(nodeNum);\n\n        // Verify the block's deadline has passed\n        node.requirePastDeadline();\n\n        // Check that prev is latest confirmed\n        assert(node.prevNum == latestConfirmed());\n\n        Node storage prevNode = getNodeStorage(node.prevNum);\n        prevNode.requirePastChildConfirmDeadline();\n\n        removeOldZombies(0);\n\n        // Require only zombies are staked on siblings to this node, and there's at least one non-zombie staked on this node\n        uint256 stakedZombies = countStakedZombies(nodeNum);\n        uint256 zombiesStakedOnOtherChildren = countZombiesStakedOnChildren(node.prevNum) -\n            stakedZombies;\n        require(node.stakerCount > stakedZombies, \"NO_STAKERS\");\n        require(\n            prevNode.childStakerCount == node.stakerCount + zombiesStakedOnOtherChildren,\n            \"NOT_ALL_STAKED\"\n        );\n\n        confirmNode(nodeNum, blockHash, sendRoot);\n    }\n\n    /**\n     * @notice Create a new stake\n     * @param depositAmount The amount of either eth or tokens staked\n     */\n    function _newStake(uint256 depositAmount) internal onlyValidator whenNotPaused {\n        // Verify that sender is not already a staker\n        require(!isStaked(msg.sender), \"ALREADY_STAKED\");\n        require(!isZombie(msg.sender), \"STAKER_IS_ZOMBIE\");\n        require(depositAmount >= currentRequiredStake(), \"NOT_ENOUGH_STAKE\");\n\n        createNewStake(msg.sender, depositAmount);\n    }\n\n    /**\n     * @notice Move stake onto existing child node\n     * @param nodeNum Index of the node to move stake to. This must by a child of the node the staker is currently staked on\n     * @param nodeHash Node hash of nodeNum (protects against reorgs)\n     */\n    function stakeOnExistingNode(uint64 nodeNum, bytes32 nodeHash)\n        public\n        onlyValidator\n        whenNotPaused\n    {\n        require(isStakedOnLatestConfirmed(msg.sender), \"NOT_STAKED\");\n\n        require(\n            nodeNum >= firstUnresolvedNode() && nodeNum <= latestNodeCreated(),\n            \"NODE_NUM_OUT_OF_RANGE\"\n        );\n        Node storage node = getNodeStorage(nodeNum);\n        require(node.nodeHash == nodeHash, \"NODE_REORG\");\n        require(latestStakedNode(msg.sender) == node.prevNum, \"NOT_STAKED_PREV\");\n        stakeOnNode(msg.sender, nodeNum);\n    }\n\n    /**\n     * @notice Create a new node and move stake onto it\n     * @param assertion The assertion data\n     * @param expectedNodeHash The hash of the node being created (protects against reorgs)\n     */\n    function stakeOnNewNode(\n        Assertion calldata assertion,\n        bytes32 expectedNodeHash,\n        uint256 prevNodeInboxMaxCount\n    ) public onlyValidator whenNotPaused {\n        require(isStakedOnLatestConfirmed(msg.sender), \"NOT_STAKED\");\n        // Ensure staker is staked on the previous node\n        uint64 prevNode = latestStakedNode(msg.sender);\n\n        {\n            uint256 timeSinceLastNode = block.number - getNode(prevNode).createdAtBlock;\n            // Verify that assertion meets the minimum Delta time requirement\n            require(timeSinceLastNode >= minimumAssertionPeriod, \"TIME_DELTA\");\n\n            // Minimum size requirement: any assertion must consume at least all inbox messages\n            // put into L1 inbox before the prev node’s L1 blocknum.\n            // We make an exception if the machine enters the errored state,\n            // as it can't consume future batches.\n            require(\n                assertion.afterState.machineStatus == MachineStatus.ERRORED ||\n                    assertion.afterState.globalState.getInboxPosition() >= prevNodeInboxMaxCount,\n                \"TOO_SMALL\"\n            );\n            // Minimum size requirement: any assertion must contain at least one block\n            require(assertion.numBlocks > 0, \"EMPTY_ASSERTION\");\n\n            // The rollup cannot advance normally from an errored state\n            require(\n                assertion.beforeState.machineStatus == MachineStatus.FINISHED,\n                \"BAD_PREV_STATUS\"\n            );\n        }\n        createNewNode(assertion, prevNode, prevNodeInboxMaxCount, expectedNodeHash);\n\n        stakeOnNode(msg.sender, latestNodeCreated());\n    }\n\n    /**\n     * @notice Refund a staker that is currently staked on or before the latest confirmed node\n     * @dev Since a staker is initially placed in the latest confirmed node, if they don't move it\n     * a griefer can remove their stake. It is recomended to batch together the txs to place a stake\n     * and move it to the desired node.\n     * @param stakerAddress Address of the staker whose stake is refunded\n     */\n    function returnOldDeposit(address stakerAddress)\n        external\n        override\n        onlyValidator\n        whenNotPausedOrDeprecated\n    {\n        require(latestStakedNode(stakerAddress) <= latestConfirmed(), \"TOO_RECENT\");\n        requireUnchallengedStaker(stakerAddress);\n        withdrawStaker(stakerAddress);\n    }\n\n    /**\n     * @notice Increase the amount staked for the given staker\n     * @param stakerAddress Address of the staker whose stake is increased\n     * @param depositAmount The amount of either eth or tokens deposited\n     */\n    function _addToDeposit(address stakerAddress, uint256 depositAmount)\n        internal\n        onlyValidator\n        whenNotPaused\n    {\n        requireUnchallengedStaker(stakerAddress);\n        increaseStakeBy(stakerAddress, depositAmount);\n    }\n\n    /**\n     * @notice Reduce the amount staked for the sender (difference between initial amount staked and target is creditted back to the sender).\n     * @param target Target amount of stake for the staker. If this is below the current minimum, it will be set to minimum instead\n     */\n    function reduceDeposit(uint256 target) external onlyValidator whenNotPausedOrDeprecated {\n        requireUnchallengedStaker(msg.sender);\n        uint256 currentRequired = currentRequiredStake();\n        if (target < currentRequired) {\n            target = currentRequired;\n        }\n        reduceStakeTo(msg.sender, target);\n    }\n\n    /**\n     * @notice Start a challenge between the given stakers over the node created by the first staker assuming that the two are staked on conflicting nodes. N.B.: challenge creator does not necessarily need to be one of the two asserters.\n     * @param stakers Stakers engaged in the challenge. The first staker should be staked on the first node\n     * @param nodeNums Nodes of the stakers engaged in the challenge. The first node should be the earliest and is the one challenged\n     * @param machineStatuses The before and after machine status for the first assertion\n     * @param globalStates The before and after global state for the first assertion\n     * @param numBlocks The number of L2 blocks contained in the first assertion\n     * @param secondExecutionHash The execution hash of the second assertion\n     * @param proposedBlocks L1 block numbers that the two nodes were proposed at\n     * @param wasmModuleRoots The wasm module roots at the time of the creation of each assertion\n     */\n    function createChallenge(\n        address[2] calldata stakers,\n        uint64[2] calldata nodeNums,\n        MachineStatus[2] calldata machineStatuses,\n        GlobalState[2] calldata globalStates,\n        uint64 numBlocks,\n        bytes32 secondExecutionHash,\n        uint256[2] calldata proposedBlocks,\n        bytes32[2] calldata wasmModuleRoots\n    ) external onlyValidator whenNotPaused {\n        require(nodeNums[0] < nodeNums[1], \"WRONG_ORDER\");\n        require(nodeNums[1] <= latestNodeCreated(), \"NOT_PROPOSED\");\n        require(latestConfirmed() < nodeNums[0], \"ALREADY_CONFIRMED\");\n\n        Node storage node1 = getNodeStorage(nodeNums[0]);\n        Node storage node2 = getNodeStorage(nodeNums[1]);\n\n        // ensure nodes staked on the same parent (and thus in conflict)\n        require(node1.prevNum == node2.prevNum, \"DIFF_PREV\");\n\n        // ensure both stakers aren't currently in challenge\n        requireUnchallengedStaker(stakers[0]);\n        requireUnchallengedStaker(stakers[1]);\n\n        require(nodeHasStaker(nodeNums[0], stakers[0]), \"STAKER1_NOT_STAKED\");\n        require(nodeHasStaker(nodeNums[1], stakers[1]), \"STAKER2_NOT_STAKED\");\n\n        // Check param data against challenge hash\n        require(\n            node1.challengeHash ==\n                RollupLib.challengeRootHash(\n                    RollupLib.executionHash(machineStatuses, globalStates, numBlocks),\n                    proposedBlocks[0],\n                    wasmModuleRoots[0]\n                ),\n            \"CHAL_HASH1\"\n        );\n\n        require(\n            node2.challengeHash ==\n                RollupLib.challengeRootHash(\n                    secondExecutionHash,\n                    proposedBlocks[1],\n                    wasmModuleRoots[1]\n                ),\n            \"CHAL_HASH2\"\n        );\n\n        // Calculate upper limit for allowed node proposal time:\n        uint256 commonEndBlock = getNodeStorage(node1.prevNum).firstChildBlock +\n            // Dispute start: dispute timer for a node starts when its first child is created\n            (node1.deadlineBlock - proposedBlocks[0]) +\n            extraChallengeTimeBlocks; // add dispute window to dispute start time\n        if (commonEndBlock < proposedBlocks[1]) {\n            // The 2nd node was created too late; loses challenge automatically.\n            completeChallengeImpl(stakers[0], stakers[1]);\n            return;\n        }\n        // Start a challenge between staker1 and staker2. Staker1 will defend the correctness of node1, and staker2 will challenge it.\n        uint64 challengeIndex = createChallengeHelper(\n            stakers,\n            machineStatuses,\n            globalStates,\n            numBlocks,\n            wasmModuleRoots,\n            // convert from block counts to real second based timestamps\n            (commonEndBlock - proposedBlocks[0]) * ETH_POS_BLOCK_TIME,\n            (commonEndBlock - proposedBlocks[1]) * ETH_POS_BLOCK_TIME\n        ); // trusted external call\n\n        challengeStarted(stakers[0], stakers[1], challengeIndex);\n\n        emit RollupChallengeStarted(challengeIndex, stakers[0], stakers[1], nodeNums[0]);\n    }\n\n    function createChallengeHelper(\n        address[2] calldata stakers,\n        MachineStatus[2] calldata machineStatuses,\n        GlobalState[2] calldata globalStates,\n        uint64 numBlocks,\n        bytes32[2] calldata wasmModuleRoots,\n        uint256 asserterTimeLeft,\n        uint256 challengerTimeLeft\n    ) internal returns (uint64) {\n        return\n            challengeManager.createChallenge(\n                wasmModuleRoots[0],\n                machineStatuses,\n                globalStates,\n                numBlocks,\n                stakers[0],\n                stakers[1],\n                asserterTimeLeft,\n                challengerTimeLeft\n            );\n    }\n\n    /**\n     * @notice Inform the rollup that the challenge between the given stakers is completed\n     * @param winningStaker Address of the winning staker\n     * @param losingStaker Address of the losing staker\n     */\n    function completeChallenge(\n        uint256 challengeIndex,\n        address winningStaker,\n        address losingStaker\n    ) external override whenNotPaused {\n        // Only the challenge manager contract can call this to declare the winner and loser\n        require(msg.sender == address(challengeManager), \"WRONG_SENDER\");\n        require(challengeIndex == inChallenge(winningStaker, losingStaker), \"NOT_IN_CHAL\");\n        completeChallengeImpl(winningStaker, losingStaker);\n    }\n\n    function completeChallengeImpl(address winningStaker, address losingStaker) private {\n        uint256 remainingLoserStake = amountStaked(losingStaker);\n        uint256 winnerStake = amountStaked(winningStaker);\n        if (remainingLoserStake > winnerStake) {\n            // If loser has a higher stake than the winner, refund the difference\n            remainingLoserStake -= reduceStakeTo(losingStaker, winnerStake);\n        }\n\n        // Reward the winner with half the remaining stake\n        uint256 amountWon = remainingLoserStake / 2;\n        increaseStakeBy(winningStaker, amountWon);\n        remainingLoserStake -= amountWon;\n        // We deliberately leave loser in challenge state to prevent them from\n        // doing certain thing that are allowed only to parties not in a challenge\n        clearChallenge(winningStaker);\n        // Credit the other half to the loserStakeEscrow address\n        increaseWithdrawableFunds(loserStakeEscrow, remainingLoserStake);\n        // Turning loser into zombie renders the loser's remaining stake inaccessible\n        turnIntoZombie(losingStaker);\n    }\n\n    /**\n     * @notice Remove the given zombie from nodes it is staked on, moving backwords from the latest node it is staked on\n     * @param zombieNum Index of the zombie to remove\n     * @param maxNodes Maximum number of nodes to remove the zombie from (to limit the cost of this transaction)\n     */\n    function removeZombie(uint256 zombieNum, uint256 maxNodes)\n        external\n        onlyValidator\n        whenNotPaused\n    {\n        require(zombieNum < zombieCount(), \"NO_SUCH_ZOMBIE\");\n        address zombieStakerAddress = zombieAddress(zombieNum);\n        uint64 latestNodeStaked = zombieLatestStakedNode(zombieNum);\n        uint256 nodesRemoved = 0;\n        uint256 latestConfirmedNum = latestConfirmed();\n        while (latestNodeStaked >= latestConfirmedNum && nodesRemoved < maxNodes) {\n            Node storage node = getNodeStorage(latestNodeStaked);\n            removeStaker(latestNodeStaked, zombieStakerAddress);\n            latestNodeStaked = node.prevNum;\n            nodesRemoved++;\n        }\n        if (latestNodeStaked < latestConfirmedNum) {\n            removeZombie(zombieNum);\n        } else {\n            zombieUpdateLatestStakedNode(zombieNum, latestNodeStaked);\n        }\n    }\n\n    /**\n     * @notice Remove any zombies whose latest stake is earlier than the latest confirmed node\n     * @param startIndex Index in the zombie list to start removing zombies from (to limit the cost of this transaction)\n     */\n    function removeOldZombies(uint256 startIndex) public onlyValidator whenNotPaused {\n        uint256 currentZombieCount = zombieCount();\n        uint256 latestConfirmedNum = latestConfirmed();\n        for (uint256 i = startIndex; i < currentZombieCount; i++) {\n            while (zombieLatestStakedNode(i) < latestConfirmedNum) {\n                removeZombie(i);\n                currentZombieCount--;\n                if (i >= currentZombieCount) {\n                    return;\n                }\n            }\n        }\n    }\n\n    /**\n     * @notice Calculate the current amount of funds required to place a new stake in the rollup\n     * @dev If the stake requirement get's too high, this function may start reverting due to overflow, but\n     * that only blocks operations that should be blocked anyway\n     * @return The current minimum stake requirement\n     */\n    function currentRequiredStake(\n        uint256 _blockNumber,\n        uint64 _firstUnresolvedNodeNum,\n        uint256 _latestCreatedNode\n    ) internal view returns (uint256) {\n        // If there are no unresolved nodes, then you can use the base stake\n        if (_firstUnresolvedNodeNum - 1 == _latestCreatedNode) {\n            return baseStake;\n        }\n        uint256 firstUnresolvedDeadline = getNodeStorage(_firstUnresolvedNodeNum).deadlineBlock;\n        if (_blockNumber < firstUnresolvedDeadline) {\n            return baseStake;\n        }\n        uint24[10] memory numerators = [\n            1,\n            122971,\n            128977,\n            80017,\n            207329,\n            114243,\n            314252,\n            129988,\n            224562,\n            162163\n        ];\n        uint24[10] memory denominators = [\n            1,\n            114736,\n            112281,\n            64994,\n            157126,\n            80782,\n            207329,\n            80017,\n            128977,\n            86901\n        ];\n        uint256 firstUnresolvedAge = _blockNumber - firstUnresolvedDeadline;\n        uint256 periodsPassed = (firstUnresolvedAge * 10) / confirmPeriodBlocks;\n        uint256 baseMultiplier = 2**(periodsPassed / 10);\n        uint256 withNumerator = baseMultiplier * numerators[periodsPassed % 10];\n        uint256 multiplier = withNumerator / denominators[periodsPassed % 10];\n        if (multiplier == 0) {\n            multiplier = 1;\n        }\n        return baseStake * multiplier;\n    }\n\n    /**\n     * @notice Calculate the current amount of funds required to place a new stake in the rollup\n     * @dev If the stake requirement get's too high, this function may start reverting due to overflow, but\n     * that only blocks operations that should be blocked anyway\n     * @return The current minimum stake requirement\n     */\n    function requiredStake(\n        uint256 blockNumber,\n        uint64 firstUnresolvedNodeNum,\n        uint64 latestCreatedNode\n    ) external view returns (uint256) {\n        return currentRequiredStake(blockNumber, firstUnresolvedNodeNum, latestCreatedNode);\n    }\n\n    function owner() external view returns (address) {\n        return _getAdmin();\n    }\n\n    function currentRequiredStake() public view returns (uint256) {\n        uint64 firstUnresolvedNodeNum = firstUnresolvedNode();\n\n        return currentRequiredStake(block.number, firstUnresolvedNodeNum, latestNodeCreated());\n    }\n\n    /**\n     * @notice Calculate the number of zombies staked on the given node\n     *\n     * @dev This function could be uncallable if there are too many zombies. However,\n     * removeZombie and removeOldZombies can be used to remove any zombies that exist\n     * so that this will then be callable\n     *\n     * @param nodeNum The node on which to count staked zombies\n     * @return The number of zombies staked on the node\n     */\n    function countStakedZombies(uint64 nodeNum) public view override returns (uint256) {\n        uint256 currentZombieCount = zombieCount();\n        uint256 stakedZombieCount = 0;\n        for (uint256 i = 0; i < currentZombieCount; i++) {\n            if (nodeHasStaker(nodeNum, zombieAddress(i))) {\n                stakedZombieCount++;\n            }\n        }\n        return stakedZombieCount;\n    }\n\n    /**\n     * @notice Calculate the number of zombies staked on a child of the given node\n     *\n     * @dev This function could be uncallable if there are too many zombies. However,\n     * removeZombie and removeOldZombies can be used to remove any zombies that exist\n     * so that this will then be callable\n     *\n     * @param nodeNum The parent node on which to count zombies staked on children\n     * @return The number of zombies staked on children of the node\n     */\n    function countZombiesStakedOnChildren(uint64 nodeNum) public view override returns (uint256) {\n        uint256 currentZombieCount = zombieCount();\n        uint256 stakedZombieCount = 0;\n        for (uint256 i = 0; i < currentZombieCount; i++) {\n            Zombie storage zombie = getZombieStorage(i);\n            // If this zombie is staked on this node, but its _latest_ staked node isn't this node,\n            // then it must be staked on a child of this node.\n            if (\n                zombie.latestStakedNode != nodeNum && nodeHasStaker(nodeNum, zombie.stakerAddress)\n            ) {\n                stakedZombieCount++;\n            }\n        }\n        return stakedZombieCount;\n    }\n\n    /**\n     * @notice Verify that there are some number of nodes still unresolved\n     */\n    function requireUnresolvedExists() public view override {\n        uint256 firstUnresolved = firstUnresolvedNode();\n        require(\n            firstUnresolved > latestConfirmed() && firstUnresolved <= latestNodeCreated(),\n            \"NO_UNRESOLVED\"\n        );\n    }\n\n    function requireUnresolved(uint256 nodeNum) public view override {\n        require(nodeNum >= firstUnresolvedNode(), \"ALREADY_DECIDED\");\n        require(nodeNum <= latestNodeCreated(), \"DOESNT_EXIST\");\n    }\n\n    /**\n     * @notice Verify that the given address is staked and not actively in a challenge\n     * @param stakerAddress Address to check\n     */\n    function requireUnchallengedStaker(address stakerAddress) private view {\n        require(isStaked(stakerAddress), \"NOT_STAKED\");\n        require(currentChallenge(stakerAddress) == NO_CHAL_INDEX, \"IN_CHAL\");\n    }\n}\n\ncontract RollupUserLogic is AbsRollupUserLogic, IRollupUser {\n    /// @dev the user logic just validated configuration and shouldn't write to state during init\n    /// this allows the admin logic to ensure consistency on parameters.\n    function initialize(address _stakeToken) external view override onlyProxy {\n        require(_stakeToken == address(0), \"NO_TOKEN_ALLOWED\");\n        require(!isERC20Enabled(), \"FACET_NOT_ERC20\");\n    }\n\n    /**\n     * @notice Create a new stake on an existing node\n     * @param nodeNum Number of the node your stake will be place one\n     * @param nodeHash Node hash of the node with the given nodeNum\n     */\n    function newStakeOnExistingNode(uint64 nodeNum, bytes32 nodeHash) external payable override {\n        _newStake(msg.value);\n        stakeOnExistingNode(nodeNum, nodeHash);\n    }\n\n    /**\n     * @notice Create a new stake on a new node\n     * @param assertion Assertion describing the state change between the old node and the new one\n     * @param expectedNodeHash Node hash of the node that will be created\n     * @param prevNodeInboxMaxCount Total of messages in the inbox as of the previous node\n     */\n    function newStakeOnNewNode(\n        Assertion calldata assertion,\n        bytes32 expectedNodeHash,\n        uint256 prevNodeInboxMaxCount\n    ) external payable override {\n        _newStake(msg.value);\n        stakeOnNewNode(assertion, expectedNodeHash, prevNodeInboxMaxCount);\n    }\n\n    /**\n     * @notice Increase the amount staked eth for the given staker\n     * @param stakerAddress Address of the staker whose stake is increased\n     */\n    function addToDeposit(address stakerAddress)\n        external\n        payable\n        override\n        onlyValidator\n        whenNotPaused\n    {\n        _addToDeposit(stakerAddress, msg.value);\n    }\n\n    /**\n     * @notice Withdraw uncommitted funds owned by sender from the rollup chain\n     */\n    function withdrawStakerFunds()\n        external\n        override\n        onlyValidator\n        whenNotPausedOrDeprecated\n        returns (uint256)\n    {\n        uint256 amount = withdrawFunds(msg.sender);\n        // This is safe because it occurs after all checks and effects\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, ) = msg.sender.call{value: amount}(\"\");\n        require(success, \"TRANSFER_FAILED\");\n        return amount;\n    }\n}\n\ncontract ERC20RollupUserLogic is AbsRollupUserLogic, IRollupUserERC20 {\n    /// @dev the user logic just validated configuration and shouldn't write to state during init\n    /// this allows the admin logic to ensure consistency on parameters.\n    function initialize(address _stakeToken) external view override onlyProxy {\n        require(_stakeToken != address(0), \"NEED_STAKE_TOKEN\");\n        require(isERC20Enabled(), \"FACET_NOT_ERC20\");\n    }\n\n    /**\n     * @notice Create a new stake on an existing node\n     * @param tokenAmount Amount of the rollups staking token to stake\n     * @param nodeNum Number of the node your stake will be place one\n     * @param nodeHash Node hash of the node with the given nodeNum\n     */\n    function newStakeOnExistingNode(\n        uint256 tokenAmount,\n        uint64 nodeNum,\n        bytes32 nodeHash\n    ) external override {\n        _newStake(tokenAmount);\n        stakeOnExistingNode(nodeNum, nodeHash);\n        /// @dev This is an external call, safe because it's at the end of the function\n        receiveTokens(tokenAmount);\n    }\n\n    /**\n     * @notice Create a new stake on a new node\n     * @param tokenAmount Amount of the rollups staking token to stake\n     * @param assertion Assertion describing the state change between the old node and the new one\n     * @param expectedNodeHash Node hash of the node that will be created\n     * @param prevNodeInboxMaxCount Total of messages in the inbox as of the previous node\n     */\n    function newStakeOnNewNode(\n        uint256 tokenAmount,\n        Assertion calldata assertion,\n        bytes32 expectedNodeHash,\n        uint256 prevNodeInboxMaxCount\n    ) external override {\n        _newStake(tokenAmount);\n        stakeOnNewNode(assertion, expectedNodeHash, prevNodeInboxMaxCount);\n        /// @dev This is an external call, safe because it's at the end of the function\n        receiveTokens(tokenAmount);\n    }\n\n    /**\n     * @notice Increase the amount staked tokens for the given staker\n     * @param stakerAddress Address of the staker whose stake is increased\n     * @param tokenAmount the amount of tokens staked\n     */\n    function addToDeposit(address stakerAddress, uint256 tokenAmount)\n        external\n        onlyValidator\n        whenNotPaused\n    {\n        _addToDeposit(stakerAddress, tokenAmount);\n        /// @dev This is an external call, safe because it's at the end of the function\n        receiveTokens(tokenAmount);\n    }\n\n    /**\n     * @notice Withdraw uncommitted funds owned by sender from the rollup chain\n     */\n    function withdrawStakerFunds()\n        external\n        override\n        onlyValidator\n        whenNotPausedOrDeprecated\n        returns (uint256)\n    {\n        uint256 amount = withdrawFunds(msg.sender);\n        // This is safe because it occurs after all checks and effects\n        require(IERC20Upgradeable(stakeToken).transfer(msg.sender, amount), \"TRANSFER_FAILED\");\n        return amount;\n    }\n\n    function receiveTokens(uint256 tokenAmount) private {\n        require(\n            IERC20Upgradeable(stakeToken).transferFrom(msg.sender, address(this), tokenAmount),\n            \"TRANSFER_FAIL\"\n        );\n    }\n}\n"
      },
      "src/state/GlobalState.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nstruct GlobalState {\n    bytes32[2] bytes32Vals;\n    uint64[2] u64Vals;\n}\n\nlibrary GlobalStateLib {\n    uint16 internal constant BYTES32_VALS_NUM = 2;\n    uint16 internal constant U64_VALS_NUM = 2;\n\n    function hash(GlobalState memory state) internal pure returns (bytes32) {\n        return\n            keccak256(\n                abi.encodePacked(\n                    \"Global state:\",\n                    state.bytes32Vals[0],\n                    state.bytes32Vals[1],\n                    state.u64Vals[0],\n                    state.u64Vals[1]\n                )\n            );\n    }\n\n    function getBlockHash(GlobalState memory state) internal pure returns (bytes32) {\n        return state.bytes32Vals[0];\n    }\n\n    function getSendRoot(GlobalState memory state) internal pure returns (bytes32) {\n        return state.bytes32Vals[1];\n    }\n\n    function getInboxPosition(GlobalState memory state) internal pure returns (uint64) {\n        return state.u64Vals[0];\n    }\n\n    function getPositionInMessage(GlobalState memory state) internal pure returns (uint64) {\n        return state.u64Vals[1];\n    }\n\n    function isEmpty(GlobalState calldata state) internal pure returns (bool) {\n        return (state.bytes32Vals[0] == bytes32(0) &&\n            state.bytes32Vals[1] == bytes32(0) &&\n            state.u64Vals[0] == 0 &&\n            state.u64Vals[1] == 0);\n    }\n}\n"
      },
      "src/state/Instructions.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nstruct Instruction {\n    uint16 opcode;\n    uint256 argumentData;\n}\n\nlibrary Instructions {\n    uint16 internal constant UNREACHABLE = 0x00;\n    uint16 internal constant NOP = 0x01;\n    uint16 internal constant RETURN = 0x0F;\n    uint16 internal constant CALL = 0x10;\n    uint16 internal constant CALL_INDIRECT = 0x11;\n    uint16 internal constant LOCAL_GET = 0x20;\n    uint16 internal constant LOCAL_SET = 0x21;\n    uint16 internal constant GLOBAL_GET = 0x23;\n    uint16 internal constant GLOBAL_SET = 0x24;\n\n    uint16 internal constant I32_LOAD = 0x28;\n    uint16 internal constant I64_LOAD = 0x29;\n    uint16 internal constant F32_LOAD = 0x2A;\n    uint16 internal constant F64_LOAD = 0x2B;\n    uint16 internal constant I32_LOAD8_S = 0x2C;\n    uint16 internal constant I32_LOAD8_U = 0x2D;\n    uint16 internal constant I32_LOAD16_S = 0x2E;\n    uint16 internal constant I32_LOAD16_U = 0x2F;\n    uint16 internal constant I64_LOAD8_S = 0x30;\n    uint16 internal constant I64_LOAD8_U = 0x31;\n    uint16 internal constant I64_LOAD16_S = 0x32;\n    uint16 internal constant I64_LOAD16_U = 0x33;\n    uint16 internal constant I64_LOAD32_S = 0x34;\n    uint16 internal constant I64_LOAD32_U = 0x35;\n\n    uint16 internal constant I32_STORE = 0x36;\n    uint16 internal constant I64_STORE = 0x37;\n    uint16 internal constant F32_STORE = 0x38;\n    uint16 internal constant F64_STORE = 0x39;\n    uint16 internal constant I32_STORE8 = 0x3A;\n    uint16 internal constant I32_STORE16 = 0x3B;\n    uint16 internal constant I64_STORE8 = 0x3C;\n    uint16 internal constant I64_STORE16 = 0x3D;\n    uint16 internal constant I64_STORE32 = 0x3E;\n\n    uint16 internal constant MEMORY_SIZE = 0x3F;\n    uint16 internal constant MEMORY_GROW = 0x40;\n\n    uint16 internal constant DROP = 0x1A;\n    uint16 internal constant SELECT = 0x1B;\n    uint16 internal constant I32_CONST = 0x41;\n    uint16 internal constant I64_CONST = 0x42;\n    uint16 internal constant F32_CONST = 0x43;\n    uint16 internal constant F64_CONST = 0x44;\n    uint16 internal constant I32_EQZ = 0x45;\n    uint16 internal constant I32_RELOP_BASE = 0x46;\n    uint16 internal constant IRELOP_EQ = 0;\n    uint16 internal constant IRELOP_NE = 1;\n    uint16 internal constant IRELOP_LT_S = 2;\n    uint16 internal constant IRELOP_LT_U = 3;\n    uint16 internal constant IRELOP_GT_S = 4;\n    uint16 internal constant IRELOP_GT_U = 5;\n    uint16 internal constant IRELOP_LE_S = 6;\n    uint16 internal constant IRELOP_LE_U = 7;\n    uint16 internal constant IRELOP_GE_S = 8;\n    uint16 internal constant IRELOP_GE_U = 9;\n    uint16 internal constant IRELOP_LAST = IRELOP_GE_U;\n\n    uint16 internal constant I64_EQZ = 0x50;\n    uint16 internal constant I64_RELOP_BASE = 0x51;\n\n    uint16 internal constant I32_UNOP_BASE = 0x67;\n    uint16 internal constant IUNOP_CLZ = 0;\n    uint16 internal constant IUNOP_CTZ = 1;\n    uint16 internal constant IUNOP_POPCNT = 2;\n    uint16 internal constant IUNOP_LAST = IUNOP_POPCNT;\n\n    uint16 internal constant I32_ADD = 0x6A;\n    uint16 internal constant I32_SUB = 0x6B;\n    uint16 internal constant I32_MUL = 0x6C;\n    uint16 internal constant I32_DIV_S = 0x6D;\n    uint16 internal constant I32_DIV_U = 0x6E;\n    uint16 internal constant I32_REM_S = 0x6F;\n    uint16 internal constant I32_REM_U = 0x70;\n    uint16 internal constant I32_AND = 0x71;\n    uint16 internal constant I32_OR = 0x72;\n    uint16 internal constant I32_XOR = 0x73;\n    uint16 internal constant I32_SHL = 0x74;\n    uint16 internal constant I32_SHR_S = 0x75;\n    uint16 internal constant I32_SHR_U = 0x76;\n    uint16 internal constant I32_ROTL = 0x77;\n    uint16 internal constant I32_ROTR = 0x78;\n\n    uint16 internal constant I64_UNOP_BASE = 0x79;\n\n    uint16 internal constant I64_ADD = 0x7C;\n    uint16 internal constant I64_SUB = 0x7D;\n    uint16 internal constant I64_MUL = 0x7E;\n    uint16 internal constant I64_DIV_S = 0x7F;\n    uint16 internal constant I64_DIV_U = 0x80;\n    uint16 internal constant I64_REM_S = 0x81;\n    uint16 internal constant I64_REM_U = 0x82;\n    uint16 internal constant I64_AND = 0x83;\n    uint16 internal constant I64_OR = 0x84;\n    uint16 internal constant I64_XOR = 0x85;\n    uint16 internal constant I64_SHL = 0x86;\n    uint16 internal constant I64_SHR_S = 0x87;\n    uint16 internal constant I64_SHR_U = 0x88;\n    uint16 internal constant I64_ROTL = 0x89;\n    uint16 internal constant I64_ROTR = 0x8A;\n\n    uint16 internal constant I32_WRAP_I64 = 0xA7;\n    uint16 internal constant I64_EXTEND_I32_S = 0xAC;\n    uint16 internal constant I64_EXTEND_I32_U = 0xAD;\n\n    uint16 internal constant I32_REINTERPRET_F32 = 0xBC;\n    uint16 internal constant I64_REINTERPRET_F64 = 0xBD;\n    uint16 internal constant F32_REINTERPRET_I32 = 0xBE;\n    uint16 internal constant F64_REINTERPRET_I64 = 0xBF;\n\n    uint16 internal constant I32_EXTEND_8S = 0xC0;\n    uint16 internal constant I32_EXTEND_16S = 0xC1;\n    uint16 internal constant I64_EXTEND_8S = 0xC2;\n    uint16 internal constant I64_EXTEND_16S = 0xC3;\n    uint16 internal constant I64_EXTEND_32S = 0xC4;\n\n    uint16 internal constant INIT_FRAME = 0x8002;\n    uint16 internal constant ARBITRARY_JUMP = 0x8003;\n    uint16 internal constant ARBITRARY_JUMP_IF = 0x8004;\n    uint16 internal constant MOVE_FROM_STACK_TO_INTERNAL = 0x8005;\n    uint16 internal constant MOVE_FROM_INTERNAL_TO_STACK = 0x8006;\n    uint16 internal constant DUP = 0x8008;\n    uint16 internal constant CROSS_MODULE_CALL = 0x8009;\n    uint16 internal constant CALLER_MODULE_INTERNAL_CALL = 0x800A;\n\n    uint16 internal constant GET_GLOBAL_STATE_BYTES32 = 0x8010;\n    uint16 internal constant SET_GLOBAL_STATE_BYTES32 = 0x8011;\n    uint16 internal constant GET_GLOBAL_STATE_U64 = 0x8012;\n    uint16 internal constant SET_GLOBAL_STATE_U64 = 0x8013;\n\n    uint16 internal constant READ_PRE_IMAGE = 0x8020;\n    uint16 internal constant READ_INBOX_MESSAGE = 0x8021;\n    uint16 internal constant HALT_AND_SET_FINISHED = 0x8022;\n\n    uint256 internal constant INBOX_INDEX_SEQUENCER = 0;\n    uint256 internal constant INBOX_INDEX_DELAYED = 1;\n\n    function hash(Instruction memory inst) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"Instruction:\", inst.opcode, inst.argumentData));\n    }\n}\n"
      },
      "src/state/Machine.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./ValueStack.sol\";\nimport \"./Instructions.sol\";\nimport \"./StackFrame.sol\";\n\nenum MachineStatus {\n    RUNNING,\n    FINISHED,\n    ERRORED,\n    TOO_FAR\n}\n\nstruct Machine {\n    MachineStatus status;\n    ValueStack valueStack;\n    ValueStack internalStack;\n    StackFrameWindow frameStack;\n    bytes32 globalStateHash;\n    uint32 moduleIdx;\n    uint32 functionIdx;\n    uint32 functionPc;\n    bytes32 modulesRoot;\n}\n\nlibrary MachineLib {\n    using StackFrameLib for StackFrameWindow;\n    using ValueStackLib for ValueStack;\n\n    function hash(Machine memory mach) internal pure returns (bytes32) {\n        // Warning: the non-running hashes are replicated in Challenge\n        if (mach.status == MachineStatus.RUNNING) {\n            return\n                keccak256(\n                    abi.encodePacked(\n                        \"Machine running:\",\n                        mach.valueStack.hash(),\n                        mach.internalStack.hash(),\n                        mach.frameStack.hash(),\n                        mach.globalStateHash,\n                        mach.moduleIdx,\n                        mach.functionIdx,\n                        mach.functionPc,\n                        mach.modulesRoot\n                    )\n                );\n        } else if (mach.status == MachineStatus.FINISHED) {\n            return keccak256(abi.encodePacked(\"Machine finished:\", mach.globalStateHash));\n        } else if (mach.status == MachineStatus.ERRORED) {\n            return keccak256(abi.encodePacked(\"Machine errored:\"));\n        } else if (mach.status == MachineStatus.TOO_FAR) {\n            return keccak256(abi.encodePacked(\"Machine too far:\"));\n        } else {\n            revert(\"BAD_MACH_STATUS\");\n        }\n    }\n}\n"
      },
      "src/state/Module.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./ModuleMemoryCompact.sol\";\n\nstruct Module {\n    bytes32 globalsMerkleRoot;\n    ModuleMemory moduleMemory;\n    bytes32 tablesMerkleRoot;\n    bytes32 functionsMerkleRoot;\n    uint32 internalsOffset;\n}\n\nlibrary ModuleLib {\n    using ModuleMemoryCompactLib for ModuleMemory;\n\n    function hash(Module memory mod) internal pure returns (bytes32) {\n        return\n            keccak256(\n                abi.encodePacked(\n                    \"Module:\",\n                    mod.globalsMerkleRoot,\n                    mod.moduleMemory.hash(),\n                    mod.tablesMerkleRoot,\n                    mod.functionsMerkleRoot,\n                    mod.internalsOffset\n                )\n            );\n    }\n}\n"
      },
      "src/state/ModuleMemoryCompact.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nstruct ModuleMemory {\n    uint64 size;\n    uint64 maxSize;\n    bytes32 merkleRoot;\n}\n\nlibrary ModuleMemoryCompactLib {\n    function hash(ModuleMemory memory mem) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"Memory:\", mem.size, mem.maxSize, mem.merkleRoot));\n    }\n}\n"
      },
      "src/state/StackFrame.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./Value.sol\";\n\nstruct StackFrame {\n    Value returnPc;\n    bytes32 localsMerkleRoot;\n    uint32 callerModule;\n    uint32 callerModuleInternals;\n}\n\nstruct StackFrameWindow {\n    StackFrame[] proved;\n    bytes32 remainingHash;\n}\n\nlibrary StackFrameLib {\n    using ValueLib for Value;\n\n    function hash(StackFrame memory frame) internal pure returns (bytes32) {\n        return\n            keccak256(\n                abi.encodePacked(\n                    \"Stack frame:\",\n                    frame.returnPc.hash(),\n                    frame.localsMerkleRoot,\n                    frame.callerModule,\n                    frame.callerModuleInternals\n                )\n            );\n    }\n\n    function hash(StackFrameWindow memory window) internal pure returns (bytes32 h) {\n        h = window.remainingHash;\n        for (uint256 i = 0; i < window.proved.length; i++) {\n            h = keccak256(abi.encodePacked(\"Stack frame stack:\", hash(window.proved[i]), h));\n        }\n    }\n\n    function peek(StackFrameWindow memory window) internal pure returns (StackFrame memory) {\n        require(window.proved.length == 1, \"BAD_WINDOW_LENGTH\");\n        return window.proved[0];\n    }\n\n    function pop(StackFrameWindow memory window) internal pure returns (StackFrame memory frame) {\n        require(window.proved.length == 1, \"BAD_WINDOW_LENGTH\");\n        frame = window.proved[0];\n        window.proved = new StackFrame[](0);\n    }\n\n    function push(StackFrameWindow memory window, StackFrame memory frame) internal pure {\n        StackFrame[] memory newProved = new StackFrame[](window.proved.length + 1);\n        for (uint256 i = 0; i < window.proved.length; i++) {\n            newProved[i] = window.proved[i];\n        }\n        newProved[window.proved.length] = frame;\n        window.proved = newProved;\n    }\n}\n"
      },
      "src/state/Value.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nenum ValueType {\n    I32,\n    I64,\n    F32,\n    F64,\n    REF_NULL,\n    FUNC_REF,\n    INTERNAL_REF\n}\n\nstruct Value {\n    ValueType valueType;\n    uint256 contents;\n}\n\nlibrary ValueLib {\n    function hash(Value memory val) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"Value:\", val.valueType, val.contents));\n    }\n\n    function maxValueType() internal pure returns (ValueType) {\n        return ValueType.INTERNAL_REF;\n    }\n\n    function assumeI32(Value memory val) internal pure returns (uint32) {\n        uint256 uintval = uint256(val.contents);\n        require(val.valueType == ValueType.I32, \"NOT_I32\");\n        require(uintval < (1 << 32), \"BAD_I32\");\n        return uint32(uintval);\n    }\n\n    function assumeI64(Value memory val) internal pure returns (uint64) {\n        uint256 uintval = uint256(val.contents);\n        require(val.valueType == ValueType.I64, \"NOT_I64\");\n        require(uintval < (1 << 64), \"BAD_I64\");\n        return uint64(uintval);\n    }\n\n    function newRefNull() internal pure returns (Value memory) {\n        return Value({valueType: ValueType.REF_NULL, contents: 0});\n    }\n\n    function newI32(uint32 x) internal pure returns (Value memory) {\n        return Value({valueType: ValueType.I32, contents: uint256(x)});\n    }\n\n    function newI64(uint64 x) internal pure returns (Value memory) {\n        return Value({valueType: ValueType.I64, contents: uint256(x)});\n    }\n\n    function newBoolean(bool x) internal pure returns (Value memory) {\n        if (x) {\n            return newI32(uint32(1));\n        } else {\n            return newI32(uint32(0));\n        }\n    }\n}\n"
      },
      "src/state/ValueArray.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./Value.sol\";\n\nstruct ValueArray {\n    Value[] inner;\n}\n\nlibrary ValueArrayLib {\n    function get(ValueArray memory arr, uint256 index) internal pure returns (Value memory) {\n        return arr.inner[index];\n    }\n\n    function set(\n        ValueArray memory arr,\n        uint256 index,\n        Value memory val\n    ) internal pure {\n        arr.inner[index] = val;\n    }\n\n    function length(ValueArray memory arr) internal pure returns (uint256) {\n        return arr.inner.length;\n    }\n\n    function push(ValueArray memory arr, Value memory val) internal pure {\n        Value[] memory newInner = new Value[](arr.inner.length + 1);\n        for (uint256 i = 0; i < arr.inner.length; i++) {\n            newInner[i] = arr.inner[i];\n        }\n        newInner[arr.inner.length] = val;\n        arr.inner = newInner;\n    }\n\n    function pop(ValueArray memory arr) internal pure returns (Value memory popped) {\n        popped = arr.inner[arr.inner.length - 1];\n        Value[] memory newInner = new Value[](arr.inner.length - 1);\n        for (uint256 i = 0; i < newInner.length; i++) {\n            newInner[i] = arr.inner[i];\n        }\n        arr.inner = newInner;\n    }\n}\n"
      },
      "src/state/ValueStack.sol": {
        "content": "// Copyright 2021-2022, Offchain Labs, Inc.\n// For license information, see https://github.com/OffchainLabs/nitro-contracts/blob/main/LICENSE\n// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity ^0.8.0;\n\nimport \"./Value.sol\";\nimport \"./ValueArray.sol\";\n\nstruct ValueStack {\n    ValueArray proved;\n    bytes32 remainingHash;\n}\n\nlibrary ValueStackLib {\n    using ValueLib for Value;\n    using ValueArrayLib for ValueArray;\n\n    function hash(ValueStack memory stack) internal pure returns (bytes32 h) {\n        h = stack.remainingHash;\n        uint256 len = stack.proved.length();\n        for (uint256 i = 0; i < len; i++) {\n            h = keccak256(abi.encodePacked(\"Value stack:\", stack.proved.get(i).hash(), h));\n        }\n    }\n\n    function peek(ValueStack memory stack) internal pure returns (Value memory) {\n        uint256 len = stack.proved.length();\n        return stack.proved.get(len - 1);\n    }\n\n    function pop(ValueStack memory stack) internal pure returns (Value memory) {\n        return stack.proved.pop();\n    }\n\n    function push(ValueStack memory stack, Value memory val) internal pure {\n        return stack.proved.push(val);\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 100
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "metadata": {
        "useLiteralContent": true
      },
      "libraries": {}
    }
  }}