creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "starkware/solidity/interactions/AcceptModifications.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../libraries/LibConstants.sol\";\nimport \"../interfaces/MAcceptModifications.sol\";\nimport \"../interfaces/MTokenQuantization.sol\";\nimport \"../components/MainStorage.sol\";\n\n/*\n  Interface containing actions a verifier can invoke on the state.\n  The contract containing the state should implement these and verify correctness.\n*/\nabstract contract AcceptModifications is\n    MainStorage,\n    LibConstants,\n    MAcceptModifications,\n    MTokenQuantization\n{\n    event LogWithdrawalAllowed(\n        uint256 ownerKey,\n        uint256 assetType,\n        uint256 nonQuantizedAmount,\n        uint256 quantizedAmount\n    );\n\n    event LogNftWithdrawalAllowed(uint256 ownerKey, uint256 assetId);\n\n    event LogAssetWithdrawalAllowed(uint256 ownerKey, uint256 assetId, uint256 quantizedAmount);\n\n    event LogMintableWithdrawalAllowed(uint256 ownerKey, uint256 assetId, uint256 quantizedAmount);\n\n    /*\n      Transfers funds from the on-chain deposit area to the off-chain area.\n      Implemented in the Deposits contracts.\n    */\n    function acceptDeposit(\n        uint256 ownerKey,\n        uint256 vaultId,\n        uint256 assetId,\n        uint256 quantizedAmount\n    ) internal virtual override {\n        // Fetch deposit.\n        require(\n            pendingDeposits[ownerKey][assetId][vaultId] >= quantizedAmount,\n            \"DEPOSIT_INSUFFICIENT\"\n        );\n\n        // Subtract accepted quantized amount.\n        pendingDeposits[ownerKey][assetId][vaultId] -= quantizedAmount;\n    }\n\n    /*\n      Transfers funds from the off-chain area to the on-chain withdrawal area.\n    */\n    function allowWithdrawal(\n        uint256 ownerKey,\n        uint256 assetId,\n        uint256 quantizedAmount\n    ) internal override {\n        // Fetch withdrawal.\n        uint256 withdrawal = pendingWithdrawals[ownerKey][assetId];\n\n        // Add accepted quantized amount.\n        withdrawal += quantizedAmount;\n        require(withdrawal >= quantizedAmount, \"WITHDRAWAL_OVERFLOW\");\n\n        // Store withdrawal.\n        pendingWithdrawals[ownerKey][assetId] = withdrawal;\n\n        // Log event.\n        uint256 presumedAssetType = assetId;\n        if (registeredAssetType[presumedAssetType]) {\n            emit LogWithdrawalAllowed(\n                ownerKey,\n                presumedAssetType,\n                fromQuantized(presumedAssetType, quantizedAmount),\n                quantizedAmount\n            );\n        } else if (\n            assetId ==\n            ((assetId &\n                (MASK_240 | NON_UNIQUE_MINTABLE_ASSET_ID_FLAG | MINTABLE_ERC20_ASSET_ID_FLAG)) |\n                MINTABLE_ASSET_ID_FLAG)\n        ) {\n            emit LogMintableWithdrawalAllowed(ownerKey, assetId, quantizedAmount);\n        } else {\n            // Default case is Non-Mintable ERC721 or ERC1155 asset id.\n            // In ERC721 and ERC1155 cases, assetId is not the assetType.\n            require(assetId == assetId & MASK_250, \"INVALID_ASSET_ID\");\n            // If withdrawal amount is 1, the asset could be either NFT or SFT. In that case, both\n            // NFT and general events will be emitted so that the listened for event is captured.\n            // When withdrawal is greater than 1, it must be SFT and only one event will be emitted.\n            if (withdrawal <= 1) {\n                emit LogNftWithdrawalAllowed(ownerKey, assetId);\n            }\n            emit LogAssetWithdrawalAllowed(ownerKey, assetId, quantizedAmount);\n        }\n    }\n\n    // Verifier authorizes withdrawal.\n    function acceptWithdrawal(\n        uint256 ownerKey,\n        uint256 assetId,\n        uint256 quantizedAmount\n    ) internal virtual override {\n        allowWithdrawal(ownerKey, assetId, quantizedAmount);\n    }\n}\n"
      },
      "starkware/solidity/components/ActionHash.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../components/MainStorage.sol\";\nimport \"../libraries/LibConstants.sol\";\n\n/*\n  Calculation action hash for the various forced actions in a generic manner.\n*/\ncontract ActionHash is MainStorage, LibConstants {\n    function getActionHash(string memory actionName, bytes memory packedActionParameters)\n        internal\n        pure\n        returns (bytes32 actionHash)\n    {\n        actionHash = keccak256(abi.encodePacked(actionName, packedActionParameters));\n    }\n\n    function setActionHash(bytes32 actionHash, bool premiumCost) internal {\n        // The rate of forced trade requests is restricted.\n        // First restriction is by capping the number of requests in a block.\n        // User can override this cap by requesting with a permium flag set,\n        // in this case, the gas cost is high (~1M) but no \"technical\" limit is set.\n        // However, the high gas cost creates an obvious limitation due to the block gas limit.\n        if (premiumCost) {\n            for (uint256 i = 0; i < 21129; i++) {}\n        } else {\n            require(\n                forcedRequestsInBlock[block.number] < MAX_FORCED_ACTIONS_REQS_PER_BLOCK,\n                \"MAX_REQUESTS_PER_BLOCK_REACHED\"\n            );\n            forcedRequestsInBlock[block.number] += 1;\n        }\n        forcedActionRequests[actionHash] = block.timestamp;\n        actionHashList.push(actionHash);\n    }\n\n    function getActionCount() external view returns (uint256) {\n        return actionHashList.length;\n    }\n\n    function getActionHashByIndex(uint256 actionIndex) external view returns (bytes32) {\n        require(actionIndex < actionHashList.length, \"ACTION_INDEX_TOO_HIGH\");\n        return actionHashList[actionIndex];\n    }\n}\n"
      },
      "starkware/solidity/libraries/Addresses.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\n/*\n  Common Utility Libraries.\n  I. Addresses (extending address).\n*/\nlibrary Addresses {\n    /*\n      Note: isContract function has some known limitation.\n      See https://github.com/OpenZeppelin/\n      openzeppelin-contracts/blob/master/contracts/utils/Address.sol.\n    */\n    function isContract(address account) internal view returns (bool) {\n        uint256 size;\n        assembly {\n            size := extcodesize(account)\n        }\n        return size > 0;\n    }\n\n    function performEthTransfer(address recipient, uint256 amount) internal {\n        if (amount == 0) return;\n        (bool success, ) = recipient.call{value: amount}(\"\"); // NOLINT: low-level-calls.\n        require(success, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*\n      Safe wrapper around ERC20/ERC721 calls.\n      This is required because many deployed ERC20 contracts don't return a value.\n      See https://github.com/ethereum/solidity/issues/4116.\n    */\n    function safeTokenContractCall(address tokenAddress, bytes memory callData) internal {\n        require(isContract(tokenAddress), \"BAD_TOKEN_ADDRESS\");\n        // NOLINTNEXTLINE: low-level-calls.\n        (bool success, bytes memory returndata) = tokenAddress.call(callData);\n        require(success, string(returndata));\n\n        if (returndata.length > 0) {\n            require(abi.decode(returndata, (bool)), \"TOKEN_OPERATION_FAILED\");\n        }\n    }\n}\n"
      },
      "starkware/solidity/starkex/components/Escapes.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../../components/MainStorage.sol\";\nimport \"../../libraries/LibConstants.sol\";\nimport \"../../interfaces/MAcceptModifications.sol\";\nimport \"../../interfaces/MFreezable.sol\";\nimport \"../../interfaces/IFactRegistry.sol\";\nimport \"../../interfaces/MStateRoot.sol\";\n\n/**\n  Escaping the exchange is the last resort for users that wish to withdraw their funds without\n  relying on off-chain exchange services. The Escape functionality may only be invoked once the\n  contract has become frozen. This will be as the result of an unserviced full withdraw request\n  (see :sol:mod:`FullWithdrawals`). At that point, any escaper entity may perform an escape\n  operation as follows:\n\n  1. Escapers must obtain a Merkle path of a vault leaf to be evicted with respect to the frozen vault tree root. There are two vault trees: a validium vaults tree and a rollup vaults tree. Rollup vaults data can always be reconstructed from on-chain data. Typically, once the exchange is frozen, validium vaults data will be made public or would be obtainable from an exchange API, depending on the data availability approach used by the exchange.\n  2. Escapers call the :sol:mod:`EscapeVerifier` contract with the Merkle proof for the vault to be evicted. The leaf index for the escape verifier can be computed from the vaultId by clearing the ROLLUP_VAULTS_BIT bit. If the proof is valid, this results in the registration of such proof.\n  3. Escapers call :sol:func:`escape` function with the parameters that constituted the escapeProof submitted to the :sol:mod:`EscapeVerifier` (i.e. the Public Key of the vault owner, full vault ID, asset ID and vault balance). If a proof was accepted for those parameters by the :sol:mod:`EscapeVerifier`, and no prior escape call was made for the vault, the contract adds the vault balance to an on-chain pending withdrawals account under the Public Key of the vault owner and the appropriate asset ID.\n  4. The owner of the vault may then withdraw this amount from the pending withdrawals account by calling the normal withdraw function (see :sol:mod:`Withdrawals`) to transfer the funds to the users Eth or ERC20 account (depending on the token type).\n\n  Note that while anyone can perform the initial steps of the escape operation (including the\n  exchange operator, for example), only the owner of the vault may perform the final step of\n  transferring the funds.\n*/\nabstract contract Escapes is\n    MainStorage,\n    LibConstants,\n    MAcceptModifications,\n    MFreezable,\n    MStateRoot\n{\n    function initialize(address escapeVerifier) internal {\n        escapeVerifierAddress = escapeVerifier;\n    }\n\n    /*\n      Escape when the contract is frozen.\n    */\n    function escape(\n        uint256 ownerKey,\n        uint256 vaultId,\n        uint256 assetId,\n        uint256 quantizedAmount\n    ) external onlyFrozen {\n        require(isVaultInRange(vaultId), \"OUT_OF_RANGE_VAULT_ID\");\n        require(!escapesUsed[vaultId], \"ESCAPE_ALREADY_USED\");\n\n        // Escape can be used only once.\n        escapesUsed[vaultId] = true;\n        escapesUsedCount += 1;\n\n        // Select a vault tree to escape from, based on the vault id.\n        (uint256 root, uint256 treeHeight) = isValidiumVault(vaultId)\n            ? (getValidiumVaultRoot(), getValidiumTreeHeight())\n            : (getRollupVaultRoot(), getRollupTreeHeight());\n\n        // The index of vaultId leaf in its tree doesn't include the rollup bit flag.\n        uint256 vaultLeafIndex = getVaultLeafIndex(vaultId);\n\n        bytes32 claimHash = keccak256(\n            abi.encode(ownerKey, assetId, quantizedAmount, root, treeHeight, vaultLeafIndex)\n        );\n        IFactRegistry escapeVerifier = IFactRegistry(escapeVerifierAddress);\n        require(escapeVerifier.isValid(claimHash), \"ESCAPE_LACKS_PROOF\");\n\n        allowWithdrawal(ownerKey, assetId, quantizedAmount);\n    }\n}\n"
      },
      "starkware/solidity/components/FactRegistry.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../interfaces/IQueryableFactRegistry.sol\";\n\ncontract FactRegistry is IQueryableFactRegistry {\n    // Mapping: fact hash -> true.\n    mapping(bytes32 => bool) private verifiedFact;\n\n    // Indicates whether the Fact Registry has at least one fact registered.\n    bool anyFactRegistered = false;\n\n    /*\n      Checks if a fact was registered.\n    */\n    function isValid(bytes32 fact) external view virtual override returns (bool) {\n        return internalIsValid(fact);\n    }\n\n    /*\n      The internal implementation that checks if the fact was registered.\n    */\n    function internalIsValid(bytes32 fact) internal view virtual returns (bool) {\n        return verifiedFact[fact];\n    }\n\n    function registerFact(bytes32 factHash) internal {\n        // This function stores the fact hash in the mapping.\n        verifiedFact[factHash] = true;\n\n        // Mark first time off.\n        if (!anyFactRegistered) {\n            anyFactRegistered = true;\n        }\n    }\n\n    /*\n      Indicates whether at least one fact was registered.\n    */\n    function hasRegisteredFact() external view override returns (bool) {\n        return anyFactRegistered;\n    }\n}\n"
      },
      "starkware/solidity/components/Freezable.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../libraries/LibConstants.sol\";\nimport \"../interfaces/MFreezable.sol\";\nimport \"../interfaces/MGovernance.sol\";\nimport \"./MainStorage.sol\";\n\n/*\n  Implements MFreezable.\n*/\nabstract contract Freezable is MainStorage, LibConstants, MGovernance, MFreezable {\n    event LogFrozen();\n    event LogUnFrozen();\n\n    function isFrozen() public view override returns (bool) {\n        return stateFrozen;\n    }\n\n    function validateFreezeRequest(uint256 requestTime) internal override {\n        require(requestTime != 0, \"FORCED_ACTION_UNREQUESTED\");\n        // Verify timer on escape request.\n        uint256 freezeTime = requestTime + FREEZE_GRACE_PERIOD;\n\n        // Prevent wraparound.\n        assert(freezeTime >= FREEZE_GRACE_PERIOD);\n        require(block.timestamp >= freezeTime, \"FORCED_ACTION_PENDING\"); // NOLINT: timestamp.\n\n        // Forced action requests placed before freeze, are no longer valid after the un-freeze.\n        require(freezeTime > unFreezeTime, \"REFREEZE_ATTEMPT\");\n    }\n\n    function freeze() internal override notFrozen {\n        unFreezeTime = block.timestamp + UNFREEZE_DELAY;\n\n        // Update state.\n        stateFrozen = true;\n\n        // Log event.\n        emit LogFrozen();\n    }\n\n    function unFreeze() external onlyFrozen onlyGovernance {\n        require(block.timestamp >= unFreezeTime, \"UNFREEZE_NOT_ALLOWED_YET\");\n\n        // Update state.\n        stateFrozen = false;\n\n        // Increment roots to invalidate them, w/o losing information.\n        validiumVaultRoot += 1;\n        rollupVaultRoot += 1;\n        orderRoot += 1;\n\n        // Log event.\n        emit LogUnFrozen();\n    }\n}\n"
      },
      "starkware/solidity/components/Governance.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\nimport \"../interfaces/MGovernance.sol\";\n\n/*\n  Implements Generic Governance, applicable for both proxy and main contract, and possibly others.\n  Notes:\n   The use of the same function names by both the Proxy and a delegated implementation\n   is not possible since calling the implementation functions is done via the default function\n   of the Proxy. For this reason, for example, the implementation of MainContract (MainGovernance)\n   exposes mainIsGovernor, which calls the internal _isGovernor method.\n*/\nstruct GovernanceInfoStruct {\n    mapping(address => bool) effectiveGovernors;\n    address candidateGovernor;\n    bool initialized;\n}\n\nabstract contract Governance is MGovernance {\n    event LogNominatedGovernor(address nominatedGovernor);\n    event LogNewGovernorAccepted(address acceptedGovernor);\n    event LogRemovedGovernor(address removedGovernor);\n    event LogNominationCancelled();\n\n    function getGovernanceInfo() internal view virtual returns (GovernanceInfoStruct storage);\n\n    /*\n      Current code intentionally prevents governance re-initialization.\n      This may be a problem in an upgrade situation, in a case that the upgrade-to implementation\n      performs an initialization (for real) and within that calls initGovernance().\n\n      Possible workarounds:\n      1. Clearing the governance info altogether by changing the MAIN_GOVERNANCE_INFO_TAG.\n         This will remove existing main governance information.\n      2. Modify the require part in this function, so that it will exit quietly\n         when trying to re-initialize (uncomment the lines below).\n    */\n    function initGovernance() internal {\n        GovernanceInfoStruct storage gub = getGovernanceInfo();\n        require(!gub.initialized, \"ALREADY_INITIALIZED\");\n        gub.initialized = true; // to ensure acceptNewGovernor() won't fail.\n        // Add the initial governer.\n        acceptNewGovernor(msg.sender);\n    }\n\n    function _isGovernor(address user) internal view override returns (bool) {\n        GovernanceInfoStruct storage gub = getGovernanceInfo();\n        return gub.effectiveGovernors[user];\n    }\n\n    /*\n      Cancels the nomination of a governor candidate.\n    */\n    function _cancelNomination() internal onlyGovernance {\n        GovernanceInfoStruct storage gub = getGovernanceInfo();\n        if (gub.candidateGovernor != address(0x0)) {\n            gub.candidateGovernor = address(0x0);\n            emit LogNominationCancelled();\n        }\n    }\n\n    function _nominateNewGovernor(address newGovernor) internal onlyGovernance {\n        GovernanceInfoStruct storage gub = getGovernanceInfo();\n        require(newGovernor != address(0x0), \"BAD_ADDRESS\");\n        require(!_isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n        require(gub.candidateGovernor == address(0x0), \"OTHER_CANDIDATE_PENDING\");\n        gub.candidateGovernor = newGovernor;\n        emit LogNominatedGovernor(newGovernor);\n    }\n\n    /*\n      The acceptNewGovernor is called in two cases:\n      1. by _acceptGovernance when a new governor accepts its role.\n      2. by initGovernance to add the initial governor.\n      The difference is that the init path skips the nominate step\n      that would fail because of the onlyGovernance modifier.\n    */\n    function acceptNewGovernor(address newGovernor) private {\n        require(!_isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n        GovernanceInfoStruct storage gub = getGovernanceInfo();\n        gub.effectiveGovernors[newGovernor] = true;\n\n        // Emit governance information.\n        emit LogNewGovernorAccepted(newGovernor);\n    }\n\n    function _acceptGovernance() internal {\n        // The new governor was proposed as a candidate by the current governor.\n        GovernanceInfoStruct storage gub = getGovernanceInfo();\n        require(msg.sender == gub.candidateGovernor, \"ONLY_CANDIDATE_GOVERNOR\");\n\n        // Update state.\n        acceptNewGovernor(msg.sender);\n        gub.candidateGovernor = address(0x0);\n    }\n\n    /*\n      Remove a governor from office.\n    */\n    function _removeGovernor(address governorForRemoval) internal onlyGovernance {\n        require(msg.sender != governorForRemoval, \"GOVERNOR_SELF_REMOVE\");\n        GovernanceInfoStruct storage gub = getGovernanceInfo();\n        require(_isGovernor(governorForRemoval), \"NOT_GOVERNOR\");\n        gub.effectiveGovernors[governorForRemoval] = false;\n        emit LogRemovedGovernor(governorForRemoval);\n    }\n}\n"
      },
      "starkware/solidity/components/GovernanceStorage.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\nimport {GovernanceInfoStruct} from \"./Governance.sol\";\n\n/*\n  Holds the governance slots for ALL entities, including proxy and the main contract.\n*/\ncontract GovernanceStorage {\n    // A map from a Governor tag to its own GovernanceInfoStruct.\n    mapping(string => GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state.\n}\n"
      },
      "starkware/solidity/interfaces/IFactRegistry.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\n/*\n  The Fact Registry design pattern is a way to separate cryptographic verification from the\n  business logic of the contract flow.\n\n  A fact registry holds a hash table of verified \"facts\" which are represented by a hash of claims\n  that the registry hash check and found valid. This table may be queried by accessing the\n  isValid() function of the registry with a given hash.\n\n  In addition, each fact registry exposes a registry specific function for submitting new claims\n  together with their proofs. The information submitted varies from one registry to the other\n  depending of the type of fact requiring verification.\n\n  For further reading on the Fact Registry design pattern see this\n  `StarkWare blog post <https://medium.com/starkware/the-fact-registry-a64aafb598b6>`_.\n*/\ninterface IFactRegistry {\n    /*\n      Returns true if the given fact was previously registered in the contract.\n    */\n    function isValid(bytes32 fact) external view returns (bool);\n}\n"
      },
      "starkware/solidity/interfaces/IQueryableFactRegistry.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"./IFactRegistry.sol\";\n\n/*\n  Extends the IFactRegistry interface with a query method that indicates\n  whether the fact registry has successfully registered any fact or is still empty of such facts.\n*/\ninterface IQueryableFactRegistry is IFactRegistry {\n    /*\n      Returns true if at least one fact has been registered.\n    */\n    function hasRegisteredFact() external view returns (bool);\n}\n"
      },
      "starkware/solidity/interfaces/Identity.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\ninterface Identity {\n    /*\n      Allows a caller to ensure that the provided address is of the expected type and version.\n    */\n    function identify() external pure returns (string memory);\n}\n"
      },
      "starkware/solidity/libraries/LibConstants.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\ncontract LibConstants {\n    // Durations for time locked mechanisms (in seconds).\n    // Note that it is known that miners can manipulate block timestamps\n    // up to a deviation of a few seconds.\n    // This mechanism should not be used for fine grained timing.\n\n    // The time required to cancel a deposit, in the case the operator does not move the funds\n    // to the off-chain storage.\n    uint256 public constant DEPOSIT_CANCEL_DELAY = 2 days;\n\n    // The time required to freeze the exchange, in the case the operator does not execute a\n    // requested full withdrawal.\n    uint256 public constant FREEZE_GRACE_PERIOD = 7 days;\n\n    // The time after which the exchange may be unfrozen after it froze. This should be enough time\n    // for users to perform escape hatches to get back their funds.\n    uint256 public constant UNFREEZE_DELAY = 365 days;\n\n    // Maximal number of verifiers which may co-exist.\n    uint256 public constant MAX_VERIFIER_COUNT = uint256(64);\n\n    // The time required to remove a verifier in case of a verifier upgrade.\n    uint256 public constant VERIFIER_REMOVAL_DELAY = FREEZE_GRACE_PERIOD + (21 days);\n\n    address constant ZERO_ADDRESS = address(0x0);\n\n    uint256 constant K_MODULUS = 0x800000000000011000000000000000000000000000000000000000000000001;\n\n    uint256 constant K_BETA = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89;\n\n    uint256 internal constant MASK_250 =\n        0x03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n    uint256 internal constant MASK_240 =\n        0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n    uint256 public constant MAX_FORCED_ACTIONS_REQS_PER_BLOCK = 10;\n\n    uint256 constant QUANTUM_UPPER_BOUND = 2**128;\n\n    // All mintable asset ids have the MINTABLE_ASSET_ID_FLAG (251st bit) set.\n    // Mintable ERC1155 and ERC20 assets have NON_UNIQUE_MINTABLE_ASSET_ID_FLAG (250th bit) set too.\n    // Mintable ERC20s also have the MINTABLE_ERC20_ASSET_ID_FLAG (249th bit) set.\n    // I.e. mintable asset ids that start with: 100 => ERC721, 110 => ERC1155, 111 => ERC20.\n    // All non-mintable asset ids have the MINTABLE_ASSET_ID_FLAG bit off.\n    uint256 internal constant MINTABLE_ASSET_ID_FLAG = 1 << 250;\n    uint256 internal constant NON_UNIQUE_MINTABLE_ASSET_ID_FLAG = 1 << 249;\n    uint256 internal constant MINTABLE_ERC20_ASSET_ID_FLAG = 1 << 248;\n\n    // Bit 64 (indexed 63, counting from 0) is a flag indicating a rollup vault id.\n    uint256 constant ROLLUP_VAULTS_BIT = 63;\n}\n"
      },
      "starkware/solidity/interfaces/MAcceptModifications.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/*\n  Interface containing actions a verifier can invoke on the state.\n  The contract containing the state should implement these and verify correctness.\n*/\nabstract contract MAcceptModifications {\n    function acceptDeposit(\n        uint256 ownerKey,\n        uint256 vaultId,\n        uint256 assetId,\n        uint256 quantizedAmount\n    ) internal virtual;\n\n    function allowWithdrawal(\n        uint256 ownerKey,\n        uint256 assetId,\n        uint256 quantizedAmount\n    ) internal virtual;\n\n    function acceptWithdrawal(\n        uint256 ownerKey,\n        uint256 assetId,\n        uint256 quantizedAmount\n    ) internal virtual;\n}\n"
      },
      "starkware/solidity/interfaces/MFreezable.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nabstract contract MFreezable {\n    /*\n      Returns true if the exchange is frozen.\n    */\n    function isFrozen() public view virtual returns (bool); // NOLINT: external-function.\n\n    /*\n      Forbids calling the function if the exchange is frozen.\n    */\n    modifier notFrozen() {\n        require(!isFrozen(), \"STATE_IS_FROZEN\");\n        _;\n    }\n\n    function validateFreezeRequest(uint256 requestTime) internal virtual;\n\n    /*\n      Allows calling the function only if the exchange is frozen.\n    */\n    modifier onlyFrozen() {\n        require(isFrozen(), \"STATE_NOT_FROZEN\");\n        _;\n    }\n\n    /*\n      Freezes the exchange.\n    */\n    function freeze() internal virtual;\n}\n"
      },
      "starkware/solidity/interfaces/MGovernance.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\nabstract contract MGovernance {\n    function _isGovernor(address user) internal view virtual returns (bool);\n\n    /*\n      Allows calling the function only by a Governor.\n    */\n    modifier onlyGovernance() {\n        require(_isGovernor(msg.sender), \"ONLY_GOVERNANCE\");\n        _;\n    }\n}\n"
      },
      "starkware/solidity/interfaces/MOperator.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\nimport \"./MGovernance.sol\";\n\nabstract contract MOperator {\n    event LogOperatorAdded(address operator);\n    event LogOperatorRemoved(address operator);\n\n    function isOperator(address user) public view virtual returns (bool);\n\n    modifier onlyOperator() {\n        require(isOperator(msg.sender), \"ONLY_OPERATOR\");\n        _;\n    }\n\n    function registerOperator(address newOperator) external virtual;\n\n    function unregisterOperator(address removedOperator) external virtual;\n\n    function getOperators() internal view virtual returns (mapping(address => bool) storage);\n}\n"
      },
      "starkware/solidity/starkex/interfaces/MStarkExForcedActionState.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nabstract contract MStarkExForcedActionState {\n    function fullWithdrawActionHash(uint256 ownerKey, uint256 vaultId)\n        internal\n        pure\n        virtual\n        returns (bytes32);\n\n    function clearFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal virtual;\n\n    // NOLINTNEXTLINE: external-function.\n    function getFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId)\n        public\n        view\n        virtual\n        returns (uint256);\n\n    function setFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal virtual;\n}\n"
      },
      "starkware/solidity/interfaces/MStateRoot.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nabstract contract MStateRoot {\n    function getValidiumVaultRoot() public view virtual returns (uint256);\n\n    function getValidiumTreeHeight() public view virtual returns (uint256);\n\n    function getRollupVaultRoot() public view virtual returns (uint256);\n\n    function getRollupTreeHeight() public view virtual returns (uint256);\n\n    /*\n      Returns true iff vaultId is in the valid vault ids range,\n      i.e. could appear in either the validium or rollup vaults trees.\n    */\n    function isVaultInRange(uint256 vaultId) internal view virtual returns (bool);\n\n    /*\n      Returns true if vaultId is a valid validium vault id.\n\n      Note: when this function returns false it might mean that vaultId is invalid and does not\n      guarantee that vaultId is a valid rollup vault id.\n    */\n    function isValidiumVault(uint256 vaultId) internal view virtual returns (bool);\n\n    /*\n      Returns true if vaultId is a valid rollup vault id.\n\n      Note: when this function returns false it might mean that vaultId is invalid and does not\n      guarantee that vaultId is a valid validium vault id.\n    */\n    function isRollupVault(uint256 vaultId) internal view virtual returns (bool);\n\n    /*\n      Given a valid vaultId, returns its leaf index in the validium/rollup tree.\n\n      Note: this function does not assert the validity of vaultId, make sure to explicitly assert it\n      when required.\n    */\n    function getVaultLeafIndex(uint256 vaultId) internal pure virtual returns (uint256);\n}\n"
      },
      "starkware/solidity/interfaces/MTokenQuantization.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nabstract contract MTokenQuantization {\n    function fromQuantized(uint256 presumedAssetType, uint256 quantizedAmount)\n        internal\n        view\n        virtual\n        returns (uint256 amount);\n\n    // NOLINTNEXTLINE: external-function.\n    function getQuantum(uint256 presumedAssetType) public view virtual returns (uint256 quantum);\n\n    function toQuantized(uint256 presumedAssetType, uint256 amount)\n        internal\n        view\n        virtual\n        returns (uint256 quantizedAmount);\n}\n"
      },
      "starkware/solidity/components/MainGovernance.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"./Governance.sol\";\nimport \"./GovernanceStorage.sol\";\n\n/**\n  The StarkEx contract is governed by one or more Governors of which the initial one is the\n  deployer of the contract.\n\n  A governor has the sole authority to perform the following operations:\n\n  1. Nominate additional governors (:sol:func:`mainNominateNewGovernor`)\n  2. Remove other governors (:sol:func:`mainRemoveGovernor`)\n  3. Add new :sol:mod:`Verifiers` and :sol:mod:`AvailabilityVerifiers`\n  4. Remove :sol:mod:`Verifiers` and :sol:mod:`AvailabilityVerifiers` after a timelock allows it\n  5. Nominate Operators (see :sol:mod:`Operator`) and Token Administrators (see :sol:mod:`TokenRegister`)\n\n  Adding governors is performed in a two step procedure:\n\n  1. First, an existing governor nominates a new governor (:sol:func:`mainNominateNewGovernor`)\n  2. Then, the new governor must accept governance to become a governor (:sol:func:`mainAcceptGovernance`)\n\n  This two step procedure ensures that a governor public key cannot be nominated unless there is an\n  entity that has the corresponding private key. This is intended to prevent errors in the addition\n  process.\n\n  The governor private key should typically be held in a secure cold wallet.\n*/\n/*\n  Implements Governance for the StarkDex main contract.\n  The wrapper methods (e.g. mainIsGovernor wrapping _isGovernor) are needed to give\n  the method unique names.\n  Both Proxy and StarkExchange inherit from Governance. Thus, the logical contract method names\n  must have unique names in order for the proxy to successfully delegate to them.\n*/\ncontract MainGovernance is GovernanceStorage, Governance {\n    // The tag is the sting key that is used in the Governance storage mapping.\n    string public constant MAIN_GOVERNANCE_INFO_TAG = \"StarkEx.Main.2019.GovernorsInformation\";\n\n    /*\n      Returns the GovernanceInfoStruct associated with the governance tag.\n    */\n    function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) {\n        return governanceInfo[MAIN_GOVERNANCE_INFO_TAG];\n    }\n\n    function mainIsGovernor(address user) external view returns (bool) {\n        return _isGovernor(user);\n    }\n\n    function mainNominateNewGovernor(address newGovernor) external {\n        _nominateNewGovernor(newGovernor);\n    }\n\n    function mainRemoveGovernor(address governorForRemoval) external {\n        _removeGovernor(governorForRemoval);\n    }\n\n    function mainAcceptGovernance() external {\n        _acceptGovernance();\n    }\n\n    function mainCancelNomination() external {\n        _cancelNomination();\n    }\n}\n"
      },
      "starkware/solidity/components/MainStorage.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../upgrade/ProxyStorage.sol\";\nimport \"../libraries/Addresses.sol\";\nimport {ApprovalChainData} from \"../libraries/StarkExTypes.sol\";\n\n/*\n  Holds ALL the main contract state (storage) variables.\n*/\ncontract MainStorage is ProxyStorage {\n    uint256 internal constant LAYOUT_LENGTH = 2**64;\n\n    address escapeVerifierAddress; // NOLINT: constable-states.\n\n    // Global dex-frozen flag.\n    bool stateFrozen; // NOLINT: constable-states.\n\n    // Time when unFreeze can be successfully called (UNFREEZE_DELAY after freeze).\n    uint256 unFreezeTime; // NOLINT: constable-states.\n\n    // Pending deposits.\n    // A map STARK key => asset id => vault id => quantized amount.\n    mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) pendingDeposits;\n\n    // Cancellation requests.\n    // A map STARK key => asset id => vault id => request timestamp.\n    mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) cancellationRequests;\n\n    // Pending withdrawals.\n    // A map STARK key => asset id => quantized amount.\n    mapping(uint256 => mapping(uint256 => uint256)) pendingWithdrawals;\n\n    // vault_id => escape used boolean.\n    mapping(uint256 => bool) escapesUsed;\n\n    // Number of escapes that were performed when frozen.\n    uint256 escapesUsedCount; // NOLINT: constable-states.\n\n    // NOTE: fullWithdrawalRequests is deprecated, and replaced by forcedActionRequests.\n    // NOLINTNEXTLINE naming-convention.\n    mapping(uint256 => mapping(uint256 => uint256)) fullWithdrawalRequests_DEPRECATED;\n\n    // State sequence number.\n    uint256 sequenceNumber; // NOLINT: constable-states uninitialized-state.\n\n    // Validium Vaults Tree Root & Height.\n    uint256 validiumVaultRoot; // NOLINT: constable-states uninitialized-state.\n    uint256 validiumTreeHeight; // NOLINT: constable-states uninitialized-state.\n\n    // Order Tree Root & Height.\n    uint256 orderRoot; // NOLINT: constable-states uninitialized-state.\n    uint256 orderTreeHeight; // NOLINT: constable-states uninitialized-state.\n\n    // True if and only if the address is allowed to add tokens.\n    mapping(address => bool) tokenAdmins;\n\n    // This mapping is no longer in use, remains for backwards compatibility.\n    mapping(address => bool) userAdmins_DEPRECATED; // NOLINT: naming-convention.\n\n    // True if and only if the address is an operator (allowed to update state).\n    mapping(address => bool) operators; // NOLINT: uninitialized-state.\n\n    // Mapping of contract ID to asset data.\n    mapping(uint256 => bytes) assetTypeToAssetInfo; // NOLINT: uninitialized-state.\n\n    // Mapping of registered contract IDs.\n    mapping(uint256 => bool) registeredAssetType; // NOLINT: uninitialized-state.\n\n    // Mapping from contract ID to quantum.\n    mapping(uint256 => uint256) assetTypeToQuantum; // NOLINT: uninitialized-state.\n\n    // This mapping is no longer in use, remains for backwards compatibility.\n    mapping(address => uint256) starkKeys_DEPRECATED; // NOLINT: naming-convention.\n\n    // Mapping from STARK public key to the Ethereum public key of its owner.\n    mapping(uint256 => address) ethKeys; // NOLINT: uninitialized-state.\n\n    // Timelocked state transition and availability verification chain.\n    ApprovalChainData verifiersChain;\n    ApprovalChainData availabilityVerifiersChain;\n\n    // Batch id of last accepted proof.\n    uint256 lastBatchId; // NOLINT: constable-states uninitialized-state.\n\n    // Mapping between sub-contract index to sub-contract address.\n    mapping(uint256 => address) subContracts; // NOLINT: uninitialized-state.\n\n    mapping(uint256 => bool) permissiveAssetType_DEPRECATED; // NOLINT: naming-convention.\n    // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX2.0 ----\n\n    // Onchain-data version configured for the system.\n    uint256 onchainDataVersion_DEPRECATED; // NOLINT: naming-convention constable-states.\n\n    // Counter of forced action request in block. The key is the block number.\n    mapping(uint256 => uint256) forcedRequestsInBlock;\n\n    // ForcedAction requests: actionHash => requestTime.\n    mapping(bytes32 => uint256) forcedActionRequests;\n\n    // Mapping for timelocked actions.\n    // A actionKey => activation time.\n    mapping(bytes32 => uint256) actionsTimeLock;\n\n    // Append only list of requested forced action hashes.\n    bytes32[] actionHashList;\n    // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX3.0 ----\n    // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX4.0 ----\n\n    // Rollup Vaults Tree Root & Height.\n    uint256 rollupVaultRoot; // NOLINT: constable-states uninitialized-state.\n    uint256 rollupTreeHeight; // NOLINT: constable-states uninitialized-state.\n\n    uint256 globalConfigCode; // NOLINT: constable-states uninitialized-state.\n\n    // Reserved storage space for Extensibility.\n    // Every added MUST be added above the end gap, and the __endGap size must be reduced\n    // accordingly.\n    // NOLINTNEXTLINE: naming-convention.\n    uint256[LAYOUT_LENGTH - 40] private __endGap; // __endGap complements layout to LAYOUT_LENGTH.\n}\n"
      },
      "starkware/solidity/components/MessageRegistry.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../interfaces/Identity.sol\";\nimport \"./FactRegistry.sol\";\n\ncontract MessageRegistry is FactRegistry, Identity {\n    event LogMsgRegistered(address from, address to, bytes32 msgHash);\n\n    function identify() external pure virtual override returns (string memory) {\n        return \"StarkWare_MessageRegistry_2021_1\";\n    }\n\n    // NOLINTNEXTLINE: external-function.\n    function registerMessage(address to, bytes32 messageHash) public {\n        bytes32 messageFact = keccak256(abi.encodePacked(msg.sender, to, messageHash));\n        registerFact(messageFact);\n        emit LogMsgRegistered(msg.sender, to, messageHash);\n    }\n\n    function isMessageRegistered(\n        address from,\n        address to,\n        bytes32 messageHash\n    ) external view returns (bool) {\n        bytes32 messageFact = keccak256(abi.encodePacked(from, to, messageHash));\n        return internalIsValid(messageFact);\n    }\n}\n"
      },
      "starkware/solidity/components/OnchainDataFactTreeEncoder.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\nlibrary OnchainDataFactTreeEncoder {\n    struct DataAvailabilityFact {\n        uint256 onchainDataHash;\n        uint256 onchainDataSize;\n    }\n\n    // The number of additional words appended to the public input when using the\n    // OnchainDataFactTreeEncoder format.\n    uint256 internal constant ONCHAIN_DATA_FACT_ADDITIONAL_WORDS = 2;\n\n    /*\n      Encodes a GPS fact Merkle tree where the root has two children.\n      The left child contains the data we care about and the right child contains\n      on-chain data for the fact.\n    */\n    function encodeFactWithOnchainData(\n        uint256[] calldata programOutput,\n        DataAvailabilityFact memory factData\n    ) internal pure returns (bytes32) {\n        // The state transition fact is computed as a Merkle tree, as defined in\n        // GpsOutputParser.\n        //\n        // In our case the fact tree looks as follows:\n        //   The root has two children.\n        //   The left child is a leaf that includes the main part - the information regarding\n        //   the state transition required by this contract.\n        //   The right child contains the onchain-data which shouldn't be accessed by this\n        //   contract, so we are only given its hash and length\n        //   (it may be a leaf or an inner node, this has no effect on this contract).\n\n        // Compute the hash without the two additional fields.\n        uint256 mainPublicInputLen = programOutput.length;\n        bytes32 mainPublicInputHash = hashMainPublicInput(programOutput);\n\n        // Compute the hash of the fact Merkle tree.\n        bytes32 hashResult = keccak256(\n            abi.encodePacked(\n                mainPublicInputHash,\n                mainPublicInputLen,\n                factData.onchainDataHash,\n                mainPublicInputLen + factData.onchainDataSize\n            )\n        );\n        // Add one to the hash to indicate it represents an inner node, rather than a leaf.\n        return bytes32(uint256(hashResult) + 1);\n    }\n\n    /*\n      Hashes the main public input.\n    */\n    function hashMainPublicInput(uint256[] calldata programOutput) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(programOutput));\n    }\n}\n"
      },
      "starkware/solidity/components/Operator.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity >=0.6.12;\n\nimport \"../interfaces/MOperator.sol\";\nimport \"../interfaces/MGovernance.sol\";\n\n/**\n  The Operator of the contract is the entity entitled to submit state update requests\n  by calling :sol:func:`updateState`.\n\n  An Operator may be instantly appointed or removed by the contract Governor\n  (see :sol:mod:`Governance`). Typically, the Operator is the hot wallet of the service\n  submitting proofs for state updates.\n*/\nabstract contract Operator is MGovernance, MOperator {\n    function registerOperator(address newOperator) external override onlyGovernance {\n        if (!isOperator(newOperator)) {\n            getOperators()[newOperator] = true;\n            emit LogOperatorAdded(newOperator);\n        }\n    }\n\n    function unregisterOperator(address removedOperator) external override onlyGovernance {\n        if (isOperator(removedOperator)) {\n            getOperators()[removedOperator] = false;\n            emit LogOperatorRemoved(removedOperator);\n        }\n    }\n\n    function isOperator(address user) public view override returns (bool) {\n        return getOperators()[user];\n    }\n}\n"
      },
      "starkware/solidity/upgrade/ProxyStorage.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../components/GovernanceStorage.sol\";\n\n/*\n  Holds the Proxy-specific state variables.\n  This contract is inherited by the GovernanceStorage (and indirectly by MainStorage)\n  to prevent collision hazard.\n*/\ncontract ProxyStorage is GovernanceStorage {\n    // NOLINTNEXTLINE: naming-convention uninitialized-state.\n    mapping(address => bytes32) internal initializationHash_DEPRECATED;\n\n    // The time after which we can switch to the implementation.\n    // Hash(implementation, data, finalize) => time.\n    mapping(bytes32 => uint256) internal enabledTime;\n\n    // A central storage of the flags whether implementation has been initialized.\n    // Note - it can be used flexibly enough to accommodate multiple levels of initialization\n    // (i.e. using different key salting schemes for different initialization levels).\n    mapping(bytes32 => bool) internal initialized;\n}\n"
      },
      "starkware/solidity/starkex/PublicInputOffsets.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\ncontract PublicInputOffsets {\n    // The following constants are offsets of data expected in the public input.\n    uint256 internal constant PUB_IN_GLOBAL_CONFIG_CODE_OFFSET = 0;\n    uint256 internal constant PUB_IN_INITIAL_VALIDIUM_VAULT_ROOT_OFFSET = 1;\n    uint256 internal constant PUB_IN_FINAL_VALIDIUM_VAULT_ROOT_OFFSET = 2;\n    uint256 internal constant PUB_IN_INITIAL_ROLLUP_VAULT_ROOT_OFFSET = 3;\n    uint256 internal constant PUB_IN_FINAL_ROLLUP_VAULT_ROOT_OFFSET = 4;\n    uint256 internal constant PUB_IN_INITIAL_ORDER_ROOT_OFFSET = 5;\n    uint256 internal constant PUB_IN_FINAL_ORDER_ROOT_OFFSET = 6;\n    uint256 internal constant PUB_IN_GLOBAL_EXPIRATION_TIMESTAMP_OFFSET = 7;\n    uint256 internal constant PUB_IN_VALIDIUM_VAULT_TREE_HEIGHT_OFFSET = 8;\n    uint256 internal constant PUB_IN_ROLLUP_VAULT_TREE_HEIGHT_OFFSET = 9;\n    uint256 internal constant PUB_IN_ORDER_TREE_HEIGHT_OFFSET = 10;\n    uint256 internal constant PUB_IN_N_MODIFICATIONS_OFFSET = 11;\n    uint256 internal constant PUB_IN_N_CONDITIONAL_TRANSFERS_OFFSET = 12;\n    uint256 internal constant PUB_IN_N_ONCHAIN_VAULT_UPDATES_OFFSET = 13;\n    uint256 internal constant PUB_IN_N_ONCHAIN_ORDERS_OFFSET = 14;\n    uint256 internal constant PUB_IN_TRANSACTIONS_DATA_OFFSET = 15;\n\n    uint256 internal constant PUB_IN_N_WORDS_PER_MODIFICATION = 3;\n    uint256 internal constant PUB_IN_N_WORDS_PER_CONDITIONAL_TRANSFER = 1;\n    uint256 internal constant PUB_IN_N_WORDS_PER_ONCHAIN_VAULT_UPDATE = 3;\n    uint256 internal constant PUB_IN_N_MIN_WORDS_PER_ONCHAIN_ORDER = 3;\n\n    // The following constants are offsets of data expected in the application data.\n    uint256 internal constant APP_DATA_BATCH_ID_OFFSET = 0;\n    uint256 internal constant APP_DATA_PREVIOUS_BATCH_ID_OFFSET = 1;\n    uint256 internal constant APP_DATA_TRANSACTIONS_DATA_OFFSET = 2;\n\n    uint256 internal constant APP_DATA_N_WORDS_PER_CONDITIONAL_TRANSFER = 2;\n}\n"
      },
      "starkware/solidity/starkex/StarkExConstants.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../libraries/LibConstants.sol\";\n\ncontract StarkExConstants is LibConstants {\n    uint256 constant STARKEX_EXPIRATION_TIMESTAMP_BITS = 22;\n    uint256 public constant STARKEX_MAX_DEFAULT_VAULT_LOCK = 7 days;\n}\n"
      },
      "starkware/solidity/starkex/interactions/StarkExForcedActionState.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../components/StarkExStorage.sol\";\nimport \"../interfaces/MStarkExForcedActionState.sol\";\nimport \"../../components/ActionHash.sol\";\n\n/*\n  StarkExchange specific action hashses.\n*/\ncontract StarkExForcedActionState is StarkExStorage, ActionHash, MStarkExForcedActionState {\n    function fullWithdrawActionHash(uint256 ownerKey, uint256 vaultId)\n        internal\n        pure\n        override\n        returns (bytes32)\n    {\n        return getActionHash(\"FULL_WITHDRAWAL\", abi.encode(ownerKey, vaultId));\n    }\n\n    /*\n      Implemented in the FullWithdrawal contracts.\n    */\n    function clearFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId)\n        internal\n        virtual\n        override\n    {\n        // Reset escape request.\n        delete forcedActionRequests[fullWithdrawActionHash(ownerKey, vaultId)];\n    }\n\n    function getFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId)\n        public\n        view\n        override\n        returns (uint256)\n    {\n        // Return request value. Expect zero if the request doesn't exist or has been serviced, and\n        // a non-zero value otherwise.\n        return forcedActionRequests[fullWithdrawActionHash(ownerKey, vaultId)];\n    }\n\n    function setFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal override {\n        // FullWithdrawal is always at premium cost, hence the `true`.\n        setActionHash(fullWithdrawActionHash(ownerKey, vaultId), true);\n    }\n}\n"
      },
      "starkware/solidity/components/StarkExOperator.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"./Operator.sol\";\nimport \"./MainStorage.sol\";\n\n/**\n  Operator implementation for StarkEx (StarkExchange & StarkPerpetual).\n*/\nabstract contract StarkExOperator is MainStorage, Operator {\n    function initialize() internal {\n        getOperators()[msg.sender] = true;\n        emit LogOperatorAdded(msg.sender);\n    }\n\n    function getOperators() internal view override returns (mapping(address => bool) storage) {\n        return operators;\n    }\n}\n"
      },
      "starkware/solidity/starkex/toplevel_subcontracts/StarkExState.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../components/Escapes.sol\";\nimport \"../interactions/StarkExForcedActionState.sol\";\nimport \"../interactions/UpdateState.sol\";\nimport \"../../components/Freezable.sol\";\nimport \"../../components/MainGovernance.sol\";\nimport \"../../components/StarkExOperator.sol\";\nimport \"../../interactions/AcceptModifications.sol\";\nimport \"../../interactions/StateRoot.sol\";\nimport \"../../interactions/TokenQuantization.sol\";\nimport \"../../interfaces/SubContractor.sol\";\n\ncontract StarkExState is\n    MainGovernance,\n    SubContractor,\n    StarkExOperator,\n    Freezable,\n    AcceptModifications,\n    TokenQuantization,\n    StarkExForcedActionState,\n    StateRoot,\n    Escapes,\n    UpdateState\n{\n    // InitializationArgStruct contains 2 * address + 8 * uint256 + 1 * bool = 352 bytes.\n    uint256 constant INITIALIZER_SIZE = 11 * 32;\n\n    struct InitializationArgStruct {\n        uint256 globalConfigCode;\n        address escapeVerifierAddress;\n        uint256 sequenceNumber;\n        uint256 validiumVaultRoot;\n        uint256 rollupVaultRoot;\n        uint256 orderRoot;\n        uint256 validiumTreeHeight;\n        uint256 rollupTreeHeight;\n        uint256 orderTreeHeight;\n        bool strictVaultBalancePolicy;\n        address orderRegistryAddress;\n    }\n\n    /*\n      Initialization flow:\n      1. Extract initialization parameters from data.\n      2. Call internalInitializer with those parameters.\n    */\n    function initialize(bytes calldata data) external virtual override {\n        // This initializer sets roots etc. It must not be applied twice.\n        // I.e. it can run only when the state is still empty.\n        string memory ALREADY_INITIALIZED_MSG = \"STATE_ALREADY_INITIALIZED\";\n        require(validiumVaultRoot == 0, ALREADY_INITIALIZED_MSG);\n        require(validiumTreeHeight == 0, ALREADY_INITIALIZED_MSG);\n        require(rollupVaultRoot == 0, ALREADY_INITIALIZED_MSG);\n        require(rollupTreeHeight == 0, ALREADY_INITIALIZED_MSG);\n        require(orderRoot == 0, ALREADY_INITIALIZED_MSG);\n        require(orderTreeHeight == 0, ALREADY_INITIALIZED_MSG);\n\n        require(data.length == INITIALIZER_SIZE, \"INCORRECT_INIT_DATA_SIZE_352\");\n\n        // Copies initializer values into initValues.\n        InitializationArgStruct memory initValues;\n        bytes memory _data = data;\n        assembly {\n            initValues := add(32, _data)\n        }\n        require(initValues.globalConfigCode < K_MODULUS, \"GLOBAL_CONFIG_CODE >= PRIME\");\n        require(initValues.validiumTreeHeight < ROLLUP_VAULTS_BIT, \"INVALID_VALIDIUM_HEIGHT\");\n        require(initValues.rollupTreeHeight < ROLLUP_VAULTS_BIT, \"INVALID_ROLLUP_HEIGHT\");\n\n        initGovernance();\n        StarkExOperator.initialize();\n        StateRoot.initialize(\n            initValues.sequenceNumber,\n            initValues.validiumVaultRoot,\n            initValues.rollupVaultRoot,\n            initValues.orderRoot,\n            initValues.validiumTreeHeight,\n            initValues.rollupTreeHeight,\n            initValues.orderTreeHeight\n        );\n        Escapes.initialize(initValues.escapeVerifierAddress);\n        globalConfigCode = initValues.globalConfigCode;\n        strictVaultBalancePolicy = initValues.strictVaultBalancePolicy;\n        orderRegistryAddress = initValues.orderRegistryAddress;\n    }\n\n    /*\n      The call to initializerSize is done from MainDispatcherBase using delegatecall,\n      thus the existing state is already accessible.\n    */\n    function initializerSize() external view virtual override returns (uint256) {\n        return INITIALIZER_SIZE;\n    }\n\n    function validatedSelectors() external pure override returns (bytes4[] memory selectors) {\n        uint256 len_ = 1;\n        uint256 index_ = 0;\n\n        selectors = new bytes4[](len_);\n        selectors[index_++] = Escapes.escape.selector;\n        require(index_ == len_, \"INCORRECT_SELECTORS_ARRAY_LENGTH\");\n    }\n\n    function identify() external pure override returns (string memory) {\n        return \"StarkWare_StarkExState_2022_5\";\n    }\n}\n"
      },
      "starkware/solidity/starkex/components/StarkExStorage.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../../components/MainStorage.sol\";\n\n/*\n  Extends MainStorage, holds StarkEx App specific state (storage) variables.\n\n  ALL State variables that are common to all applications, reside in MainStorage,\n  whereas ALL the StarkEx app specific ones reside here.\n*/\ncontract StarkExStorage is MainStorage {\n    // Onchain vaults balances.\n    // A map eth_address => asset_id => vault_id => quantized amount.\n    mapping(address => mapping(uint256 => mapping(uint256 => uint256))) vaultsBalances;\n\n    // Onchain vaults withdrawal lock time.\n    // A map eth_address => asset_id => vault_id => lock expiration timestamp.\n    mapping(address => mapping(uint256 => mapping(uint256 => uint256))) vaultsWithdrawalLocks;\n\n    // Enforces the minimal balance requirement (as output by Cairo) on onchain vault updates.\n    // When disabled, flash loans are enabled.\n    bool strictVaultBalancePolicy; // NOLINT: constable-states, uninitialized-state.\n\n    // The default time, in seconds, that an onchain vault is locked for withdrawal after a deposit.\n    uint256 public defaultVaultWithdrawalLock; // NOLINT: constable-states.\n\n    // Address of the message registry contract that is used to sign and verify L1 orders.\n    address public orderRegistryAddress; // NOLINT: constable-states.\n\n    // Reserved storage space for Extensibility.\n    // Every added MUST be added above the end gap, and the __endGap size must be reduced\n    // accordingly.\n    // NOLINTNEXTLINE: naming-convention shadowing-abstract.\n    uint256[LAYOUT_LENGTH - 5] private __endGap; // __endGap complements layout to LAYOUT_LENGTH.\n}\n"
      },
      "starkware/solidity/libraries/StarkExTypes.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n// Structure representing a list of verifiers (validity/availability).\n// A statement is valid only if all the verifiers in the list agree on it.\n// Adding a verifier to the list is immediate - this is used for fast resolution of\n// any soundness issues.\n// Removing a verifier from the list is time-locked, to ensure that any user of the system\n// not content with the announced removal has ample time to leave the system before it is\n// removed.\nstruct ApprovalChainData {\n    address[] verifiers;\n    // Represents the time after which the verifier with the given address can be removed.\n    // Removal of the verifier with address A is allowed only in the case the value\n    // of verifierAllowedRemovalTime[A] != 0 and verifierAllowedRemovalTime[A] < (current time).\n    mapping(address => uint256) verifierAllowedRemovalTime;\n}\n"
      },
      "starkware/solidity/interactions/StateRoot.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../interfaces/MStateRoot.sol\";\nimport \"../components/MainStorage.sol\";\nimport \"../libraries/LibConstants.sol\";\n\ncontract StateRoot is MainStorage, LibConstants, MStateRoot {\n    function initialize(\n        uint256 initialSequenceNumber,\n        uint256 initialValidiumVaultRoot,\n        uint256 initialRollupVaultRoot,\n        uint256 initialOrderRoot,\n        uint256 initialValidiumTreeHeight,\n        uint256 initialRollupTreeHeight,\n        uint256 initialOrderTreeHeight\n    ) internal {\n        sequenceNumber = initialSequenceNumber;\n        validiumVaultRoot = initialValidiumVaultRoot;\n        rollupVaultRoot = initialRollupVaultRoot;\n        orderRoot = initialOrderRoot;\n        validiumTreeHeight = initialValidiumTreeHeight;\n        rollupTreeHeight = initialRollupTreeHeight;\n        orderTreeHeight = initialOrderTreeHeight;\n    }\n\n    function getValidiumVaultRoot() public view override returns (uint256) {\n        return validiumVaultRoot;\n    }\n\n    function getValidiumTreeHeight() public view override returns (uint256) {\n        return validiumTreeHeight;\n    }\n\n    function getRollupVaultRoot() public view override returns (uint256) {\n        return rollupVaultRoot;\n    }\n\n    function getRollupTreeHeight() public view override returns (uint256) {\n        return rollupTreeHeight;\n    }\n\n    function getOrderRoot() external view returns (uint256) {\n        return orderRoot;\n    }\n\n    function getOrderTreeHeight() external view returns (uint256) {\n        return orderTreeHeight;\n    }\n\n    function getSequenceNumber() external view returns (uint256) {\n        return sequenceNumber;\n    }\n\n    function getLastBatchId() external view returns (uint256) {\n        return lastBatchId;\n    }\n\n    function getGlobalConfigCode() external view returns (uint256) {\n        return globalConfigCode;\n    }\n\n    function isVaultInRange(uint256 vaultId) internal view override returns (bool) {\n        return (isValidiumVault(vaultId) || isRollupVault(vaultId));\n    }\n\n    function isValidiumVault(uint256 vaultId) internal view override returns (bool) {\n        // Return true iff vaultId is in the validium vaults tree.\n        return vaultId < 2**getValidiumTreeHeight();\n    }\n\n    function isRollupVault(uint256 vaultId) internal view override returns (bool) {\n        // Return true iff vaultId is in the rollup vaults tree.\n        uint256 rollupLowerBound = 2**ROLLUP_VAULTS_BIT;\n        uint256 rollupUpperBound = rollupLowerBound + 2**getRollupTreeHeight();\n        return (rollupLowerBound <= vaultId && vaultId < rollupUpperBound);\n    }\n\n    function getVaultLeafIndex(uint256 vaultId) internal pure override returns (uint256) {\n        // Return the index of vaultId leaf in its tree, which doesn't include the rollup bit flag.\n        return (vaultId & (2**ROLLUP_VAULTS_BIT - 1));\n    }\n}\n"
      },
      "starkware/solidity/interfaces/SubContractor.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"./Identity.sol\";\n\ninterface SubContractor is Identity {\n    function initialize(bytes calldata data) external;\n\n    function initializerSize() external view returns (uint256);\n\n    /*\n      Returns an array with selectors for validation.\n      These selectors are the critical ones for maintaining self custody and anti censorship.\n      During the upgrade process, as part of the sub-contract validation, the MainDispatcher\n      validates that the selectos are mapped to the correct sub-contract.\n    */\n    function validatedSelectors() external pure returns (bytes4[] memory);\n}\n"
      },
      "starkware/solidity/interactions/TokenQuantization.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../components/MainStorage.sol\";\nimport \"../interfaces/MTokenQuantization.sol\";\n\ncontract TokenQuantization is MainStorage, MTokenQuantization {\n    function fromQuantized(uint256 presumedAssetType, uint256 quantizedAmount)\n        internal\n        view\n        override\n        returns (uint256 amount)\n    {\n        uint256 quantum = getQuantum(presumedAssetType);\n        amount = quantizedAmount * quantum;\n        require(amount / quantum == quantizedAmount, \"DEQUANTIZATION_OVERFLOW\");\n    }\n\n    function getQuantum(uint256 presumedAssetType) public view override returns (uint256 quantum) {\n        if (!registeredAssetType[presumedAssetType]) {\n            // Default quantization, for NFTs etc.\n            quantum = 1;\n        } else {\n            // Retrieve registration.\n            quantum = assetTypeToQuantum[presumedAssetType];\n        }\n    }\n\n    function toQuantized(uint256 presumedAssetType, uint256 amount)\n        internal\n        view\n        override\n        returns (uint256 quantizedAmount)\n    {\n        uint256 quantum = getQuantum(presumedAssetType);\n        require(amount % quantum == 0, \"INVALID_AMOUNT\");\n        quantizedAmount = amount / quantum;\n    }\n}\n"
      },
      "starkware/solidity/starkex/interactions/UpdateState.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"../components/StarkExStorage.sol\";\nimport \"../interfaces/MStarkExForcedActionState.sol\";\nimport \"../PublicInputOffsets.sol\";\nimport \"../StarkExConstants.sol\";\nimport \"../../components/MessageRegistry.sol\";\nimport \"../../components/OnchainDataFactTreeEncoder.sol\";\nimport \"../../components/VerifyFactChain.sol\";\nimport \"../../interfaces/MAcceptModifications.sol\";\nimport \"../../interfaces/MFreezable.sol\";\nimport \"../../interfaces/MOperator.sol\";\nimport \"../../libraries/Addresses.sol\";\n\n/**\n  The StarkEx contract tracks the state of the off-chain exchange service by storing Merkle roots\n  of the vault state (off-chain account state) and the order state (including fully executed and\n  partially fulfilled orders).\n\n  The :sol:mod:`Operator` is the only entity entitled to submit state updates for a batch of\n  exchange transactions by calling :sol:func:`updateState` and this is only allowed if the contract\n  is not in the `frozen` state (see :sol:mod:`FullWithdrawals`). The call includes the `publicInput`\n  of a STARK proof, and additional data (`applicationData`) that includes information not attested\n  to by the proof.\n\n  The `publicInput` includes the current (initial) and next (final) Merkle roots as mentioned above,\n  the heights of the Merkle trees, a list of vault operations and a list of conditional transfers.\n\n  A vault operation can be a ramping operation (deposit/withdrawal) or an indication to clear\n  a full withdrawal request. Each vault operation is encoded in 3 words as follows:\n  | 1. Word 0: Stark Key of the vault owner (or the requestor Stark Key for false full\n  |    withdrawal).\n  | 2. Word 1: Asset ID of the vault representing either the currency (for fungible tokens) or\n  |    a unique token ID and its on-chain contract association (for non-fungible tokens).\n  | 3. Word 2:\n  |    a. ID of the vault (off-chain account)\n  |    b. Vault balance change in biased representation (excess-2**63).\n  |       A negative balance change implies a withdrawal while a positive amount implies a deposit.\n  |       A zero balance change may be used for operations implying neither\n  |       (e.g. a false full withdrawal request).\n  |    c. A bit indicating whether the operation requires clearing a full withdrawal request.\n\n  The above information is used by the exchange contract in order to update the pending accounts\n  used for deposits (see :sol:mod:`Deposits`) and withdrawals (see :sol:mod:`Withdrawals`).\n\n  The next section in the publicInput is a list of encoded conditions corresponding to the\n  conditional transfers in the batch. A condition is encoded as a hash of the conditional transfer\n  `applicationData`, described below, masked to 250 bits.\n\n  The `applicationData` holds the following information:\n  | 1. The ID of the current batch for which the operator is submitting the update.\n  | 2. The expected ID of the last batch accepted on chain. This allows the operator submitting\n  |    state updates to ensure the same batch order is accepted on-chain as was intended by the\n  |    operator in the event that more than one valid update may have been generated based on\n  |    different previous batches - an unlikely but possible event.\n  | 3. For each conditional transfer in the batch two words are provided:\n  |    a. Word 0: The address of a fact registry contract\n  |    b. Word 1: A fact to be verified on the above contract attesting that the\n  |       condition has been met on-chain.\n\n\n  The following section in the publicInput is a list of orders to be verified onchain, corresponding\n  to the onchain orders in the batch. An onchain order is of a variable length (at least 3 words)\n  and is structured as follows:\n  | 1. The Eth address of the user who submitted the order.\n  | 2. The size (number of words) of the order blob that follows. Denoted 'n' below.\n  | 3. First word of the order blob.\n  | ...\n  | n + 2. Last word of the order blob.\n\n  The STARK proof attesting to the validity of the state update is submitted separately by the\n  exchange service to (one or more) STARK integrity verifier contract(s).\n  Likewise, the signatures of committee members attesting to\n  the availability of the vault and order data is submitted separately by the exchange service to\n  (one or more) availability verifier contract(s) (see :sol:mod:`Committee`).\n\n  The state update is only accepted by the exchange contract if the integrity verifier and\n  availability verifier contracts have indeed received such proof of soundness and data\n  availability.\n*/\nabstract contract UpdateState is\n    StarkExStorage,\n    StarkExConstants,\n    MStarkExForcedActionState,\n    VerifyFactChain,\n    MAcceptModifications,\n    MFreezable,\n    MOperator,\n    PublicInputOffsets\n{\n    event LogRootUpdate(\n        uint256 sequenceNumber,\n        uint256 batchId,\n        uint256 validiumVaultRoot,\n        uint256 rollupVaultRoot,\n        uint256 orderRoot\n    );\n\n    event LogStateTransitionFact(bytes32 stateTransitionFact);\n\n    event LogVaultBalanceChangeApplied(\n        address ethKey,\n        uint256 assetId,\n        uint256 vaultId,\n        int256 quantizedAmountChange\n    );\n\n    function updateState(uint256[] calldata publicInput, uint256[] calldata applicationData)\n        external\n        virtual\n        notFrozen\n        onlyOperator\n    {\n        require(\n            publicInput.length >= PUB_IN_TRANSACTIONS_DATA_OFFSET,\n            \"publicInput does not contain all required fields.\"\n        );\n        require(\n            publicInput[PUB_IN_GLOBAL_CONFIG_CODE_OFFSET] == globalConfigCode,\n            \"Global config code mismatch.\"\n        );\n        require(\n            publicInput[PUB_IN_FINAL_VALIDIUM_VAULT_ROOT_OFFSET] < K_MODULUS,\n            \"New validium vault root >= PRIME.\"\n        );\n        require(\n            publicInput[PUB_IN_FINAL_ROLLUP_VAULT_ROOT_OFFSET] < K_MODULUS,\n            \"New rollup vault root >= PRIME.\"\n        );\n        require(\n            publicInput[PUB_IN_FINAL_ORDER_ROOT_OFFSET] < K_MODULUS,\n            \"New order root >= PRIME.\"\n        );\n        require(\n            lastBatchId == 0 || applicationData[APP_DATA_PREVIOUS_BATCH_ID_OFFSET] == lastBatchId,\n            \"WRONG_PREVIOUS_BATCH_ID\"\n        );\n\n        // Ensure global timestamp has not expired.\n        require(\n            publicInput[PUB_IN_GLOBAL_EXPIRATION_TIMESTAMP_OFFSET] <\n                2**STARKEX_EXPIRATION_TIMESTAMP_BITS,\n            \"Global expiration timestamp is out of range.\"\n        );\n\n        require( // NOLINT: block-timestamp.\n            publicInput[PUB_IN_GLOBAL_EXPIRATION_TIMESTAMP_OFFSET] > block.timestamp / 3600,\n            \"Timestamp of the current block passed the threshold for the transaction batch.\"\n        );\n\n        bytes32 stateTransitionFact = getStateTransitionFact(publicInput);\n\n        emit LogStateTransitionFact(stateTransitionFact);\n\n        verifyFact(\n            verifiersChain,\n            stateTransitionFact,\n            \"NO_STATE_TRANSITION_VERIFIERS\",\n            \"NO_STATE_TRANSITION_PROOF\"\n        );\n\n        bytes32 availabilityFact = keccak256(\n            abi.encodePacked(\n                publicInput[PUB_IN_FINAL_VALIDIUM_VAULT_ROOT_OFFSET],\n                publicInput[PUB_IN_VALIDIUM_VAULT_TREE_HEIGHT_OFFSET],\n                publicInput[PUB_IN_FINAL_ORDER_ROOT_OFFSET],\n                publicInput[PUB_IN_ORDER_TREE_HEIGHT_OFFSET],\n                sequenceNumber + 1\n            )\n        );\n\n        verifyFact(\n            availabilityVerifiersChain,\n            availabilityFact,\n            \"NO_AVAILABILITY_VERIFIERS\",\n            \"NO_AVAILABILITY_PROOF\"\n        );\n\n        performUpdateState(publicInput, applicationData);\n    }\n\n    function getStateTransitionFact(uint256[] calldata publicInput)\n        internal\n        pure\n        returns (bytes32)\n    {\n        // Use a simple fact tree.\n        require(\n            publicInput.length >=\n                PUB_IN_TRANSACTIONS_DATA_OFFSET +\n                    OnchainDataFactTreeEncoder.ONCHAIN_DATA_FACT_ADDITIONAL_WORDS,\n            \"programOutput does not contain all required fields.\"\n        );\n        return\n            OnchainDataFactTreeEncoder.encodeFactWithOnchainData(\n                publicInput[:publicInput.length -\n                    OnchainDataFactTreeEncoder.ONCHAIN_DATA_FACT_ADDITIONAL_WORDS],\n                OnchainDataFactTreeEncoder.DataAvailabilityFact({\n                    onchainDataHash: publicInput[publicInput.length - 2],\n                    onchainDataSize: publicInput[publicInput.length - 1]\n                })\n            );\n    }\n\n    function performUpdateState(uint256[] calldata publicInput, uint256[] calldata applicationData)\n        internal\n    {\n        rootUpdate(\n            publicInput[PUB_IN_INITIAL_VALIDIUM_VAULT_ROOT_OFFSET],\n            publicInput[PUB_IN_FINAL_VALIDIUM_VAULT_ROOT_OFFSET],\n            publicInput[PUB_IN_INITIAL_ROLLUP_VAULT_ROOT_OFFSET],\n            publicInput[PUB_IN_FINAL_ROLLUP_VAULT_ROOT_OFFSET],\n            publicInput[PUB_IN_INITIAL_ORDER_ROOT_OFFSET],\n            publicInput[PUB_IN_FINAL_ORDER_ROOT_OFFSET],\n            publicInput[PUB_IN_VALIDIUM_VAULT_TREE_HEIGHT_OFFSET],\n            publicInput[PUB_IN_ROLLUP_VAULT_TREE_HEIGHT_OFFSET],\n            publicInput[PUB_IN_ORDER_TREE_HEIGHT_OFFSET],\n            applicationData[APP_DATA_BATCH_ID_OFFSET]\n        );\n        performOnchainOperations(publicInput, applicationData);\n    }\n\n    function rootUpdate(\n        uint256 oldValidiumVaultRoot,\n        uint256 newValidiumVaultRoot,\n        uint256 oldRollupVaultRoot,\n        uint256 newRollupVaultRoot,\n        uint256 oldOrderRoot,\n        uint256 newOrderRoot,\n        uint256 validiumTreeHeightSent,\n        uint256 rollupTreeHeightSent,\n        uint256 orderTreeHeightSent,\n        uint256 batchId\n    ) internal virtual {\n        // Assert that the old state is correct.\n        require(oldValidiumVaultRoot == validiumVaultRoot, \"VALIDIUM_VAULT_ROOT_INCORRECT\");\n        require(oldRollupVaultRoot == rollupVaultRoot, \"ROLLUP_VAULT_ROOT_INCORRECT\");\n        require(oldOrderRoot == orderRoot, \"ORDER_ROOT_INCORRECT\");\n\n        // Assert that heights are correct.\n        require(validiumTreeHeight == validiumTreeHeightSent, \"VALIDIUM_TREE_HEIGHT_INCORRECT\");\n        require(rollupTreeHeight == rollupTreeHeightSent, \"ROLLUP_TREE_HEIGHT_INCORRECT\");\n        require(orderTreeHeight == orderTreeHeightSent, \"ORDER_TREE_HEIGHT_INCORRECT\");\n\n        // Update state.\n        validiumVaultRoot = newValidiumVaultRoot;\n        rollupVaultRoot = newRollupVaultRoot;\n        orderRoot = newOrderRoot;\n        sequenceNumber = sequenceNumber + 1;\n        lastBatchId = batchId;\n\n        // Log update.\n        emit LogRootUpdate(sequenceNumber, batchId, validiumVaultRoot, rollupVaultRoot, orderRoot);\n    }\n\n    function performOnchainOperations(\n        uint256[] calldata publicInput,\n        uint256[] calldata applicationData\n    ) private {\n        uint256 nModifications = publicInput[PUB_IN_N_MODIFICATIONS_OFFSET];\n        uint256 nCondTransfers = publicInput[PUB_IN_N_CONDITIONAL_TRANSFERS_OFFSET];\n        uint256 nOnchainVaultUpdates = publicInput[PUB_IN_N_ONCHAIN_VAULT_UPDATES_OFFSET];\n        uint256 nOnchainOrders = publicInput[PUB_IN_N_ONCHAIN_ORDERS_OFFSET];\n\n        // Sanity value that also protects from theoretical overflow in multiplication.\n        require(nModifications < 2**64, \"Invalid number of modifications.\");\n        require(nCondTransfers < 2**64, \"Invalid number of conditional transfers.\");\n        require(nOnchainVaultUpdates < 2**64, \"Invalid number of onchain vault updates.\");\n        require(nOnchainOrders < 2**64, \"Invalid number of onchain orders.\");\n        require(\n            publicInput.length >=\n                PUB_IN_TRANSACTIONS_DATA_OFFSET +\n                    PUB_IN_N_WORDS_PER_MODIFICATION *\n                    nModifications +\n                    PUB_IN_N_WORDS_PER_CONDITIONAL_TRANSFER *\n                    nCondTransfers +\n                    PUB_IN_N_WORDS_PER_ONCHAIN_VAULT_UPDATE *\n                    nOnchainVaultUpdates +\n                    PUB_IN_N_MIN_WORDS_PER_ONCHAIN_ORDER *\n                    nOnchainOrders +\n                    OnchainDataFactTreeEncoder.ONCHAIN_DATA_FACT_ADDITIONAL_WORDS,\n            \"publicInput size is inconsistent with expected transactions.\"\n        );\n        require(\n            applicationData.length ==\n                APP_DATA_TRANSACTIONS_DATA_OFFSET +\n                    APP_DATA_N_WORDS_PER_CONDITIONAL_TRANSFER *\n                    nCondTransfers,\n            \"applicationData size is inconsistent with expected transactions.\"\n        );\n\n        uint256 offsetPubInput = PUB_IN_TRANSACTIONS_DATA_OFFSET;\n        uint256 offsetAppData = APP_DATA_TRANSACTIONS_DATA_OFFSET;\n\n        // When reaching this line, offsetPubInput is initialized to the beginning of modifications\n        // data in publicInput. Following this line's execution, offsetPubInput is incremented by\n        // the number of words consumed by sendModifications.\n        offsetPubInput += sendModifications(publicInput[offsetPubInput:], nModifications);\n\n        // When reaching this line, offsetPubInput and offsetAppData are pointing to the beginning\n        // of conditional transfers data in publicInput and applicationData.\n        // Following the execution of this block, offsetPubInput and offsetAppData are incremented\n        // by the number of words consumed by verifyConditionalTransfers.\n        {\n            uint256 consumedPubInputWords;\n            uint256 consumedAppDataWords;\n            (consumedPubInputWords, consumedAppDataWords) = verifyConditionalTransfers(\n                publicInput[offsetPubInput:],\n                applicationData[offsetAppData:],\n                nCondTransfers\n            );\n\n            offsetPubInput += consumedPubInputWords;\n            offsetAppData += consumedAppDataWords;\n        }\n\n        // offsetPubInput is incremented by the number of words consumed by updateOnchainVaults.\n        // NOLINTNEXTLINE: reentrancy-benign.\n        offsetPubInput += updateOnchainVaults(publicInput[offsetPubInput:], nOnchainVaultUpdates);\n\n        // offsetPubInput is incremented by the number of words consumed by verifyOnchainOrders.\n        offsetPubInput += verifyOnchainOrders(publicInput[offsetPubInput:], nOnchainOrders);\n\n        // The Onchain Data info appears at the end of publicInput.\n        offsetPubInput += OnchainDataFactTreeEncoder.ONCHAIN_DATA_FACT_ADDITIONAL_WORDS;\n\n        require(offsetPubInput == publicInput.length, \"Incorrect Size\");\n    }\n\n    /*\n      Deposits and withdrawals. Moves funds off and on chain.\n        slidingPublicInput - a pointer to the beginning of modifications data in publicInput.\n        nModifications - the number of modifications.\n      Returns the number of publicInput words consumed by this function.\n    */\n    function sendModifications(uint256[] calldata slidingPublicInput, uint256 nModifications)\n        private\n        returns (uint256 consumedPubInputItems)\n    {\n        uint256 offsetPubInput = 0;\n\n        for (uint256 i = 0; i < nModifications; i++) {\n            uint256 ownerKey = slidingPublicInput[offsetPubInput];\n            uint256 assetId = slidingPublicInput[offsetPubInput + 1];\n\n            require(ownerKey < K_MODULUS, \"Stark key >= PRIME\");\n            require(assetId < K_MODULUS, \"Asset id >= PRIME\");\n\n            uint256 actionParams = slidingPublicInput[offsetPubInput + 2];\n            require((actionParams >> 129) == 0, \"Unsupported modification action field.\");\n\n            // Extract and unbias the balanceDiff.\n            int256 balanceDiff = int256((actionParams & ((1 << 64) - 1)) - (1 << 63));\n            uint256 vaultId = (actionParams >> 64) & ((1 << 64) - 1);\n\n            if (balanceDiff > 0) {\n                // This is a deposit.\n                acceptDeposit(ownerKey, vaultId, assetId, uint256(balanceDiff));\n            } else if (balanceDiff < 0) {\n                // This is a withdrawal.\n                acceptWithdrawal(ownerKey, assetId, uint256(-balanceDiff));\n            }\n\n            if ((actionParams & (1 << 128)) != 0) {\n                clearFullWithdrawalRequest(ownerKey, vaultId);\n            }\n\n            offsetPubInput += PUB_IN_N_WORDS_PER_MODIFICATION;\n        }\n        return offsetPubInput;\n    }\n\n    /*\n      Verifies that each conditional transfer's condition was met.\n        slidingPublicInput - a pointer to the beginning of condTransfers data in publicInput.\n        slidingAppData - a pointer to the beginning of condTransfers data in applicationData.\n        nCondTransfers - the number of conditional transfers.\n      Returns the number of publicInput and applicationData words consumed by this function.\n    */\n    function verifyConditionalTransfers(\n        uint256[] calldata slidingPublicInput,\n        uint256[] calldata slidingAppData,\n        uint256 nCondTransfers\n    ) private view returns (uint256 consumedPubInputItems, uint256 consumedAppDataItems) {\n        uint256 offsetPubInput = 0;\n        uint256 offsetAppData = 0;\n\n        for (uint256 i = 0; i < nCondTransfers; i++) {\n            address factRegistryAddress = address(slidingAppData[offsetAppData]);\n            bytes32 condTransferFact = bytes32(slidingAppData[offsetAppData + 1]);\n            uint256 condition = slidingPublicInput[offsetPubInput];\n\n            // The condition is the 250 LS bits of keccak256 of the fact registry & fact.\n            require(\n                condition ==\n                    uint256(keccak256(abi.encodePacked(factRegistryAddress, condTransferFact))) &\n                        MASK_250,\n                \"Condition mismatch.\"\n            );\n            // NOLINTNEXTLINE: low-level-calls-loop.\n            (bool success, bytes memory returndata) = factRegistryAddress.staticcall(\n                abi.encodeWithSignature(\"isValid(bytes32)\", condTransferFact)\n            );\n            require(success && returndata.length == 32, \"BAD_FACT_REGISTRY_CONTRACT\");\n            require(\n                abi.decode(returndata, (bool)),\n                \"Condition for the conditional transfer was not met.\"\n            );\n\n            offsetPubInput += PUB_IN_N_WORDS_PER_CONDITIONAL_TRANSFER;\n            offsetAppData += APP_DATA_N_WORDS_PER_CONDITIONAL_TRANSFER;\n        }\n        return (offsetPubInput, offsetAppData);\n    }\n\n    /*\n      Moves funds into and out of onchain vaults.\n        slidingPublicInput - a pointer to the beginning of onchain vaults update data in publicInput.\n        nOnchainVaultUpdates - the number of onchain vaults updates.\n      Returns the number of publicInput words consumed by this function.\n    */\n    function updateOnchainVaults(\n        uint256[] calldata slidingPublicInput,\n        uint256 nOnchainVaultUpdates\n    ) private returns (uint256 consumedPubInputItems) {\n        uint256 offsetPubInput = 0;\n\n        for (uint256 i = 0; i < nOnchainVaultUpdates; i++) {\n            address ethAddress = address(slidingPublicInput[offsetPubInput]);\n            uint256 assetId = slidingPublicInput[offsetPubInput + 1];\n\n            require(assetId < K_MODULUS, \"assetId >= PRIME\");\n\n            uint256 additionalParams = slidingPublicInput[offsetPubInput + 2];\n            require((additionalParams >> 160) == 0, \"Unsupported vault update field.\");\n\n            // Extract and unbias the balanceDiff.\n            int256 balanceDiff = int256((additionalParams & ((1 << 64) - 1)) - (1 << 63));\n\n            int256 minBalance = int256((additionalParams >> 64) & ((1 << 64) - 1));\n            uint256 vaultId = (additionalParams >> 128) & ((1 << 31) - 1);\n\n            int256 balanceBefore = int256(vaultsBalances[ethAddress][assetId][vaultId]);\n            int256 newBalance = balanceBefore + balanceDiff;\n\n            if (balanceDiff > 0) {\n                require(newBalance > balanceBefore, \"VAULT_OVERFLOW\");\n            } else {\n                require(balanceBefore >= balanceDiff, \"INSUFFICIENT_VAULT_BALANCE\");\n            }\n\n            if (strictVaultBalancePolicy) {\n                require(minBalance >= 0, \"ILLEGAL_BALANCE_REQUIREMENT\");\n                require(balanceBefore >= minBalance, \"UNMET_BALANCE_REQUIREMENT\");\n            }\n\n            require(newBalance >= 0, \"NEGATIVE_BALANCE\");\n            vaultsBalances[ethAddress][assetId][vaultId] = uint256(newBalance);\n            // NOLINTNEXTLINE: reentrancy-events.\n            emit LogVaultBalanceChangeApplied(ethAddress, assetId, vaultId, balanceDiff);\n\n            offsetPubInput += PUB_IN_N_WORDS_PER_ONCHAIN_VAULT_UPDATE;\n        }\n        return offsetPubInput;\n    }\n\n    /*\n      Verifies that each order was registered by its sender.\n        slidingPublicInput - a pointer to the beginning of onchain orders data in publicInput.\n        nOnchainOrders - the number of onchain orders.\n      Returns the number of publicInput words consumed by this function.\n    */\n    function verifyOnchainOrders(uint256[] calldata slidingPublicInput, uint256 nOnchainOrders)\n        private\n        view\n        returns (uint256 consumedPubInputItems)\n    {\n        MessageRegistry orderRegistry = MessageRegistry(orderRegistryAddress);\n        uint256 offsetPubInput = 0;\n\n        for (uint256 i = 0; i < nOnchainOrders; i++) {\n            // Make sure we remain within slidingPublicInput's bounds.\n            require(offsetPubInput + 2 <= slidingPublicInput.length, \"Input out of bounds.\");\n            // First word is the order sender.\n            address orderSender = address(slidingPublicInput[offsetPubInput]);\n            // Second word is the order blob size (number of blob words) that follow.\n            uint256 blobSize = uint256(slidingPublicInput[offsetPubInput + 1]);\n            require(offsetPubInput + blobSize + 2 >= offsetPubInput, \"Blob size overflow.\");\n\n            offsetPubInput += 2;\n            require(offsetPubInput + blobSize <= slidingPublicInput.length, \"Input out of bounds.\");\n            // Calculate the hash of the order blob.\n            bytes32 orderHash = keccak256(\n                abi.encodePacked(slidingPublicInput[offsetPubInput:offsetPubInput + blobSize])\n            );\n\n            // Verify this order has been registered.\n            require(\n                orderRegistry.isMessageRegistered(orderSender, address(this), orderHash),\n                \"Order not registered.\"\n            );\n\n            offsetPubInput += blobSize;\n        }\n        return offsetPubInput;\n    }\n}\n"
      },
      "starkware/solidity/components/VerifyFactChain.sol": {
        "content": "/*\n  Copyright 2019-2024 StarkWare Industries Ltd.\n\n  Licensed under the Apache License, Version 2.0 (the \"License\").\n  You may not use this file except in compliance with the License.\n  You may obtain a copy of the License at\n\n  https://www.starkware.co/open-source-license/\n\n  Unless required by applicable law or agreed to in writing,\n  software distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions\n  and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"./MainStorage.sol\";\nimport \"../interfaces/IFactRegistry.sol\";\nimport {ApprovalChainData} from \"../libraries/StarkExTypes.sol\";\n\ncontract VerifyFactChain is MainStorage {\n    function verifyFact(\n        ApprovalChainData storage chain,\n        bytes32 fact,\n        string memory noVerifiersErrorMessage,\n        string memory invalidFactErrorMessage\n    ) internal view {\n        address[] storage verifiers = chain.verifiers;\n        uint256 n_entries = verifiers.length;\n        require(n_entries > 0, noVerifiersErrorMessage);\n        for (uint256 i = 0; i < n_entries; i++) {\n            // NOLINTNEXTLINE: calls-loop.\n            require(IFactRegistry(verifiers[i]).isValid(fact), invalidFactErrorMessage);\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "metadata": {
        "useLiteralContent": true
      },
      "libraries": {},
      "remappings": [],
      "optimizer": {
        "enabled": true,
        "runs": 100
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      }
    }
  }}