Transaction Hash:
Block:
19831611 at May-09-2024 09:32:35 AM +UTC
Transaction Fee:
0.00028384823877039 ETH
$0.54
Gas Used:
64,995 Gas / 4.367231922 Gwei
Emitted Events:
369 |
Proxy.0x7a06c571aa77f34d9706c51e5d8122b5595aebeaa34233bfe866f22befb973b1( 0x7a06c571aa77f34d9706c51e5d8122b5595aebeaa34233bfe866f22befb973b1, 0x073314940630fd6dcda0d772d4c972c4e0a9946bef9dabf4ef84eda8ef542b82, 0x000000000000000000000000ae0ee0a63a2ce6baeeffe56e7714fb4efe48d419, 0000000000000000000000000000000000000000000000000000000000000020, 0000000000000000000000000000000000000000000000000000000000000005, 0000000000000000000000000000000000000000000000000000000000000000, 000000000000000000000000d01946f82f7713cd7859c16ef69b06ec05b3fcc6, 0000000000000000000000000000000000000000000000000000000000455448, 00000000000000000000000000000000000000000000000011c37937e0800000, 0000000000000000000000000000000000000000000000000000000000000000 )
|
370 |
Proxy.0x2717ead6b9200dd235aad468c9809ea400fe33ac69b5bfaa6d3e90fc922b6398( 0x2717ead6b9200dd235aad468c9809ea400fe33ac69b5bfaa6d3e90fc922b6398, 0x000000000000000000000000d01946f82f7713cd7859c16ef69b06ec05b3fcc6, 0x0000000000000000000000000000000000000000000000000000000000455448, 00000000000000000000000000000000000000000000000011c37937e0800000 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x8325cFBC...6BA7B46bF |
4.135215484939129562 Eth
Nonce: 4674
|
4.134931636700359172 Eth
Nonce: 4675
| 0.00028384823877039 | ||
0x95222290...5CC4BAfe5
Miner
| (beaverbuild) | 7.344009517478386109 Eth | 7.344010666636197554 Eth | 0.000001149157811445 | |
0xae0Ee0A6...EFE48D419 | (Starknet: StarkGate ETH Bridge) | 61,048.660356064875709481 Eth | 61,047.380356064875709481 Eth | 1.28 | |
0xc662c410...BeBD9C8c4 | (Starknet: Core Contract) | ||||
0xd01946F8...C05b3FcC6 | 0.004014271315881521 Eth | 1.284014271315881521 Eth | 1.28 |
Execution Trace
Proxy.00f714ce( )
StarknetEthBridge.withdraw( amount=1280000000000000000, recipient=0xd01946F82F7713CD7859c16EF69B06EC05b3FcC6 )
Proxy.2c9dd5c0( )
-
Starknet.consumeMessageFromL2( fromAddress=3256441166037631918262930812410838598500200462657642943867372734773841898370, payload=[0, 1188033781274456107001895706489015262002195725510, 4543560, 1280000000000000000, 0] ) => ( DE53EE2F8EE9AD50C0CF0DCC1523307002800B14FB178FE0A11146B157C3A446 )
-
- ETH 1.28
0xd01946f82f7713cd7859c16ef69b06ec05b3fcc6.CALL( )
withdraw[LegacyBridge (ln:969)]
withdraw[LegacyBridge (ln:970)]
withdraw[LegacyBridge (ln:970)]
bridgedToken[LegacyBridge (ln:970)]
getAddressValue[LegacyBridge (ln:920)]
bridgedToken[LegacyBridge (ln:970)]
getAddressValue[LegacyBridge (ln:920)]
File 1 of 4: Proxy
File 2 of 4: Proxy
File 3 of 4: StarknetEthBridge
File 4 of 4: Starknet
{"Common.sol":{"content":"/*\n Copyright 2019-2022 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 librarries.\n I. Addresses (extending address).\n*/\nlibrary Addresses {\n function isContract(address account) internal view returns (bool) {\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size \u003e 0;\n }\n\n function performEthTransfer(address recipient, uint256 amount) internal {\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\u0027t 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 \u003e 0) {\n require(abi.decode(returndata, (bool)), \"TOKEN_OPERATION_FAILED\");\n }\n }\n\n /*\n Validates that the passed contract address is of a real contract,\n and that its id hash (as infered fromn identify()) matched the expected one.\n */\n function validateContractId(address contractAddress, bytes32 expectedIdHash) internal {\n require(isContract(contractAddress), \"ADDRESS_NOT_CONTRACT\");\n (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls.\n abi.encodeWithSignature(\"identify()\")\n );\n require(success, \"FAILED_TO_IDENTIFY_CONTRACT\");\n string memory realContractId = abi.decode(returndata, (string));\n require(\n keccak256(abi.encodePacked(realContractId)) == expectedIdHash,\n \"UNEXPECTED_CONTRACT_IDENTIFIER\"\n );\n }\n}\n\n/*\n II. StarkExTypes - Common data types.\n*/\nlibrary StarkExTypes {\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 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.\n struct ApprovalChainData {\n address[] list;\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 unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] \u003c (current time).\n mapping(address =\u003e uint256) unlockedForRemovalTime;\n }\n}\n"},"Governance.sol":{"content":"/*\n Copyright 2019-2022 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\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*/\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 addGovernor() won\u0027t fail.\n // Add the initial governer.\n addGovernor(msg.sender);\n }\n\n function _isGovernor(address testGovernor) internal view override returns (bool) {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n return gub.effectiveGovernors[testGovernor];\n }\n\n /*\n Cancels the nomination of a governor candidate.\n */\n function _cancelNomination() internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.candidateGovernor = address(0x0);\n emit LogNominationCancelled();\n }\n\n function _nominateNewGovernor(address newGovernor) internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(!_isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n gub.candidateGovernor = newGovernor;\n emit LogNominatedGovernor(newGovernor);\n }\n\n /*\n The addGovernor 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 addGovernor(address newGovernor) private {\n require(!_isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.effectiveGovernors[newGovernor] = true;\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 addGovernor(gub.candidateGovernor);\n gub.candidateGovernor = address(0x0);\n\n // Send a notification about the change of governor.\n emit LogNewGovernorAccepted(msg.sender);\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"},"GovernanceStorage.sol":{"content":"/*\n Copyright 2019-2022 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 \"MGovernance.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 =\u003e GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state.\n}\n"},"MGovernance.sol":{"content":"/*\n Copyright 2019-2022 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\nstruct GovernanceInfoStruct {\n mapping(address =\u003e bool) effectiveGovernors;\n address candidateGovernor;\n bool initialized;\n}\n\nabstract contract MGovernance {\n function _isGovernor(address testGovernor) 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"},"Proxy.sol":{"content":"/*\n Copyright 2019-2022 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 \"ProxyGovernance.sol\";\nimport \"ProxyStorage.sol\";\nimport \"StorageSlots.sol\";\nimport \"Common.sol\";\n\n/**\n The Proxy contract implements delegation of calls to other contracts (`implementations`), with\n proper forwarding of return values and revert reasons. This pattern allows retaining the contract\n storage while replacing implementation code.\n\n The following operations are supported by the proxy contract:\n\n - :sol:func:`addImplementation`: Defines a new implementation, the data with which it should be initialized and whether this will be the last version of implementation.\n - :sol:func:`upgradeTo`: Once an implementation is added, the governor may upgrade to that implementation only after a safety time period has passed (time lock), the current implementation is not the last version and the implementation is not frozen (see :sol:mod:`FullWithdrawals`).\n - :sol:func:`removeImplementation`: Any announced implementation may be removed. Removing an implementation is especially important once it has been used for an upgrade in order to avoid an additional unwanted revert to an older version.\n\n The only entity allowed to perform the above operations is the proxy governor\n (see :sol:mod:`ProxyGovernance`).\n\n Every implementation is required to have an `initialize` function that replaces the constructor\n of a normal contract. Furthermore, the only parameter of this function is an array of bytes\n (`data`) which may be decoded arbitrarily by the `initialize` function. It is up to the\n implementation to ensure that this function cannot be run more than once if so desired.\n\n When an implementation is added (:sol:func:`addImplementation`) the initialization `data` is also\n announced, allowing users of the contract to analyze the full effect of an upgrade to the new\n implementation. During an :sol:func:`upgradeTo`, the `data` is provided again and only if it is\n identical to the announced `data` is the upgrade performed by pointing the proxy to the new\n implementation and calling its `initialize` function with this `data`.\n\n It is the responsibility of the implementation not to overwrite any storage belonging to the\n proxy (`ProxyStorage`). In addition, upon upgrade, the new implementation is assumed to be\n backward compatible with previous implementations with respect to the storage used until that\n point.\n*/\ncontract Proxy is ProxyStorage, ProxyGovernance, StorageSlots {\n // Emitted when the active implementation is replaced.\n event ImplementationUpgraded(address indexed implementation, bytes initializer);\n\n // Emitted when an implementation is submitted as an upgrade candidate and a time lock\n // is activated.\n event ImplementationAdded(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when an implementation is removed from the list of upgrade candidates.\n event ImplementationRemoved(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when the implementation is finalized.\n event FinalizedImplementation(address indexed implementation);\n\n using Addresses for address;\n\n string public constant PROXY_VERSION = \"3.0.1\";\n\n constructor(uint256 upgradeActivationDelay) public {\n initGovernance();\n setUpgradeActivationDelay(upgradeActivationDelay);\n }\n\n function setUpgradeActivationDelay(uint256 delayInSeconds) private {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n sstore(slot, delayInSeconds)\n }\n }\n\n function getUpgradeActivationDelay() public view returns (uint256 delay) {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n delay := sload(slot)\n }\n return delay;\n }\n\n /*\n Returns the address of the current implementation.\n */\n // NOLINTNEXTLINE external-function.\n function implementation() public view returns (address _implementation) {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n _implementation := sload(slot)\n }\n }\n\n /*\n Returns true if the implementation is frozen.\n If the implementation was not assigned yet, returns false.\n */\n function implementationIsFrozen() private returns (bool) {\n address _implementation = implementation();\n\n // We can\u0027t call low level implementation before it\u0027s assigned. (i.e. ZERO).\n if (_implementation == address(0x0)) {\n return false;\n }\n\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = _implementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, string(returndata));\n return abi.decode(returndata, (bool));\n }\n\n /*\n This method blocks delegation to initialize().\n Only upgradeTo should be able to delegate call to initialize().\n */\n function initialize(\n bytes calldata /*data*/\n ) external pure {\n revert(\"CANNOT_CALL_INITIALIZE\");\n }\n\n modifier notFinalized() {\n require(isNotFinalized(), \"IMPLEMENTATION_FINALIZED\");\n _;\n }\n\n /*\n Forbids calling the function if the implementation is frozen.\n This modifier relies on the lower level (logical contract) implementation of isFrozen().\n */\n modifier notFrozen() {\n require(!implementationIsFrozen(), \"STATE_IS_FROZEN\");\n _;\n }\n\n /*\n This entry point serves only transactions with empty calldata. (i.e. pure value transfer tx).\n We don\u0027t expect to receive such, thus block them.\n */\n receive() external payable {\n revert(\"CONTRACT_NOT_EXPECTED_TO_RECEIVE\");\n }\n\n /*\n Contract\u0027s default function. Delegates execution to the implementation contract.\n It returns back to the external caller whatever the implementation delegated code returns.\n */\n fallback() external payable {\n address _implementation = implementation();\n require(_implementation != address(0x0), \"MISSING_IMPLEMENTATION\");\n\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 for now, as we don\u0027t know the out size yet.\n let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /*\n Sets the implementation address of the proxy.\n */\n function setImplementation(address newImplementation) private {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n sstore(slot, newImplementation)\n }\n }\n\n /*\n Returns true if the contract is not in the finalized state.\n */\n function isNotFinalized() public view returns (bool notFinal) {\n bytes32 slot = FINALIZED_STATE_SLOT;\n uint256 slotValue;\n assembly {\n slotValue := sload(slot)\n }\n notFinal = (slotValue == 0);\n }\n\n /*\n Marks the current implementation as finalized.\n */\n function setFinalizedFlag() private {\n bytes32 slot = FINALIZED_STATE_SLOT;\n assembly {\n sstore(slot, 0x1)\n }\n }\n\n /*\n Introduce an implementation and its initialization vector,\n and start the time-lock before it can be upgraded to.\n addImplementation is not blocked when frozen or finalized.\n (upgradeTo API is blocked when finalized or frozen).\n */\n function addImplementation(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n\n uint256 activationTime = block.timestamp + getUpgradeActivationDelay();\n\n enabledTime[implVectorHash] = activationTime;\n emit ImplementationAdded(newImplementation, data, finalize);\n }\n\n /*\n Removes a candidate implementation.\n Note that it is possible to remove the current implementation. Doing so doesn\u0027t affect the\n current implementation, but rather revokes it as a future candidate.\n */\n function removeImplementation(\n address removedImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n bytes32 implVectorHash = keccak256(abi.encode(removedImplementation, data, finalize));\n\n // If we have initializer, we set the hash of it.\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n delete enabledTime[implVectorHash];\n emit ImplementationRemoved(removedImplementation, data, finalize);\n }\n\n /*\n Upgrades the proxy to a new implementation, with its initialization.\n to upgrade successfully, implementation must have been added time-lock agreeably\n before, and the init vector must be identical ot the one submitted before.\n\n Upon assignment of new implementation address,\n its initialize will be called with the initializing vector (even if empty).\n Therefore, the implementation MUST must have such a method.\n\n Note - Initialization data is committed to in advance, therefore it must remain valid\n until the actual contract upgrade takes place.\n\n Care should be taken regarding initialization data and flow when planning the contract upgrade.\n\n When planning contract upgrade, special care is also needed with regard to governance\n (See comments in Governance.sol).\n */\n // NOLINTNEXTLINE: reentrancy-events timestamp.\n function upgradeTo(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external payable onlyGovernance notFinalized notFrozen {\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n\n // On the first time an implementation is set - time-lock should not be enforced.\n require(\n activationTime \u003c= block.timestamp || implementation() == address(0x0),\n \"UPGRADE_NOT_ENABLED_YET\"\n );\n\n setImplementation(newImplementation);\n\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (bool success, bytes memory returndata) = newImplementation.delegatecall(\n abi.encodeWithSelector(this.initialize.selector, data)\n );\n require(success, string(returndata));\n\n // Verify that the new implementation is not frozen post initialization.\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (success, returndata) = newImplementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, \"CALL_TO_ISFROZEN_REVERTED\");\n require(!abi.decode(returndata, (bool)), \"NEW_IMPLEMENTATION_FROZEN\");\n\n if (finalize) {\n setFinalizedFlag();\n emit FinalizedImplementation(newImplementation);\n }\n\n emit ImplementationUpgraded(newImplementation, data);\n }\n}\n"},"ProxyGovernance.sol":{"content":"/*\n Copyright 2019-2022 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 Proxy 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:`proxyNominateNewGovernor`)\n 2. Remove other governors (:sol:func:`proxyRemoveGovernor`)\n 3. Add new `implementations` (proxied contracts)\n 4. Remove (new or old) `implementations`\n 5. Update `implementations` after a timelock allows it\n\n Adding governors is performed in a two step procedure:\n\n 1. First, an existing governor nominates a new governor (:sol:func:`proxyNominateNewGovernor`)\n 2. Then, the new governor must accept governance to become a governor (:sol:func:`proxyAcceptGovernance`)\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 or managed via a\n multi-sig contract.\n*/\n/*\n Implements Governance for the proxy contract.\n It is a thin wrapper to the Governance contract,\n which is needed so that it can have non-colliding function names,\n and a specific tag (key) to allow unique state storage.\n*/\ncontract ProxyGovernance is GovernanceStorage, Governance {\n // The tag is the string key that is used in the Governance storage mapping.\n string public constant PROXY_GOVERNANCE_TAG = \"StarkEx.Proxy.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[PROXY_GOVERNANCE_TAG];\n }\n\n function proxyIsGovernor(address testGovernor) external view returns (bool) {\n return _isGovernor(testGovernor);\n }\n\n function proxyNominateNewGovernor(address newGovernor) external {\n _nominateNewGovernor(newGovernor);\n }\n\n function proxyRemoveGovernor(address governorForRemoval) external {\n _removeGovernor(governorForRemoval);\n }\n\n function proxyAcceptGovernance() external {\n _acceptGovernance();\n }\n\n function proxyCancelNomination() external {\n _cancelNomination();\n }\n}\n"},"ProxyStorage.sol":{"content":"/*\n Copyright 2019-2022 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 \"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 =\u003e bytes32) internal initializationHash_DEPRECATED;\n\n // The time after which we can switch to the implementation.\n // Hash(implementation, data, finalize) =\u003e time.\n mapping(bytes32 =\u003e 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 =\u003e bool) internal initialized;\n}\n"},"StorageSlots.sol":{"content":"/*\n Copyright 2019-2022 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 StorageSlots holds the arbitrary storage slots used throughout the Proxy pattern.\n Storage address slots are a mechanism to define an arbitrary location, that will not be\n overlapped by the logical contracts.\n*/\ncontract StorageSlots {\n // Storage slot with the address of the current implementation.\n // The address of the slot is keccak256(\"StarkWare2019.implemntation-slot\").\n // We need to keep this variable stored outside of the commonly used space,\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant IMPLEMENTATION_SLOT =\n 0x177667240aeeea7e35eabe3a35e18306f336219e1386f7710a6bf8783f761b24;\n\n // Storage slot with the address of the call-proxy current implementation.\n // The address of the slot is keccak256(\"\u0027StarkWare2020.CallProxy.Implemntation.Slot\u0027\").\n // We need to keep this variable stored outside of the commonly used space.\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant CALL_PROXY_IMPL_SLOT =\n 0x7184681641399eb4ad2fdb92114857ee6ff239f94ad635a1779978947b8843be;\n\n // This storage slot stores the finalization flag.\n // Once the value stored in this slot is set to non-zero\n // the proxy blocks implementation upgrades.\n // The current implementation is then referred to as Finalized.\n // Web3.solidityKeccak([\u0027string\u0027], [\"StarkWare2019.finalization-flag-slot\"]).\n bytes32 internal constant FINALIZED_STATE_SLOT =\n 0x7d433c6f837e8f93009937c466c82efbb5ba621fae36886d0cac433c5d0aa7d2;\n\n // Storage slot to hold the upgrade delay (time-lock).\n // The intention of this slot is to allow modification using an EIC.\n // Web3.solidityKeccak([\u0027string\u0027], [\u0027StarkWare.Upgradibility.Delay.Slot\u0027]).\n bytes32 public constant UPGRADE_DELAY_SLOT =\n 0xc21dbb3089fcb2c4f4c6a67854ab4db2b0f233ea4b21b21f912d52d18fc5db1f;\n}\n"}}
File 2 of 4: Proxy
{"Common.sol":{"content":"/*\n Copyright 2019-2021 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 librarries.\n I. Addresses (extending address).\n*/\nlibrary Addresses {\n function isContract(address account) internal view returns (bool) {\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size \u003e 0;\n }\n\n function performEthTransfer(address recipient, uint256 amount) internal {\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\u0027t 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 \u003e 0) {\n require(abi.decode(returndata, (bool)), \"TOKEN_OPERATION_FAILED\");\n }\n }\n\n /*\n Validates that the passed contract address is of a real contract,\n and that its id hash (as infered fromn identify()) matched the expected one.\n */\n function validateContractId(address contractAddress, bytes32 expectedIdHash) internal {\n require(isContract(contractAddress), \"ADDRESS_NOT_CONTRACT\");\n (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls.\n abi.encodeWithSignature(\"identify()\")\n );\n require(success, \"FAILED_TO_IDENTIFY_CONTRACT\");\n string memory realContractId = abi.decode(returndata, (string));\n require(\n keccak256(abi.encodePacked(realContractId)) == expectedIdHash,\n \"UNEXPECTED_CONTRACT_IDENTIFIER\"\n );\n }\n}\n\n/*\n II. StarkExTypes - Common data types.\n*/\nlibrary StarkExTypes {\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 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.\n struct ApprovalChainData {\n address[] list;\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 unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] \u003c (current time).\n mapping(address =\u003e uint256) unlockedForRemovalTime;\n }\n}\n"},"Governance.sol":{"content":"/*\n Copyright 2019-2021 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\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*/\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 addGovernor() won\u0027t fail.\n // Add the initial governer.\n addGovernor(msg.sender);\n }\n\n function isGovernor(address testGovernor) internal view override returns (bool) {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n return gub.effectiveGovernors[testGovernor];\n }\n\n /*\n Cancels the nomination of a governor candidate.\n */\n function cancelNomination() internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.candidateGovernor = address(0x0);\n emit LogNominationCancelled();\n }\n\n function nominateNewGovernor(address newGovernor) internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(!isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n gub.candidateGovernor = newGovernor;\n emit LogNominatedGovernor(newGovernor);\n }\n\n /*\n The addGovernor 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 addGovernor(address newGovernor) private {\n require(!isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.effectiveGovernors[newGovernor] = true;\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 addGovernor(gub.candidateGovernor);\n gub.candidateGovernor = address(0x0);\n\n // Send a notification about the change of governor.\n emit LogNewGovernorAccepted(msg.sender);\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"},"GovernanceStorage.sol":{"content":"/*\n Copyright 2019-2021 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 \"MGovernance.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 =\u003e GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state.\n}\n"},"MGovernance.sol":{"content":"/*\n Copyright 2019-2021 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\nstruct GovernanceInfoStruct {\n mapping(address =\u003e bool) effectiveGovernors;\n address candidateGovernor;\n bool initialized;\n}\n\nabstract contract MGovernance {\n function isGovernor(address testGovernor) 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"},"Proxy.sol":{"content":"/*\n Copyright 2019-2021 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 \"ProxyGovernance.sol\";\nimport \"ProxyStorage.sol\";\nimport \"StorageSlots.sol\";\nimport \"Common.sol\";\n\n/**\n The Proxy contract implements delegation of calls to other contracts (`implementations`), with\n proper forwarding of return values and revert reasons. This pattern allows retaining the contract\n storage while replacing implementation code.\n\n The following operations are supported by the proxy contract:\n\n - :sol:func:`addImplementation`: Defines a new implementation, the data with which it should be initialized and whether this will be the last version of implementation.\n - :sol:func:`upgradeTo`: Once an implementation is added, the governor may upgrade to that implementation only after a safety time period has passed (time lock), the current implementation is not the last version and the implementation is not frozen (see :sol:mod:`FullWithdrawals`).\n - :sol:func:`removeImplementation`: Any announced implementation may be removed. Removing an implementation is especially important once it has been used for an upgrade in order to avoid an additional unwanted revert to an older version.\n\n The only entity allowed to perform the above operations is the proxy governor\n (see :sol:mod:`ProxyGovernance`).\n\n Every implementation is required to have an `initialize` function that replaces the constructor\n of a normal contract. Furthermore, the only parameter of this function is an array of bytes\n (`data`) which may be decoded arbitrarily by the `initialize` function. It is up to the\n implementation to ensure that this function cannot be run more than once if so desired.\n\n When an implementation is added (:sol:func:`addImplementation`) the initialization `data` is also\n announced, allowing users of the contract to analyze the full effect of an upgrade to the new\n implementation. During an :sol:func:`upgradeTo`, the `data` is provided again and only if it is\n identical to the announced `data` is the upgrade performed by pointing the proxy to the new\n implementation and calling its `initialize` function with this `data`.\n\n It is the responsibility of the implementation not to overwrite any storage belonging to the\n proxy (`ProxyStorage`). In addition, upon upgrade, the new implementation is assumed to be\n backward compatible with previous implementations with respect to the storage used until that\n point.\n*/\ncontract Proxy is ProxyStorage, ProxyGovernance, StorageSlots {\n // Emitted when the active implementation is replaced.\n event ImplementationUpgraded(address indexed implementation, bytes initializer);\n\n // Emitted when an implementation is submitted as an upgrade candidate and a time lock\n // is activated.\n event ImplementationAdded(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when an implementation is removed from the list of upgrade candidates.\n event ImplementationRemoved(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when the implementation is finalized.\n event FinalizedImplementation(address indexed implementation);\n\n using Addresses for address;\n\n string public constant PROXY_VERSION = \"3.0.0\";\n\n constructor(uint256 upgradeActivationDelay) public {\n initGovernance();\n setUpgradeActivationDelay(upgradeActivationDelay);\n }\n\n function setUpgradeActivationDelay(uint256 delayInSeconds) private {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n sstore(slot, delayInSeconds)\n }\n }\n\n function getUpgradeActivationDelay() public view returns (uint256 delay) {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n delay := sload(slot)\n }\n return delay;\n }\n\n /*\n Returns the address of the current implementation.\n */\n // NOLINTNEXTLINE external-function.\n function implementation() public view returns (address _implementation) {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n _implementation := sload(slot)\n }\n }\n\n /*\n Returns true if the implementation is frozen.\n If the implementation was not assigned yet, returns false.\n */\n function implementationIsFrozen() private returns (bool) {\n address _implementation = implementation();\n\n // We can\u0027t call low level implementation before it\u0027s assigned. (i.e. ZERO).\n if (_implementation == address(0x0)) {\n return false;\n }\n\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = _implementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, string(returndata));\n return abi.decode(returndata, (bool));\n }\n\n /*\n This method blocks delegation to initialize().\n Only upgradeTo should be able to delegate call to initialize().\n */\n function initialize(\n bytes calldata /*data*/\n ) external pure {\n revert(\"CANNOT_CALL_INITIALIZE\");\n }\n\n modifier notFinalized() {\n require(isNotFinalized(), \"IMPLEMENTATION_FINALIZED\");\n _;\n }\n\n /*\n Forbids calling the function if the implementation is frozen.\n This modifier relies on the lower level (logical contract) implementation of isFrozen().\n */\n modifier notFrozen() {\n require(!implementationIsFrozen(), \"STATE_IS_FROZEN\");\n _;\n }\n\n /*\n This entry point serves only transactions with empty calldata. (i.e. pure value transfer tx).\n We don\u0027t expect to receive such, thus block them.\n */\n receive() external payable {\n revert(\"CONTRACT_NOT_EXPECTED_TO_RECEIVE\");\n }\n\n /*\n Contract\u0027s default function. Delegates execution to the implementation contract.\n It returns back to the external caller whatever the implementation delegated code returns.\n */\n fallback() external payable {\n address _implementation = implementation();\n require(_implementation != address(0x0), \"MISSING_IMPLEMENTATION\");\n\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 for now, as we don\u0027t know the out size yet.\n let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /*\n Sets the implementation address of the proxy.\n */\n function setImplementation(address newImplementation) private {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n sstore(slot, newImplementation)\n }\n }\n\n /*\n Returns true if the contract is not in the finalized state.\n */\n function isNotFinalized() public view returns (bool notFinal) {\n bytes32 slot = FINALIZED_STATE_SLOT;\n uint256 slotValue;\n assembly {\n slotValue := sload(slot)\n }\n notFinal = (slotValue == 0);\n }\n\n /*\n Marks the current implementation as finalized.\n */\n function setFinalizedFlag() private {\n bytes32 slot = FINALIZED_STATE_SLOT;\n assembly {\n sstore(slot, 0x1)\n }\n }\n\n /*\n Introduce an implementation and its initialization vector,\n and start the time-lock before it can be upgraded to.\n addImplementation is not blocked when frozen or finalized.\n (upgradeTo API is blocked when finalized or frozen).\n */\n function addImplementation(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n\n uint256 activationTime = block.timestamp + getUpgradeActivationDelay();\n\n // First implementation should not have time-lock.\n if (implementation() == address(0x0)) {\n activationTime = block.timestamp;\n }\n\n enabledTime[implVectorHash] = activationTime;\n emit ImplementationAdded(newImplementation, data, finalize);\n }\n\n /*\n Removes a candidate implementation.\n Note that it is possible to remove the current implementation. Doing so doesn\u0027t affect the\n current implementation, but rather revokes it as a future candidate.\n */\n function removeImplementation(\n address removedImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n bytes32 implVectorHash = keccak256(abi.encode(removedImplementation, data, finalize));\n\n // If we have initializer, we set the hash of it.\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n delete enabledTime[implVectorHash];\n emit ImplementationRemoved(removedImplementation, data, finalize);\n }\n\n /*\n Upgrades the proxy to a new implementation, with its initialization.\n to upgrade successfully, implementation must have been added time-lock agreeably\n before, and the init vector must be identical ot the one submitted before.\n\n Upon assignment of new implementation address,\n its initialize will be called with the initializing vector (even if empty).\n Therefore, the implementation MUST must have such a method.\n\n Note - Initialization data is committed to in advance, therefore it must remain valid\n until the actual contract upgrade takes place.\n\n Care should be taken regarding initialization data and flow when planning the contract upgrade.\n\n When planning contract upgrade, special care is also needed with regard to governance\n (See comments in Governance.sol).\n */\n // NOLINTNEXTLINE: reentrancy-events timestamp.\n function upgradeTo(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external payable onlyGovernance notFinalized notFrozen {\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n // NOLINTNEXTLINE: timestamp.\n require(activationTime \u003c= block.timestamp, \"UPGRADE_NOT_ENABLED_YET\");\n\n setImplementation(newImplementation);\n\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (bool success, bytes memory returndata) = newImplementation.delegatecall(\n abi.encodeWithSelector(this.initialize.selector, data)\n );\n require(success, string(returndata));\n\n // Verify that the new implementation is not frozen post initialization.\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (success, returndata) = newImplementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, \"CALL_TO_ISFROZEN_REVERTED\");\n require(!abi.decode(returndata, (bool)), \"NEW_IMPLEMENTATION_FROZEN\");\n\n if (finalize) {\n setFinalizedFlag();\n emit FinalizedImplementation(newImplementation);\n }\n\n emit ImplementationUpgraded(newImplementation, data);\n }\n}\n"},"ProxyGovernance.sol":{"content":"/*\n Copyright 2019-2021 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 Proxy 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:`proxyNominateNewGovernor`)\n 2. Remove other governors (:sol:func:`proxyRemoveGovernor`)\n 3. Add new `implementations` (proxied contracts)\n 4. Remove (new or old) `implementations`\n 5. Update `implementations` after a timelock allows it\n\n Adding governors is performed in a two step procedure:\n\n 1. First, an existing governor nominates a new governor (:sol:func:`proxyNominateNewGovernor`)\n 2. Then, the new governor must accept governance to become a governor (:sol:func:`proxyAcceptGovernance`)\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 or managed via a\n multi-sig contract.\n*/\n/*\n Implements Governance for the proxy contract.\n It is a thin wrapper to the Governance contract,\n which is needed so that it can have non-colliding function names,\n and a specific tag (key) to allow unique state storage.\n*/\ncontract ProxyGovernance is GovernanceStorage, Governance {\n // The tag is the string key that is used in the Governance storage mapping.\n string public constant PROXY_GOVERNANCE_TAG = \"StarkEx.Proxy.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[PROXY_GOVERNANCE_TAG];\n }\n\n function proxyIsGovernor(address testGovernor) external view returns (bool) {\n return isGovernor(testGovernor);\n }\n\n function proxyNominateNewGovernor(address newGovernor) external {\n nominateNewGovernor(newGovernor);\n }\n\n function proxyRemoveGovernor(address governorForRemoval) external {\n removeGovernor(governorForRemoval);\n }\n\n function proxyAcceptGovernance() external {\n acceptGovernance();\n }\n\n function proxyCancelNomination() external {\n cancelNomination();\n }\n}\n"},"ProxyStorage.sol":{"content":"/*\n Copyright 2019-2021 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 \"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 =\u003e bytes32) internal initializationHash_DEPRECATED;\n\n // The time after which we can switch to the implementation.\n // Hash(implementation, data, finalize) =\u003e time.\n mapping(bytes32 =\u003e 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 =\u003e bool) internal initialized;\n}\n"},"StorageSlots.sol":{"content":"/*\n Copyright 2019-2021 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 StorageSlots holds the arbitrary storage slots used throughout the Proxy pattern.\n Storage address slots are a mechanism to define an arbitrary location, that will not be\n overlapped by the logical contracts.\n*/\ncontract StorageSlots {\n // Storage slot with the address of the current implementation.\n // The address of the slot is keccak256(\"StarkWare2019.implemntation-slot\").\n // We need to keep this variable stored outside of the commonly used space,\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant IMPLEMENTATION_SLOT =\n 0x177667240aeeea7e35eabe3a35e18306f336219e1386f7710a6bf8783f761b24;\n\n // Storage slot with the address of the call-proxy current implementation.\n // The address of the slot is keccak256(\"\u0027StarkWare2020.CallProxy.Implemntation.Slot\u0027\").\n // We need to keep this variable stored outside of the commonly used space.\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant CALL_PROXY_IMPL_SLOT =\n 0x7184681641399eb4ad2fdb92114857ee6ff239f94ad635a1779978947b8843be;\n\n // This storage slot stores the finalization flag.\n // Once the value stored in this slot is set to non-zero\n // the proxy blocks implementation upgrades.\n // The current implementation is then referred to as Finalized.\n // Web3.solidityKeccak([\u0027string\u0027], [\"StarkWare2019.finalization-flag-slot\"]).\n bytes32 internal constant FINALIZED_STATE_SLOT =\n 0x7d433c6f837e8f93009937c466c82efbb5ba621fae36886d0cac433c5d0aa7d2;\n\n // Storage slot to hold the upgrade delay (time-lock).\n // The intention of this slot is to allow modification using an EIC.\n // Web3.solidityKeccak([\u0027string\u0027], [\u0027StarkWare.Upgradibility.Delay.Slot\u0027]).\n bytes32 public constant UPGRADE_DELAY_SLOT =\n 0xc21dbb3089fcb2c4f4c6a67854ab4db2b0f233ea4b21b21f912d52d18fc5db1f;\n}\n"}}
File 3 of 4: StarknetEthBridge
/* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: MIT // Based on OpenZeppelin Contract (access/AccessControl.sol) // StarkWare modification (storage slot, change to library). pragma solidity ^0.8.0; import "third_party/open_zeppelin/utils/Strings.sol"; /* Library module that allows using contracts to implement role-based access control mechanisms. This is a lightweight version that doesn't allow enumerating role members except through off-chain means by accessing the contract event logs. Some applications may benefit from on-chain enumerability, for those cases see {AccessControlEnumerable}. Roles are referred to by their `bytes32` identifier. These should be exposed in the external API and be unique. The best way to achieve this is by using `public constant` hash digests: ``` bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); ``` Roles can be used to represent a set of permissions. To restrict access to a function call, use {hasRole}: ``` function foo() public { require(hasRole(MY_ROLE, msg.sender)); ... } ``` Roles can be granted and revoked dynamically via the {grantRole} and {revokeRole} functions. Each role has an associated admin role, and only accounts that have a role's admin role can call {grantRole} and {revokeRole}. By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means that only accounts with this role will be able to grant or revoke other roles. More complex role relationships can be created by using {_setRoleAdmin}. WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to grant and revoke this role. Extra precautions should be taken to secure accounts that have been granted it. OpenZeppelin implementation changed as following: 1. Converted to library. 2. Storage valiable {_roles} moved outside of linear storage, to avoid potential storage conflicts or corruption. 3. Removed ERC165 support. */ library AccessControl { /* Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite {RoleAdminChanged} not being emitted signaling this. Available since v3.1. */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /* Emitted when `account` is granted `role`. `sender` is the account that originated the contract call, an admin role bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /* Emitted when `account` is revoked `role`. `sender` is the account that originated the contract call: - if using `revokeRole`, it is the admin role bearer - if using `renounceRole`, it is the role bearer (i.e. `account`). */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); struct RoleData { mapping(address => bool) members; bytes32 adminRole; } // Context interface functions. function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal pure returns (bytes calldata) { return msg.data; } // The storage variable `_roles` is located away from the contract linear area (low storage addresses) // to prevent potential collision/corruption in upgrade scenario. // Slot = Web3.keccak(text="AccesControl_Storage_Slot"). bytes32 constant rolesSlot = 0x53e43b954ba190a7e49386f1f78b01dcd9f628db23f432fa029a7dfd6d98e8fb; function _roles() private pure returns (mapping(bytes32 => RoleData) storage roles) { assembly { roles.slot := rolesSlot } } bytes32 constant DEFAULT_ADMIN_ROLE = 0x00; /* Modifier that checks that an account has a specific role. Reverts with a standardized message including the required role. The format of the revert reason is given by the following regular expression: /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ Available since v4.1. */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /* Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) internal view returns (bool) { return _roles()[role].members[account]; } /* Revert with a standard message if `_msgSender()` is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier. Format of the revert message is described in {_checkRole}. Available since v4.6. */ function _checkRole(bytes32 role) internal view { _checkRole(role, _msgSender()); } /* Revert with a standard message if `account` is missing `role`. The format of the revert reason is given by the following regular expression: /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/. */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /* Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) internal view returns (bytes32) { return _roles()[role].adminRole; } /* Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) internal onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /* Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) internal onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /* Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `account`. May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address account) internal { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /* Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Note that unlike {grantRole}, this function doesn't perform any checks on the calling account. May emit a {RoleGranted} event. [WARNING]virtual ==== This function should only be called from the constructor when setting up the initial roles for the system. Using this function in any other way is effectively circumventing the admin system imposed by {AccessControl}. ==== NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal { _grantRole(role, account); } /* Sets `adminRole` as ``role``'s admin role. Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { bytes32 previousAdminRole = getRoleAdmin(role); _roles()[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /* Grants `role` to `account`. Internal function without access restriction. May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles()[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /* Revokes `role` from `account`. Internal function without access restriction. May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles()[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; /* Common Utility Libraries. I. Addresses (extending address). */ library Addresses { /* Note: isContract function has some known limitation. See https://github.com/OpenZeppelin/ openzeppelin-contracts/blob/master/contracts/utils/Address.sol. */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function performEthTransfer(address recipient, uint256 amount) internal { if (amount == 0) return; (bool success, ) = recipient.call{value: amount}(""); // NOLINT: low-level-calls. require(success, "ETH_TRANSFER_FAILED"); } /* Safe wrapper around ERC20/ERC721 calls. This is required because many deployed ERC20 contracts don't return a value. See https://github.com/ethereum/solidity/issues/4116. */ function safeTokenContractCall(address tokenAddress, bytes memory callData) internal { require(isContract(tokenAddress), "BAD_TOKEN_ADDRESS"); // NOLINTNEXTLINE: low-level-calls. (bool success, bytes memory returndata) = tokenAddress.call(callData); require(success, string(returndata)); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED"); } } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; /* This contract provides means to block direct call of an external function. A derived contract (e.g. MainDispatcherBase) should decorate sensitive functions with the notCalledDirectly modifier, thereby preventing it from being called directly, and allowing only calling using delegate_call. */ abstract contract BlockDirectCall { address immutable this_; constructor() { this_ = address(this); } modifier notCalledDirectly() { require(this_ != address(this), "DIRECT_CALL_DISALLOWED"); _; } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; library CairoConstants { uint256 public constant FIELD_PRIME = 0x800000000000011000000000000000000000000000000000000000000000001; } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; /** Interface for contract initialization. The functions it exposes are the app specific parts of the contract initialization, and are called by the ProxySupport contract that implement the generic part of behind-proxy initialization. */ abstract contract ContractInitializer { /* The number of sub-contracts that the proxied contract consists of. */ function numOfSubContracts() internal pure virtual returns (uint256); /* Indicates if the proxied contract has already been initialized. Used to prevent re-init. */ function isInitialized() internal view virtual returns (bool); /* Validates the init data that is passed into the proxied contract. */ function validateInitData(bytes calldata data) internal view virtual; /* For a proxied contract that consists of sub-contracts, this function processes the sub-contract addresses, e.g. validates them, stores them etc. */ function processSubContractAddresses(bytes calldata subContractAddresses) internal virtual; /* This function applies the logic of initializing the proxied contract state, e.g. setting root values etc. */ function initializeContractState(bytes calldata data) internal virtual; } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; // Estimate cost for L1-L2 message handler. uint256 constant DEPOSIT_FEE_GAS = 20000; uint256 constant DEPLOYMENT_FEE_GAS = 100000; // We don't have a solid way to gauge block gas price // (block.basefee cannot be used). uint256 constant DEFAULT_WEI_PER_GAS = 5 * 10**9; abstract contract Fees { // Effectively no minimum fee on testnet. uint256 immutable MIN_FEE = (block.chainid == 1) ? 10**12 : 1; uint256 constant MAX_FEE = 10**16; function estimateDepositFee() internal pure returns (uint256) { return DEPOSIT_FEE_GAS * DEFAULT_WEI_PER_GAS; } function estimateEnrollmentFee() internal pure returns (uint256) { return DEPLOYMENT_FEE_GAS * DEFAULT_WEI_PER_GAS; } function checkFee(uint256 feeWei) internal view { require(feeWei >= MIN_FEE, "INSUFFICIENT_FEE_VALUE"); require(feeWei <= MAX_FEE, "FEE_VALUE_TOO_HIGH"); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/cairo/eth/CairoConstants.sol"; /** * @dev String to felt functions. * * These functions convert string to felt (felt252) uint value. * The felt value is the Starknet short string representation. * * As felt value is bound by the field prime, it limits the length of the represented string. * For felt252 the limit is 31 characters. * * `safeToFelt()` converts to felt as many as 31 characters of the string. * i.e. for a long string: safeToFelt(string) == toFelt(string[:31]). * * When `toFelt()` accepts a long string - it fails and the call revert. */ library Felt252 { uint256 constant MAX_SHORT_STRING_LENGTH = 31; /** Convert a string to felt uint value. Reverts if the string is longer than 31 characters. */ function toFelt(string memory shortString) internal pure returns (uint256) { uint256 length = strlen(shortString); return strToFelt(shortString, length); } /** Safely convert a string to felt uint value. For a string up to 31 characters, behaves identically ot `toFelt`. For longer strings, it returns the felt representation of the first 31 characters. */ function safeToFelt(string memory string_) internal pure returns (uint256) { uint256 len = min(MAX_SHORT_STRING_LENGTH, strlen(string_)); return strToFelt(string_, len); } function strToFelt(string memory string_, uint256 length) private pure returns (uint256) { require(length <= MAX_SHORT_STRING_LENGTH, "STRING_TOO_LONG"); uint256 asUint; // As we process only short strings (<=31 chars), // we can look no further than the first 32 bytes of the string. // We convert first 32 bytes of the string to a uint. assembly { asUint := mload(add(string_, 32)) } // We shift left the unused bits, so we don't get lsb zero padding. // The shift is 8 bits for every unused characters (of the looked at 32 bytes). uint256 felt252 = asUint >> (8 * (32 - length)); return felt252; } /** Returns string length. */ function strlen(string memory string_) private pure returns (uint256) { bytes memory bytes_; assembly { bytes_ := string_ } return bytes_.length; } function min(uint256 a, uint256 b) private pure returns (uint256) { return a < b ? a : b; } } library UintFelt252 { function isValidL2Address(uint256 l2Address) internal pure returns (bool) { return (l2Address != 0 && isFelt(l2Address)); } function isFelt(uint256 maybeFelt) internal pure returns (bool) { return (maybeFelt < CairoConstants.FIELD_PRIME); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; /** Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "./IERC20.sol"; /** Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** Returns the name of the token. */ function name() external view returns (string memory); /** Returns the symbol of the token. */ function symbol() external view returns (string memory); /** Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; interface IStarkgateBridge { /** Enrolls a token in the Starknet Token Bridge system. */ function enrollToken(address token) external payable; /** Deactivates token bridging. Deactivated token does not accept deposits. */ function deactivate(address token) external; } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; interface IStarkgateManager { /** Returns the address of the Starkgate Registry contract. */ function getRegistry() external view returns (address); /** Adds an existing bridge to the Starkgate system for a specific token. */ function addExistingBridge(address token, address bridge) external; /** Deactivates bridging of a specific token. A deactivated token is blocked for deposits and cannot be re-deployed. */ function deactivateToken(address token) external; /** Block a specific token from being used in the StarkGate. A blocked token cannot be deployed. */ function blockToken(address token) external; /** Enrolls a token bridge for a specific token. */ function enrollTokenBridge(address token) external payable; } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; interface IStarkgateRegistry { /** Returns the bridge that handles the given token. */ function getBridge(address token) external view returns (address); /** Add a mapping between a token and the bridge handling it. */ function enlistToken(address token, address bridge) external; /** Block a specific token from being used in the StarkGate. A blocked token cannot be deployed. */ function blockToken(address token) external; /** Retrieves a list of bridge addresses that have facilitated withdrawals for the specified token. */ function getWithdrawalBridges(address token) external view returns (address[] memory bridges); /** Using this function a bridge removes enlisting of its token from the registry. The bridge must implement `isServicingToken(address token)` (see `IStarkgateService`). */ function selfRemove(address token) external; } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; interface IStarkgateService { /** Checks whether the calling contract is providing a service for the specified token. Returns True if the calling contract is providing a service for the token, otherwise false. */ function isServicingToken(address token) external view returns (bool); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/starknet/solidity/IStarknetMessagingEvents.sol"; interface IStarknetMessaging is IStarknetMessagingEvents { /** Returns the max fee (in Wei) that StarkNet will accept per single message. */ function getMaxL1MsgFee() external pure returns (uint256); /** Returns the msg_fee + 1 for the message with the given 'msgHash', or 0 if no message with such a hash is pending. */ function l1ToL2Messages(bytes32 msgHash) external view returns (uint256); /** Sends a message to an L2 contract. This function is payable, the payed amount is the message fee. Returns the hash of the message and the nonce of the message. */ function sendMessageToL2( uint256 toAddress, uint256 selector, uint256[] calldata payload ) external payable returns (bytes32, uint256); /** Consumes a message that was sent from an L2 contract. Returns the hash of the message. */ function consumeMessageFromL2(uint256 fromAddress, uint256[] calldata payload) external returns (bytes32); /** Starts the cancellation of an L1 to L2 message. A message can be canceled messageCancellationDelay() seconds after this function is called. Note: This function may only be called for a message that is currently pending and the caller must be the sender of the that message. */ function startL1ToL2MessageCancellation( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external returns (bytes32); /** Cancels an L1 to L2 message, this function should be called at least messageCancellationDelay() seconds after the call to startL1ToL2MessageCancellation(). A message may only be cancelled by its sender. If the message is missing, the call will revert. Note that the message fee is not refunded. */ function cancelL1ToL2Message( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external returns (bytes32); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; interface IStarknetMessagingEvents { // This event needs to be compatible with the one defined in Output.sol. event LogMessageToL1(uint256 indexed fromAddress, address indexed toAddress, uint256[] payload); // An event that is raised when a message is sent from L1 to L2. event LogMessageToL2( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce, uint256 fee ); // An event that is raised when a message from L2 to L1 is consumed. event ConsumedMessageToL1( uint256 indexed fromAddress, address indexed toAddress, uint256[] payload ); // An event that is raised when a message from L1 to L2 is consumed. event ConsumedMessageToL2( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); // An event that is raised when a message from L1 to L2 Cancellation is started. event MessageToL2CancellationStarted( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); // An event that is raised when a message from L1 to L2 is canceled. event MessageToL2Canceled( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; interface Identity { /* Allows a caller to ensure that the provided address is of the expected type and version. */ function identify() external pure returns (string memory); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.20; import "src/solidity/StarknetTokenBridge.sol"; import "starkware/solidity/components/OverrideLegacyProxyGovernance.sol"; import "starkware/solidity/libraries/NamedStorage.sol"; /* Common implementation for the Upgraded legacy bridges, contains all the legacy relevant code except for the handling of Eth transfers (vs. ERC20). */ abstract contract LegacyBridge is StarknetTokenBridge, OverrideLegacyProxyGovernance { /* Legacy events */ event LogDepositCancelRequest( address indexed sender, uint256 amount, uint256 indexed l2Recipient, uint256 nonce ); event LogDepositReclaimed( address indexed sender, uint256 amount, uint256 indexed l2Recipient, uint256 nonce ); event LogDeposit( address indexed sender, uint256 amount, uint256 indexed l2Recipient, uint256 nonce, uint256 fee ); function bridgedToken() internal view returns (address) { return NamedStorage.getAddressValue(BRIDGED_TOKEN_TAG); } function depositors() internal pure returns (mapping(uint256 => address) storage) { return NamedStorage.uintToAddressMapping(DEPOSITOR_ADDRESSES_TAG); } modifier onlyDepositor(uint256 nonce) { require(depositors()[nonce] == msg.sender, "ONLY_DEPOSITOR"); _; } /* Upgraded legacy bridge does not support token enrollment. */ function enrollToken( address /*token*/ ) external payable virtual override { revert("UNSUPPORTED"); } /// Support Legacy ABI. /* Deposit, using the old version ABI. Note - The actual L1-L2 message sent to the l2-bridge is of the new format. */ function deposit(uint256 amount, uint256 l2Recipient) external payable { uint256[] memory noMessage = new uint256[](0); address token = bridgedToken(); uint256 fee = acceptDeposit(token, amount); uint256 nonce = sendDepositMessage( token, amount, l2Recipient, noMessage, HANDLE_TOKEN_DEPOSIT_SELECTOR, fee ); emitDepositEvent( token, amount, l2Recipient, noMessage, HANDLE_TOKEN_DEPOSIT_SELECTOR, nonce, fee ); // Emits a deposit event of the old ABI, emitted in addition to the new one. emit LogDeposit(msg.sender, amount, l2Recipient, nonce, fee); } function maxTotalBalance() external view returns (uint256) { return getMaxTotalBalance(bridgedToken()); } function withdraw(uint256 amount, address recipient) external { withdraw(bridgedToken(), amount, recipient); } function withdraw(uint256 amount) external { withdraw(bridgedToken(), amount, msg.sender); } /* This comsume message override the base implementation from StarknetTokenBridge, and supports withdraw of both the new format and the legacy format. */ function consumeMessage( address token, uint256 amount, address recipient ) internal virtual override { require(l2TokenBridge() != 0, "L2_BRIDGE_NOT_SET"); uint256 u_recipient = uint256(uint160(recipient)); uint256 amount_low = amount & (UINT256_PART_SIZE - 1); uint256 amount_high = amount >> UINT256_PART_SIZE_BITS; // Compose the new format of L2-L1 consumption. uint256[] memory payload = new uint256[](5); payload[0] = TRANSFER_FROM_STARKNET; payload[1] = u_recipient; payload[2] = uint256(uint160(token)); payload[3] = amount_low; payload[4] = amount_high; // Contain failure of comsumption (e.g. no message to consume). try messagingContract().consumeMessageFromL2(l2TokenBridge(), payload) {} catch Error( string memory ) { // Upon failure with the new format, // compose the old format, // in case the withdrawal was initiated on a bridge with an older version. payload = new uint256[](4); payload[0] = TRANSFER_FROM_STARKNET; payload[1] = u_recipient; payload[2] = amount_low; payload[3] = amount_high; messagingContract().consumeMessageFromL2(l2TokenBridge(), payload); } } // The old version of depositCancelRequest (renamed to avoid confusion). // Supports cancellation of deposits that were made before the L1 bridge was upgraded. function legacyDepositCancelRequest( uint256 amount, uint256 l2Recipient, uint256 nonce ) external onlyDepositor(nonce) { messagingContract().startL1ToL2MessageCancellation( l2TokenBridge(), HANDLE_DEPOSIT_SELECTOR, legacyDepositMessagePayload(amount, l2Recipient), nonce ); emit LogDepositCancelRequest(msg.sender, amount, l2Recipient, nonce); } // The old version of depositReclaim (renamed to avoid confusion). // Supports reclaim of deposits that were made before the L1 bridge was upgraded. function legacyDepositReclaim( uint256 amount, uint256 l2Recipient, uint256 nonce ) external onlyDepositor(nonce) { messagingContract().cancelL1ToL2Message( l2TokenBridge(), HANDLE_DEPOSIT_SELECTOR, legacyDepositMessagePayload(amount, l2Recipient), nonce ); transferOutFunds(bridgedToken(), amount, msg.sender); emit LogDepositReclaimed(msg.sender, amount, l2Recipient, nonce); } // Construct the deposit l1-l2 message payload of the older version. // (renamed to avoid confusion). function legacyDepositMessagePayload(uint256 amount, uint256 l2Recipient) private pure returns (uint256[] memory) { uint256[] memory payload = new uint256[](3); payload[0] = l2Recipient; payload[1] = amount & (UINT256_PART_SIZE - 1); payload[2] = amount >> UINT256_PART_SIZE_BITS; return payload; } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; /* Library to provide basic storage, in storage location out of the low linear address space. New types of storage variables should be added here upon need. */ library NamedStorage { function bytes32ToBoolMapping(string memory tag_) internal pure returns (mapping(bytes32 => bool) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function bytes32ToUint256Mapping(string memory tag_) internal pure returns (mapping(bytes32 => uint256) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function addressToUint256Mapping(string memory tag_) internal pure returns (mapping(address => uint256) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function bytes32ToAddressMapping(string memory tag_) internal pure returns (mapping(bytes32 => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function uintToAddressMapping(string memory tag_) internal pure returns (mapping(uint256 => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function addressToAddressMapping(string memory tag_) internal pure returns (mapping(address => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function addressToAddressListMapping(string memory tag_) internal pure returns (mapping(address => address[]) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function addressToBoolMapping(string memory tag_) internal pure returns (mapping(address => bool) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function getUintValue(string memory tag_) internal view returns (uint256 retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setUintValue(string memory tag_, uint256 value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } function setUintValueOnce(string memory tag_, uint256 value) internal { require(getUintValue(tag_) == 0, "ALREADY_SET"); setUintValue(tag_, value); } function getAddressValue(string memory tag_) internal view returns (address retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setAddressValue(string memory tag_, address value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } function setAddressValueOnce(string memory tag_, address value) internal { require(getAddressValue(tag_) == address(0x0), "ALREADY_SET"); setAddressValue(tag_, value); } function getBoolValue(string memory tag_) internal view returns (bool retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setBoolValue(string memory tag_, bool value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/libraries/RolesLib.sol"; struct GovernanceInfoStruct { mapping(address => bool) effectiveGovernors; address candidateGovernor; bool initialized; } // PROXY_GOVERNANCE_TAG = "StarkEx.Proxy.2019.GovernorsInformation" // LEGACY_PROXY_GOVERNOR_SLOT = Web3.solidityKeccak(["string", "uint256"], [PROXY_GOVERNANCE_TAG, 0]) . bytes32 constant LEGACY_PROXY_GOVERNOR_SLOT = 0x45f38e273862f8834bd2fe7a449988f63de55a7a5b685dea46ccedeb69cf0e26; /** This contract allows the governance admin (which is the top of the `Roles` heirarchy), to override the proxy governance. */ abstract contract OverrideLegacyProxyGovernance { event LogNewGovernorAccepted(address acceptedGovernor); event LogRemovedGovernor(address removedGovernor); modifier GovernanceAdminOnly() { require( AccessControl.hasRole(GOVERNANCE_ADMIN, AccessControl._msgSender()), "GOVERNANCE_ADMIN_ONLY" ); _; } function legacyProxyGovInfo() private pure returns (GovernanceInfoStruct storage gov) { bytes32 location = LEGACY_PROXY_GOVERNOR_SLOT; assembly { gov.slot := location } } /* Assigns `account` as proxy governor and clears pending govneror candidate. */ function assignLegacyProxyGovernor(address account) external GovernanceAdminOnly { GovernanceInfoStruct storage legacyProxyGov = legacyProxyGovInfo(); legacyProxyGov.effectiveGovernors[account] = true; delete legacyProxyGov.candidateGovernor; emit LogNewGovernorAccepted(account); } /* Removes `account` from proxy governor role and clears pending govneror candidate. */ function removeLegacyProxyGovernor(address account) external GovernanceAdminOnly { GovernanceInfoStruct storage legacyProxyGov = legacyProxyGovInfo(); legacyProxyGov.effectiveGovernors[account] = false; delete legacyProxyGov.candidateGovernor; emit LogRemovedGovernor(account); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/components/Roles.sol"; import "starkware/solidity/libraries/RolesLib.sol"; import "starkware/solidity/libraries/Addresses.sol"; import "starkware/solidity/interfaces/BlockDirectCall.sol"; import "starkware/solidity/interfaces/ContractInitializer.sol"; /** This contract contains the code commonly needed for a contract to be deployed behind an upgradability proxy. It perform the required semantics of the proxy pattern, but in a generic manner. */ abstract contract ProxySupport is BlockDirectCall, ContractInitializer, Roles(true) { using Addresses for address; // The two function below (isFrozen & initialize) needed to bind to the Proxy. function isFrozen() external view virtual returns (bool) { return false; } /* The initialize() function serves as an alternative constructor for a proxied deployment. Flow and notes: 1. This function cannot be called directly on the deployed contract, but only via delegate call. 2. If an EIC is provided - init is passed onto EIC and the standard init flow is skipped. This true for both first intialization or a later one. 3. The data passed to this function is as follows: [sub_contracts addresses, eic address, initData]. When calling on an initialized contract (no EIC scenario), initData.length must be 0. */ function initialize(bytes calldata data) external notCalledDirectly { uint256 eicOffset = 32 * numOfSubContracts(); uint256 expectedBaseSize = eicOffset + 32; require(data.length >= expectedBaseSize, "INIT_DATA_TOO_SMALL"); address eicAddress = abi.decode(data[eicOffset:expectedBaseSize], (address)); bytes calldata subContractAddresses = data[:eicOffset]; processSubContractAddresses(subContractAddresses); bytes calldata initData = data[expectedBaseSize:]; // EIC Provided - Pass initData to EIC and the skip standard init flow. if (eicAddress != address(0x0)) { callExternalInitializer(eicAddress, initData); return; } if (isInitialized()) { require(initData.length == 0, "UNEXPECTED_INIT_DATA"); } else { // Contract was not initialized yet. validateInitData(initData); initializeContractState(initData); RolesLib.initialize(); } } function callExternalInitializer(address externalInitializerAddr, bytes calldata eicData) private { require(externalInitializerAddr.isContract(), "EIC_NOT_A_CONTRACT"); // NOLINTNEXTLINE: low-level-calls, controlled-delegatecall. (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall( abi.encodeWithSelector(this.initialize.selector, eicData) ); require(success, string(returndata)); require(returndata.length == 0, string(returndata)); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/libraries/RolesLib.sol"; abstract contract Roles { // This flag dermine if the GOVERNANCE_ADMIN role can be renounced. bool immutable fullyRenouncable; constructor(bool renounceable) { fullyRenouncable = renounceable; RolesLib.initialize(); } // MODIFIERS. modifier onlyAppGovernor() { require(isAppGovernor(AccessControl._msgSender()), "ONLY_APP_GOVERNOR"); _; } modifier onlyOperator() { require(isOperator(AccessControl._msgSender()), "ONLY_OPERATOR"); _; } modifier onlySecurityAdmin() { require(isSecurityAdmin(AccessControl._msgSender()), "ONLY_SECURITY_ADMIN"); _; } modifier onlySecurityAgent() { require(isSecurityAgent(AccessControl._msgSender()), "ONLY_SECURITY_AGENT"); _; } modifier onlyTokenAdmin() { require(isTokenAdmin(AccessControl._msgSender()), "ONLY_TOKEN_ADMIN"); _; } modifier onlyUpgradeGovernor() { require(isUpgradeGovernor(AccessControl._msgSender()), "ONLY_UPGRADE_GOVERNOR"); _; } modifier notSelf(address account) { require(account != AccessControl._msgSender(), "CANNOT_PERFORM_ON_SELF"); _; } // Is holding role. function isAppGovernor(address account) public view returns (bool) { return AccessControl.hasRole(APP_GOVERNOR, account); } function isAppRoleAdmin(address account) public view returns (bool) { return AccessControl.hasRole(APP_ROLE_ADMIN, account); } function isGovernanceAdmin(address account) public view returns (bool) { return AccessControl.hasRole(GOVERNANCE_ADMIN, account); } function isOperator(address account) public view returns (bool) { return AccessControl.hasRole(OPERATOR, account); } function isSecurityAdmin(address account) public view returns (bool) { return AccessControl.hasRole(SECURITY_ADMIN, account); } function isSecurityAgent(address account) public view returns (bool) { return AccessControl.hasRole(SECURITY_AGENT, account); } function isTokenAdmin(address account) public view returns (bool) { return AccessControl.hasRole(TOKEN_ADMIN, account); } function isUpgradeGovernor(address account) public view returns (bool) { return AccessControl.hasRole(UPGRADE_GOVERNOR, account); } // Register Role. function registerAppGovernor(address account) external { AccessControl.grantRole(APP_GOVERNOR, account); } function registerAppRoleAdmin(address account) external { AccessControl.grantRole(APP_ROLE_ADMIN, account); } function registerGovernanceAdmin(address account) external { AccessControl.grantRole(GOVERNANCE_ADMIN, account); } function registerOperator(address account) external { AccessControl.grantRole(OPERATOR, account); } function registerSecurityAdmin(address account) external { AccessControl.grantRole(SECURITY_ADMIN, account); } function registerSecurityAgent(address account) external { AccessControl.grantRole(SECURITY_AGENT, account); } function registerTokenAdmin(address account) external { AccessControl.grantRole(TOKEN_ADMIN, account); } function registerUpgradeGovernor(address account) external { AccessControl.grantRole(UPGRADE_GOVERNOR, account); } // Revoke Role. function revokeAppGovernor(address account) external { AccessControl.revokeRole(APP_GOVERNOR, account); } function revokeAppRoleAdmin(address account) external notSelf(account) { AccessControl.revokeRole(APP_ROLE_ADMIN, account); } function revokeGovernanceAdmin(address account) external notSelf(account) { AccessControl.revokeRole(GOVERNANCE_ADMIN, account); } function revokeOperator(address account) external { AccessControl.revokeRole(OPERATOR, account); } function revokeSecurityAdmin(address account) external notSelf(account) { AccessControl.revokeRole(SECURITY_ADMIN, account); } function revokeSecurityAgent(address account) external { AccessControl.revokeRole(SECURITY_AGENT, account); } function revokeTokenAdmin(address account) external { AccessControl.revokeRole(TOKEN_ADMIN, account); } function revokeUpgradeGovernor(address account) external { AccessControl.revokeRole(UPGRADE_GOVERNOR, account); } // Renounce Role. function renounceRole(bytes32 role, address account) external { if (role == GOVERNANCE_ADMIN && !fullyRenouncable) { revert("CANNOT_RENOUNCE_GOVERNANCE_ADMIN"); } AccessControl.renounceRole(role, account); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/libraries/AccessControl.sol"; // int.from_bytes(Web3.keccak(text="ROLE_APP_GOVERNOR"), "big") & MASK_250 . bytes32 constant APP_GOVERNOR = bytes32( uint256(0xd2ead78c620e94b02d0a996e99298c59ddccfa1d8a0149080ac3a20de06068) ); // int.from_bytes(Web3.keccak(text="ROLE_APP_ROLE_ADMIN"), "big") & MASK_250 . bytes32 constant APP_ROLE_ADMIN = bytes32( uint256(0x03e615638e0b79444a70f8c695bf8f2a47033bf1cf95691ec3130f64939cee99) ); // int.from_bytes(Web3.keccak(text="ROLE_GOVERNANCE_ADMIN"), "big") & MASK_250 . bytes32 constant GOVERNANCE_ADMIN = bytes32( uint256(0x03711c9d994faf6055172091cb841fd4831aa743e6f3315163b06a122c841846) ); // int.from_bytes(Web3.keccak(text="ROLE_OPERATOR"), "big") & MASK_250 . bytes32 constant OPERATOR = bytes32( uint256(0x023edb77f7c8cc9e38e8afe78954f703aeeda7fffe014eeb6e56ea84e62f6da7) ); // int.from_bytes(Web3.keccak(text="ROLE_SECURITY_ADMIN"), "big") & MASK_250 . bytes32 constant SECURITY_ADMIN = bytes32( uint256(0x026bd110619d11cfdfc28e281df893bc24828e89177318e9dbd860cdaedeb6b3) ); // int.from_bytes(Web3.keccak(text="ROLE_SECURITY_AGENT"), "big") & MASK_250 . bytes32 constant SECURITY_AGENT = bytes32( uint256(0x037693ba312785932d430dccf0f56ffedd0aa7c0f8b6da2cc4530c2717689b96) ); // int.from_bytes(Web3.keccak(text="ROLE_TOKEN_ADMIN"), "big") & MASK_250 . bytes32 constant TOKEN_ADMIN = bytes32( uint256(0x0128d63adbf6b09002c26caf55c47e2f26635807e3ef1b027218aa74c8d61a3e) ); // int.from_bytes(Web3.keccak(text="ROLE_UPGRADE_GOVERNOR"), "big") & MASK_250 . bytes32 constant UPGRADE_GOVERNOR = bytes32( uint256(0x0251e864ca2a080f55bce5da2452e8cfcafdbc951a3e7fff5023d558452ec228) ); /* Role | Role Admin ---------------------------------------- GOVERNANCE_ADMIN | GOVERNANCE_ADMIN UPGRADE_GOVERNOR | GOVERNANCE_ADMIN APP_ROLE_ADMIN | GOVERNANCE_ADMIN APP_GOVERNOR | APP_ROLE_ADMIN OPERATOR | APP_ROLE_ADMIN TOKEN_ADMIN | APP_ROLE_ADMIN SECURITY_ADMIN | SECURITY_ADMIN SECURITY_AGENT | SECURITY_ADMIN . */ library RolesLib { // INITIALIZERS. function governanceRolesInitialized() internal view returns (bool) { return AccessControl.getRoleAdmin(GOVERNANCE_ADMIN) != bytes32(0x00); } function securityRolesInitialized() internal view returns (bool) { return AccessControl.getRoleAdmin(SECURITY_ADMIN) != bytes32(0x00); } function initialize() internal { address provisional = AccessControl._msgSender(); initialize(provisional, provisional); } function initialize(address provisionalGovernor, address provisionalSecAdmin) internal { if (governanceRolesInitialized()) { // Support Proxied contract initialization. // In case the Proxy already initialized the roles, // init will succeed IFF the provisionalGovernor is already `GovernanceAdmin`. require( AccessControl.hasRole(GOVERNANCE_ADMIN, provisionalGovernor), "ROLES_ALREADY_INITIALIZED" ); } else { initGovernanceRoles(provisionalGovernor); } if (securityRolesInitialized()) { // If SecurityAdmin initialized, // then provisionalSecAdmin must already be a `SecurityAdmin`. // If it's not initilized - initialize it. require( AccessControl.hasRole(SECURITY_ADMIN, provisionalSecAdmin), "SECURITY_ROLES_ALREADY_INITIALIZED" ); } else { initSecurityRoles(provisionalSecAdmin); } } function initSecurityRoles(address provisionalSecAdmin) private { AccessControl._setRoleAdmin(SECURITY_ADMIN, SECURITY_ADMIN); AccessControl._setRoleAdmin(SECURITY_AGENT, SECURITY_ADMIN); AccessControl._grantRole(SECURITY_ADMIN, provisionalSecAdmin); } function initGovernanceRoles(address provisionalGovernor) private { AccessControl._grantRole(GOVERNANCE_ADMIN, provisionalGovernor); AccessControl._setRoleAdmin(APP_GOVERNOR, APP_ROLE_ADMIN); AccessControl._setRoleAdmin(APP_ROLE_ADMIN, GOVERNANCE_ADMIN); AccessControl._setRoleAdmin(GOVERNANCE_ADMIN, GOVERNANCE_ADMIN); AccessControl._setRoleAdmin(OPERATOR, APP_ROLE_ADMIN); AccessControl._setRoleAdmin(TOKEN_ADMIN, APP_ROLE_ADMIN); AccessControl._setRoleAdmin(UPGRADE_GOVERNOR, GOVERNANCE_ADMIN); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.20; // Starknet L1 handler selectors. uint256 constant HANDLE_DEPOSIT_SELECTOR = 1285101517810983806491589552491143496277809242732141897358598292095611420389; uint256 constant HANDLE_TOKEN_DEPOSIT_SELECTOR = 774397379524139446221206168840917193112228400237242521560346153613428128537; uint256 constant HANDLE_DEPOSIT_WITH_MESSAGE_SELECTOR = 247015267890530308727663503380700973440961674638638362173641612402089762826; uint256 constant HANDLE_TOKEN_DEPLOYMENT_SELECTOR = 1737780302748468118210503507461757847859991634169290761669750067796330642876; uint256 constant TRANSFER_FROM_STARKNET = 0; uint256 constant UINT256_PART_SIZE_BITS = 128; uint256 constant UINT256_PART_SIZE = 2**UINT256_PART_SIZE_BITS; uint256 constant MAX_PENDING_DURATION = 5 days; address constant BLOCKED_TOKEN = address(0x1); // Cairo felt252 value (short string) of 'ETH' address constant ETH = address(0x455448); /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.20; import "starkware/solidity/components/Roles.sol"; import "starkware/solidity/interfaces/Identity.sol"; import "starkware/solidity/interfaces/ProxySupport.sol"; import "starkware/solidity/libraries/Addresses.sol"; import "starkware/solidity/libraries/NamedStorage.sol"; import "src/solidity/IStarkgateBridge.sol"; import "src/solidity/IStarkgateManager.sol"; import "src/solidity/IStarkgateRegistry.sol"; import "src/solidity/StarkgateConstants.sol"; contract StarkgateManager is Identity, IStarkgateManager, ProxySupport { using Addresses for address; // Named storage slot tags. string internal constant REGISTRY_TAG = "STARKGATE_MANAGER_REGISTRY_SLOT_TAG"; string internal constant BRIDGE_TAG = "STARKGATE_MANAGER_BRIDGE_SLOT_TAG"; event TokenEnrolled(address indexed token, address indexed sender); event ExistingBridgeAdded(address indexed token, address indexed bridge); event TokenDeactivated(address indexed token, address indexed sender); event TokenBlocked(address indexed token, address indexed sender); function getRegistry() external view returns (address) { return registry(); } // Storage Getters. // TODO : add doc. function registry() internal view returns (address) { return NamedStorage.getAddressValue(REGISTRY_TAG); } function bridge() internal view returns (address) { return NamedStorage.getAddressValue(BRIDGE_TAG); } // Storage Setters. function setRegistry(address contract_) internal { NamedStorage.setAddressValueOnce(REGISTRY_TAG, contract_); } function setBridge(address contract_) internal { NamedStorage.setAddressValueOnce(BRIDGE_TAG, contract_); } function identify() external pure override returns (string memory) { return "StarkWare_StarkgateManager_2.0_1"; } /* Initializes the contract. */ function initializeContractState(bytes calldata data) internal override { (address registry_, address bridge_) = abi.decode(data, (address, address)); setRegistry(registry_); setBridge(bridge_); } function isInitialized() internal view override returns (bool) { return registry() != address(0); } function numOfSubContracts() internal pure override returns (uint256) { return 0; } /* No processing needed, as there are no sub-contracts to this contract. */ function processSubContractAddresses(bytes calldata subContractAddresses) internal override {} function validateInitData(bytes calldata data) internal view virtual override { require(data.length == 64, "ILLEGAL_DATA_SIZE"); (address registry_, address bridge_) = abi.decode(data, (address, address)); require(registry_.isContract(), "INVALID_REGISTRY_CONTRACT_ADDRESS"); require(bridge_.isContract(), "INVALID_BRIDGE_CONTRACT_ADDRESS"); } function addExistingBridge(address token, address bridge_) external onlyTokenAdmin { require(bridge() != bridge_, "CANNOT_ADD_MAIN_MULTI_BRIDGE_AS_EXISTING"); IStarkgateRegistry(registry()).enlistToken(token, bridge_); emit ExistingBridgeAdded(token, bridge_); } /** Deactivates bridging of a specific token. A deactivated token is blocked for deposits and cannot be re-deployed. Note: Only serviced tokens can be deactivated. In order to block an unserviced tokens see 'blockToken'. */ function deactivateToken(address token) external onlyTokenAdmin { IStarkgateRegistry registryContract = IStarkgateRegistry(registry()); address current_bridge = registryContract.getBridge(token); require(current_bridge != address(0), "TOKEN_NOT_ENROLLED"); if (current_bridge == BLOCKED_TOKEN) { string memory revertMsg = registryContract.getWithdrawalBridges(token).length == 0 ? "TOKEN_ALREADY_BLOCKED" : "TOKEN_ALREADY_DEACTIVATED"; revert(revertMsg); } emit TokenDeactivated(token, msg.sender); registryContract.blockToken(token); if (current_bridge == bridge()) { IStarkgateBridge(bridge()).deactivate(token); } } /** Block token from being bridged. A blocked token cannot be deployed. Note: Only an unserviced token can be blocked. In order to deactivate a serviced tokens see 'deactivateToken'. */ function blockToken(address token) external onlyTokenAdmin { IStarkgateRegistry registryContract = IStarkgateRegistry(registry()); address current_bridge = registryContract.getBridge(token); if (current_bridge == address(0)) { emit TokenBlocked(token, msg.sender); registryContract.blockToken(token); } else if (current_bridge == BLOCKED_TOKEN) { string memory revertMsg = registryContract.getWithdrawalBridges(token).length == 0 ? "TOKEN_ALREADY_BLOCKED" : "CANNOT_BLOCK_DEACTIVATED_TOKEN"; revert(revertMsg); } else { revert("CANNOT_BLOCK_TOKEN_IN_SERVICE"); } } function enrollTokenBridge(address token) external payable { IStarkgateRegistry registryContract = IStarkgateRegistry(registry()); require(registryContract.getBridge(token) != BLOCKED_TOKEN, "CANNOT_DEPLOY_BRIDGE"); emit TokenEnrolled(token, msg.sender); registryContract.enlistToken(token, bridge()); IStarkgateBridge(bridge()).enrollToken{value: msg.value}(token); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.20; import "starkware/solidity/libraries/Addresses.sol"; import "src/solidity/Fees.sol"; import "src/solidity/LegacyBridge.sol"; contract StarknetEthBridge is LegacyBridge { using Addresses for address; function identify() external pure override returns (string memory) { return "StarkWare_StarknetEthBridge_2.0_4"; } function acceptDeposit( address, /*token*/ uint256 amount ) internal override returns (uint256) { // Make sure msg.value is enough to cover amount. The remaining value is fee. require(msg.value >= amount, "INSUFFICIENT_VALUE"); uint256 fee = msg.value - amount; Fees.checkFee(fee); // The msg.value was already credited to this contract. Fee will be passed to Starknet. require(address(this).balance - fee <= getMaxTotalBalance(ETH), "MAX_BALANCE_EXCEEDED"); return fee; } function transferOutFunds( address, /*token*/ uint256 amount, address recipient ) internal override { recipient.performEthTransfer(amount); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.20; import "starkware/solidity/interfaces/Identity.sol"; import "starkware/solidity/interfaces/ProxySupport.sol"; import "starkware/solidity/libraries/Addresses.sol"; import "starkware/solidity/libraries/NamedStorage.sol"; import "starkware/solidity/libraries/Transfers.sol"; import "starkware/solidity/tokens/ERC20/IERC20.sol"; import "starkware/solidity/tokens/ERC20/IERC20Metadata.sol"; import "starkware/starknet/solidity/IStarknetMessaging.sol"; import "src/solidity/Fees.sol"; import "src/solidity/IStarkgateBridge.sol"; import "src/solidity/IStarkgateManager.sol"; import "src/solidity/IStarkgateRegistry.sol"; import "src/solidity/IStarkgateService.sol"; import "src/solidity/StarkgateConstants.sol"; import "src/solidity/StarkgateManager.sol"; import "src/solidity/StarknetTokenStorage.sol"; import "src/solidity/WithdrawalLimit.sol"; import "src/solidity/utils/Felt252.sol"; contract StarknetTokenBridge is IStarkgateBridge, IStarkgateService, Identity, Fees, StarknetTokenStorage, ProxySupport { using Addresses for address; using Felt252 for string; using UintFelt252 for uint256; event TokenEnrollmentInitiated(address token, bytes32 deploymentMsgHash); event TokenDeactivated(address token); event DepositWithMessage( address indexed sender, address indexed token, uint256 amount, uint256 indexed l2Recipient, uint256[] message, uint256 nonce, uint256 fee ); event DepositWithMessageCancelRequest( address indexed sender, address indexed token, uint256 amount, uint256 indexed l2Recipient, uint256[] message, uint256 nonce ); event DepositWithMessageReclaimed( address indexed sender, address indexed token, uint256 amount, uint256 indexed l2Recipient, uint256[] message, uint256 nonce ); event Withdrawal(address indexed recipient, address indexed token, uint256 amount); event SetL2TokenBridge(uint256 value); event SetMaxTotalBalance(address indexed token, uint256 value); event Deposit( address indexed sender, address indexed token, uint256 amount, uint256 indexed l2Recipient, uint256 nonce, uint256 fee ); event DepositCancelRequest( address indexed sender, address indexed token, uint256 amount, uint256 indexed l2Recipient, uint256 nonce ); event DepositReclaimed( address indexed sender, address indexed token, uint256 amount, uint256 indexed l2Recipient, uint256 nonce ); event WithdrawalLimitEnabled(address indexed sender, address indexed token); event WithdrawalLimitDisabled(address indexed sender, address indexed token); uint256 constant N_DEPOSIT_PAYLOAD_ARGS = 5; uint256 constant DEPOSIT_MESSAGE_FIXED_SIZE = 1; function identify() external pure virtual returns (string memory) { return "StarkWare_StarknetTokenBridge_2.0_4"; } function validateInitData(bytes calldata data) internal view virtual override { require(data.length == 64, "ILLEGAL_DATA_SIZE"); (address manager_, address messagingContract_) = abi.decode(data, (address, address)); require(messagingContract_.isContract(), "INVALID_MESSAGING_CONTRACT_ADDRESS"); require(manager_.isContract(), "INVALID_MANAGER_CONTRACT_ADDRESS"); } /* Gets the addresses of bridgedToken & messagingContract from the ProxySupport initialize(), and sets the storage slot accordingly. */ function initializeContractState(bytes calldata data) internal override { (address manager_, address messagingContract_) = abi.decode(data, (address, address)); messagingContract(messagingContract_); setManager(manager_); WithdrawalLimit.setWithdrawLimitPct(WithdrawalLimit.DEFAULT_WITHDRAW_LIMIT_PCT); } function isInitialized() internal view virtual override returns (bool) { return address(messagingContract()) != address(0); } /* No processing needed, as there are no sub-contracts to this contract. */ function processSubContractAddresses(bytes calldata subContractAddresses) internal override {} function numOfSubContracts() internal pure override returns (uint256) { return 0; } modifier onlyManager() { require(manager() == msg.sender, "ONLY_MANAGER"); _; } modifier skipUnlessPending(address token) { if (tokenSettings()[token].tokenStatus != TokenStatus.Pending) return; _; } modifier onlyServicingToken(address token) { require(isServicingToken(token), "TOKEN_NOT_SERVICED"); _; } function estimateDepositFeeWei() external pure returns (uint256) { return Fees.estimateDepositFee(); } function estimateEnrollmentFeeWei() external pure returns (uint256) { return Fees.estimateEnrollmentFee(); } // Virtual functions. function acceptDeposit(address token, uint256 amount) internal virtual returns (uint256) { Fees.checkFee(msg.value); uint256 currentBalance = IERC20(token).balanceOf(address(this)); require(currentBalance + amount <= getMaxTotalBalance(token), "MAX_BALANCE_EXCEEDED"); Transfers.transferIn(token, msg.sender, amount); return msg.value; } function transferOutFunds( address token, uint256 amount, address recipient ) internal virtual { Transfers.transferOut(token, recipient, amount); } /** Initiates the enrollment of a token into the system. This function is used to initiate the enrollment process of a token. The token is marked as 'Pending' because the success of the deployment is uncertain at this stage. The deployment message's existence is checked, indicating that deployment has been attempted. The success of the deployment is determined at a later stage during the application's lifecycle. Only the manager, who initiates the deployment, can call this function. @param token The address of the token contract to be enrolled. No return value, but it updates the token's status to 'Pending' and records the deployment message and expiration time. Emits a `TokenEnrollmentInitiated` event when the enrollment is initiated. Throws an error if the sender is not the manager or if the deployment message does not exist. */ function enrollToken(address token) external payable virtual onlyManager { require( tokenSettings()[token].tokenStatus == TokenStatus.Unknown, "TOKEN_ALREADY_ENROLLED" ); // send message. bytes32 deploymentMsgHash = sendDeployMessage(token); require( messagingContract().l1ToL2Messages(deploymentMsgHash) > 0, "DEPLOYMENT_MESSAGE_NOT_EXIST" ); tokenSettings()[token].tokenStatus = TokenStatus.Pending; tokenSettings()[token].deploymentMsgHash = deploymentMsgHash; tokenSettings()[token].pendingDeploymentExpiration = block.timestamp + MAX_PENDING_DURATION; emit TokenEnrollmentInitiated(token, deploymentMsgHash); } function getStatus(address token) external view returns (TokenStatus) { return tokenSettings()[token].tokenStatus; } function isServicingToken(address token) public view returns (bool) { TokenStatus status = tokenSettings()[token].tokenStatus; return (status == TokenStatus.Pending || status == TokenStatus.Active); } /** Returns the remaining amount of withdrawal allowed for this day. If the daily allowance was not yet set, it is calculated and returned. If the withdraw limit is not enabled for that token - the uint256.max is returned. */ function getRemainingIntradayAllowance(address token) external view returns (uint256) { return tokenSettings()[token].withdrawalLimitApplied ? WithdrawalLimit.getRemainingIntradayAllowance(token) : type(uint256).max; } /** Deactivates a token in the system. This function is used to deactivate a token that was previously enrolled. Only the manager, who initiated the enrollment, can call this function. @param token The address of the token contract to be deactivated. No return value, but it updates the token's status to 'Deactivated'. Emits a `TokenDeactivated` event when the deactivation is successful. Throws an error if the token is not enrolled or if the sender is not the manager. */ function deactivate(address token) external virtual onlyManager { require(tokenSettings()[token].tokenStatus != TokenStatus.Unknown, "UNKNOWN_TOKEN"); tokenSettings()[token].tokenStatus = TokenStatus.Deactivated; emit TokenDeactivated(token); } /** Checks token deployment status. Relies on Starknet clearing L1-L2 message upon successful completion of deployment. Processing: Check the l1-l2 deployment message. Set status to `active` If consumed. If not consumed after the expected duration, it returns the status to unknown. */ function checkDeploymentStatus(address token) public skipUnlessPending(token) { TokenSettings storage settings = tokenSettings()[token]; bytes32 msgHash = settings.deploymentMsgHash; if (messagingContract().l1ToL2Messages(msgHash) == 0) { settings.tokenStatus = TokenStatus.Active; } else if (block.timestamp > settings.pendingDeploymentExpiration) { delete tokenSettings()[token]; address registry = IStarkgateManager(manager()).getRegistry(); IStarkgateRegistry(registry).selfRemove(token); } } function depositWithMessage( address token, uint256 amount, uint256 l2Recipient, uint256[] calldata message ) external payable onlyServicingToken(token) { uint256 fee = acceptDeposit(token, amount); uint256 nonce = sendDepositMessage( token, amount, l2Recipient, message, HANDLE_DEPOSIT_WITH_MESSAGE_SELECTOR, fee ); emitDepositEvent( token, amount, l2Recipient, message, HANDLE_DEPOSIT_WITH_MESSAGE_SELECTOR, nonce, fee ); // Piggy-back the deposit tx to check and update the status of token bridge deployment. checkDeploymentStatus(token); } function deposit( address token, uint256 amount, uint256 l2Recipient ) external payable onlyServicingToken(token) { uint256[] memory noMessage = new uint256[](0); uint256 fee = acceptDeposit(token, amount); uint256 nonce = sendDepositMessage( token, amount, l2Recipient, noMessage, HANDLE_TOKEN_DEPOSIT_SELECTOR, fee ); emitDepositEvent( token, amount, l2Recipient, noMessage, HANDLE_TOKEN_DEPOSIT_SELECTOR, nonce, fee ); // Piggy-back the deposit tx to check and update the status of token bridge deployment. checkDeploymentStatus(token); } function emitDepositEvent( address token, uint256 amount, uint256 l2Recipient, uint256[] memory message, uint256 selector, uint256 nonce, uint256 fee ) internal { if (selector == HANDLE_TOKEN_DEPOSIT_SELECTOR) { emit Deposit(msg.sender, token, amount, l2Recipient, nonce, fee); } else { require(selector == HANDLE_DEPOSIT_WITH_MESSAGE_SELECTOR, "UNKNOWN_SELECTOR"); emit DepositWithMessage(msg.sender, token, amount, l2Recipient, message, nonce, fee); } } function setL2TokenBridge(uint256 l2TokenBridge_) external onlyAppGovernor { require(isInitialized(), "CONTRACT_NOT_INITIALIZED"); require(l2TokenBridge_.isValidL2Address(), "L2_ADDRESS_OUT_OF_RANGE"); l2TokenBridge(l2TokenBridge_); emit SetL2TokenBridge(l2TokenBridge_); } /** Set withdrawal limit for a token. */ function enableWithdrawalLimit(address token) external onlySecurityAgent { tokenSettings()[token].withdrawalLimitApplied = true; emit WithdrawalLimitEnabled(msg.sender, token); } /** Unset withdrawal limit for a token. */ function disableWithdrawalLimit(address token) external onlySecurityAdmin { tokenSettings()[token].withdrawalLimitApplied = false; emit WithdrawalLimitDisabled(msg.sender, token); } /** Set the maximum allowed balance of the bridge. Note: It is possible to set a lower value than the current total balance. In this case, deposits will not be possible, until enough withdrawls are done, such that the total balance is below the limit. */ function setMaxTotalBalance(address token, uint256 maxTotalBalance_) external onlyAppGovernor { require(maxTotalBalance_ != 0, "INVALID_MAX_TOTAL_BALANCE"); emit SetMaxTotalBalance(token, maxTotalBalance_); tokenSettings()[token].maxTotalBalance = maxTotalBalance_; } // Returns the maximal allowed balance of the bridge // If the value is 0, it means that there is no limit. function getMaxTotalBalance(address token) public view returns (uint256) { uint256 maxTotalBalance = tokenSettings()[token].maxTotalBalance; return maxTotalBalance == 0 ? type(uint256).max : maxTotalBalance; } // The max depsoit limitation is deprecated. // For Backward compatibility, we return maxUint256, which means no limitation. function maxDeposit() external pure returns (uint256) { return type(uint256).max; } function deployMessagePayload(address token) private view returns (uint256[] memory) { IERC20Metadata erc20 = IERC20Metadata(token); uint256[] memory payload = new uint256[](4); payload[0] = uint256(uint160(token)); payload[1] = erc20.name().safeToFelt(); payload[2] = erc20.symbol().safeToFelt(); payload[3] = uint256(erc20.decimals()); return payload; } function depositMessagePayload( address token, uint256 amount, uint256 l2Recipient, bool withMessage, uint256[] memory message ) private view returns (uint256[] memory) { uint256 MESSAGE_OFFSET = withMessage ? N_DEPOSIT_PAYLOAD_ARGS + DEPOSIT_MESSAGE_FIXED_SIZE : N_DEPOSIT_PAYLOAD_ARGS; uint256[] memory payload = new uint256[](MESSAGE_OFFSET + message.length); payload[0] = uint256(uint160(token)); payload[1] = uint256(uint160(msg.sender)); payload[2] = l2Recipient; payload[3] = amount & (UINT256_PART_SIZE - 1); payload[4] = amount >> UINT256_PART_SIZE_BITS; if (withMessage) { payload[MESSAGE_OFFSET - 1] = message.length; for (uint256 i = 0; i < message.length; i++) { require(message[i].isFelt(), "INVALID_MESSAGE_DATA"); payload[i + MESSAGE_OFFSET] = message[i]; } } return payload; } function depositMessagePayload( address token, uint256 amount, uint256 l2Recipient ) private view returns (uint256[] memory) { uint256[] memory noMessage = new uint256[](0); return depositMessagePayload( token, amount, l2Recipient, false, /*without message*/ noMessage ); } function sendDeployMessage(address token) internal returns (bytes32) { require(l2TokenBridge() != 0, "L2_BRIDGE_NOT_SET"); Fees.checkFee(msg.value); (bytes32 deploymentMsgHash, ) = messagingContract().sendMessageToL2{value: msg.value}( l2TokenBridge(), HANDLE_TOKEN_DEPLOYMENT_SELECTOR, deployMessagePayload(token) ); return deploymentMsgHash; } function sendDepositMessage( address token, uint256 amount, uint256 l2Recipient, uint256[] memory message, uint256 selector, uint256 fee ) internal returns (uint256) { require(l2TokenBridge() != 0, "L2_BRIDGE_NOT_SET"); require(amount > 0, "ZERO_DEPOSIT"); require(l2Recipient.isValidL2Address(), "L2_ADDRESS_OUT_OF_RANGE"); bool isWithMsg = selector == HANDLE_DEPOSIT_WITH_MESSAGE_SELECTOR; (, uint256 nonce) = messagingContract().sendMessageToL2{value: fee}( l2TokenBridge(), selector, depositMessagePayload(token, amount, l2Recipient, isWithMsg, message) ); // The function exclusively supports two specific selectors, and any attempt to use an unknown // selector will result in a transaction failure. return nonce; } function consumeMessage( address token, uint256 amount, address recipient ) internal virtual { require(l2TokenBridge() != 0, "L2_BRIDGE_NOT_SET"); uint256[] memory payload = new uint256[](5); payload[0] = TRANSFER_FROM_STARKNET; payload[1] = uint256(uint160(recipient)); payload[2] = uint256(uint160(token)); payload[3] = amount & (UINT256_PART_SIZE - 1); payload[4] = amount >> UINT256_PART_SIZE_BITS; messagingContract().consumeMessageFromL2(l2TokenBridge(), payload); } function withdraw( address token, uint256 amount, address recipient ) public { // Make sure we don't accidentally burn funds. require(recipient != address(0x0), "INVALID_RECIPIENT"); // The call to consumeMessage will succeed only if a matching L2->L1 message // exists and is ready for consumption. consumeMessage(token, amount, recipient); // Check if the withdrawal limit is enabled for that token. if (tokenSettings()[token].withdrawalLimitApplied) { // If the withdrawal limit is enabled, consume the quota. WithdrawalLimit.consumeWithdrawQuota(token, amount); } transferOutFunds(token, amount, recipient); emit Withdrawal(recipient, token, amount); } function withdraw(address token, uint256 amount) external { withdraw(token, amount, msg.sender); } /* A deposit cancellation requires two steps: 1. The depositor should send a depositCancelRequest request with deposit details & nonce. 2. After a predetermined time (cancellation delay), the depositor can claim back the funds by calling depositReclaim (using the same arguments). Note: As long as the depositReclaim was not performed, the deposit may be processed, even if the cancellation delay time has already passed. Only the depositor is allowed to cancel a deposit, and only before depositReclaim was performed. */ function depositCancelRequest( address token, uint256 amount, uint256 l2Recipient, uint256 nonce ) external { messagingContract().startL1ToL2MessageCancellation( l2TokenBridge(), HANDLE_TOKEN_DEPOSIT_SELECTOR, depositMessagePayload(token, amount, l2Recipient), nonce ); emit DepositCancelRequest(msg.sender, token, amount, l2Recipient, nonce); } /* See: depositCancelRequest docstring. */ function depositWithMessageCancelRequest( address token, uint256 amount, uint256 l2Recipient, uint256[] calldata message, uint256 nonce ) external { messagingContract().startL1ToL2MessageCancellation( l2TokenBridge(), HANDLE_DEPOSIT_WITH_MESSAGE_SELECTOR, depositMessagePayload( token, amount, l2Recipient, true, /*with message*/ message ), nonce ); emit DepositWithMessageCancelRequest( msg.sender, token, amount, l2Recipient, message, nonce ); } function depositWithMessageReclaim( address token, uint256 amount, uint256 l2Recipient, uint256[] calldata message, uint256 nonce ) external { messagingContract().cancelL1ToL2Message( l2TokenBridge(), HANDLE_DEPOSIT_WITH_MESSAGE_SELECTOR, depositMessagePayload( token, amount, l2Recipient, true, /*with message*/ message ), nonce ); transferOutFunds(token, amount, msg.sender); emit DepositWithMessageReclaimed(msg.sender, token, amount, l2Recipient, message, nonce); } function depositReclaim( address token, uint256 amount, uint256 l2Recipient, uint256 nonce ) external { messagingContract().cancelL1ToL2Message( l2TokenBridge(), HANDLE_TOKEN_DEPOSIT_SELECTOR, depositMessagePayload(token, amount, l2Recipient), nonce ); transferOutFunds(token, amount, msg.sender); emit DepositReclaimed(msg.sender, token, amount, l2Recipient, nonce); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.20; import "starkware/solidity/libraries/NamedStorage.sol"; import "starkware/starknet/solidity/IStarknetMessaging.sol"; abstract contract StarknetTokenStorage { // Named storage slot tags. string internal constant BRIDGED_TOKEN_TAG = "STARKNET_ERC20_TOKEN_BRIDGE_TOKEN_ADDRESS"; string internal constant L2_BRIDGE_TAG = "STARKNET_TOKEN_BRIDGE_L2_TOKEN_CONTRACT"; string internal constant MANAGER_TAG = "STARKNET_TOKEN_BRIDGE_MANAGER_SLOT_TAG"; string internal constant MESSAGING_CONTRACT_TAG = "STARKNET_TOKEN_BRIDGE_MESSAGING_CONTRACT"; string internal constant DEPOSITOR_ADDRESSES_TAG = "STARKNET_TOKEN_BRIDGE_DEPOSITOR_ADDRESSES"; enum TokenStatus { Unknown, Pending, Active, Deactivated } struct TokenSettings { TokenStatus tokenStatus; bytes32 deploymentMsgHash; uint256 pendingDeploymentExpiration; uint256 maxTotalBalance; bool withdrawalLimitApplied; } // Slot = Web3.keccak(text="TokenSettings_Storage_Slot"). bytes32 constant tokenSettingsSlot = 0xc59c20aaa96597268f595db30ec21108a505370e3266ed3a6515637f16b8b689; function tokenSettings() internal pure returns (mapping(address => TokenSettings) storage _tokenSettings) { assembly { _tokenSettings.slot := tokenSettingsSlot } } // Storage Getters. function manager() internal view returns (address) { return NamedStorage.getAddressValue(MANAGER_TAG); } function l2TokenBridge() internal view returns (uint256) { return NamedStorage.getUintValue(L2_BRIDGE_TAG); } function messagingContract() internal view returns (IStarknetMessaging) { return IStarknetMessaging(NamedStorage.getAddressValue(MESSAGING_CONTRACT_TAG)); } // Storage Setters. function setManager(address contract_) internal { NamedStorage.setAddressValueOnce(MANAGER_TAG, contract_); } function l2TokenBridge(uint256 value) internal { NamedStorage.setUintValueOnce(L2_BRIDGE_TAG, value); } function messagingContract(address contract_) internal { NamedStorage.setAddressValueOnce(MESSAGING_CONTRACT_TAG, contract_); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/libraries/Addresses.sol"; import "starkware/solidity/tokens/ERC20/IERC20.sol"; library Transfers { using Addresses for address; /* Transfers funds from sender to this contract. */ function transferIn( address token, address sender, uint256 amount ) internal { if (amount == 0) return; IERC20 erc20Token = IERC20(token); uint256 balanceBefore = erc20Token.balanceOf(address(this)); uint256 expectedAfter = balanceBefore + amount; require(expectedAfter >= balanceBefore, "OVERFLOW"); bytes memory callData = abi.encodeWithSelector( erc20Token.transferFrom.selector, sender, address(this), amount ); token.safeTokenContractCall(callData); uint256 balanceAfter = erc20Token.balanceOf(address(this)); require(balanceAfter == expectedAfter, "INCORRECT_AMOUNT_TRANSFERRED"); } /* Transfers funds from this contract to recipient. */ function transferOut( address token, address recipient, uint256 amount ) internal { // Make sure we don't accidentally burn funds. require(recipient != address(0x0), "INVALID_RECIPIENT"); if (amount == 0) return; IERC20 erc20Token = IERC20(token); uint256 balanceBefore = erc20Token.balanceOf(address(this)); uint256 expectedAfter = balanceBefore - amount; require(expectedAfter <= balanceBefore, "UNDERFLOW"); bytes memory callData = abi.encodeWithSelector( erc20Token.transfer.selector, recipient, amount ); token.safeTokenContractCall(callData); uint256 balanceAfter = erc20Token.balanceOf(address(this)); require(balanceAfter == expectedAfter, "INCORRECT_AMOUNT_TRANSFERRED"); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/libraries/NamedStorage.sol"; import "starkware/solidity/tokens/ERC20/IERC20.sol"; import "src/solidity/StarkgateConstants.sol"; /** A library to provide withdrawal limit functionality. */ library WithdrawalLimit { uint256 constant DEFAULT_WITHDRAW_LIMIT_PCT = 5; string internal constant WITHDRAW_LIMIT_PCT_TAG = "WITHDRAWL_LIMIT_WITHDRAW_LIMIT_PCT_SLOT_TAG"; string internal constant INTRADAY_QUOTA_TAG = "WITHDRAWL_LIMIT_INTRADAY_QUOTA_SLOT_TAG"; function getWithdrawLimitPct() internal view returns (uint256) { return NamedStorage.getUintValue(WITHDRAW_LIMIT_PCT_TAG); } function setWithdrawLimitPct(uint256 value) internal { NamedStorage.setUintValue(WITHDRAW_LIMIT_PCT_TAG, value); } // Returns the key for the intraday allowance mapping. function withdrawQuotaKey(address token) internal view returns (bytes32) { uint256 day = block.timestamp / 86400; return keccak256(abi.encode(token, day)); } /** Calculates the intraday allowance for a given token. The allowance is calculated as a percentage of the current balance. */ function calculateIntradayAllowance(address token) internal view returns (uint256) { uint256 currentBalance; // If the token is Eth and not an ERC20 - calculate balance accordingly. if (token == ETH) { currentBalance = address(this).balance; } else { currentBalance = IERC20(token).balanceOf(address(this)); } uint256 withdrawLimitPct = getWithdrawLimitPct(); return (currentBalance * withdrawLimitPct) / 100; } /** Returns the intraday quota mapping. */ function intradayQuota() internal pure returns (mapping(bytes32 => uint256) storage) { return NamedStorage.bytes32ToUint256Mapping(INTRADAY_QUOTA_TAG); } // The offset is used to distinguish between an unset value and a value of 0. uint256 constant OFFSET = 1; function isWithdrawQuotaInitialized(address token) private view returns (bool) { return intradayQuota()[withdrawQuotaKey(token)] != 0; } function getIntradayQuota(address token) internal view returns (uint256) { return intradayQuota()[withdrawQuotaKey(token)] - OFFSET; } function setIntradayQuota(address token, uint256 value) private { intradayQuota()[withdrawQuotaKey(token)] = value + OFFSET; } /** Returns the remaining amount of withdrawal allowed for this day. If the daily allowance was not yet set, it is calculated and returned. */ function getRemainingIntradayAllowance(address token) internal view returns (uint256) { if (!isWithdrawQuotaInitialized(token)) { return calculateIntradayAllowance(token); } return getIntradayQuota(token); } /** Consumes the intraday allowance for a given token. If the allowance was not yet calculated, it is calculated and consumed. */ function consumeWithdrawQuota(address token, uint256 amount) internal { uint256 intradayAllowance = getRemainingIntradayAllowance(token); require(intradayAllowance >= amount, "EXCEEDS_GLOBAL_WITHDRAW_LIMIT"); setIntradayQuota(token, intradayAllowance - amount); } }
File 4 of 4: Starknet
/* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; /* Common Utility Libraries. I. Addresses (extending address). */ library Addresses { /* Note: isContract function has some known limitation. See https://github.com/OpenZeppelin/ openzeppelin-contracts/blob/master/contracts/utils/Address.sol. */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function performEthTransfer(address recipient, uint256 amount) internal { if (amount == 0) return; (bool success, ) = recipient.call{value: amount}(""); // NOLINT: low-level-calls. require(success, "ETH_TRANSFER_FAILED"); } /* Safe wrapper around ERC20/ERC721 calls. This is required because many deployed ERC20 contracts don't return a value. See https://github.com/ethereum/solidity/issues/4116. */ function safeTokenContractCall(address tokenAddress, bytes memory callData) internal { require(isContract(tokenAddress), "BAD_TOKEN_ADDRESS"); // NOLINTNEXTLINE: low-level-calls. (bool success, bytes memory returndata) = tokenAddress.call(callData); require(success, string(returndata)); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED"); } } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; /* This contract provides means to block direct call of an external function. A derived contract (e.g. MainDispatcherBase) should decorate sensitive functions with the notCalledDirectly modifier, thereby preventing it from being called directly, and allowing only calling using delegate_call. */ abstract contract BlockDirectCall { address immutable this_; constructor() internal { this_ = address(this); } modifier notCalledDirectly() { require(this_ != address(this), "DIRECT_CALL_DISALLOWED"); _; } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; /** Interface for contract initialization. The functions it exposes are the app specific parts of the contract initialization, and are called by the ProxySupport contract that implement the generic part of behind-proxy initialization. */ abstract contract ContractInitializer { /* The number of sub-contracts that the proxied contract consists of. */ function numOfSubContracts() internal pure virtual returns (uint256); /* Indicates if the proxied contract has already been initialized. Used to prevent re-init. */ function isInitialized() internal view virtual returns (bool); /* Validates the init data that is passed into the proxied contract. */ function validateInitData(bytes calldata data) internal view virtual; /* For a proxied contract that consists of sub-contracts, this function processes the sub-contract addresses, e.g. validates them, stores them etc. */ function processSubContractAddresses(bytes calldata subContractAddresses) internal virtual; /* This function applies the logic of initializing the proxied contract state, e.g. setting root values etc. */ function initializeContractState(bytes calldata data) internal virtual; } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; import "../interfaces/MGovernance.sol"; /* Implements Generic Governance, applicable for both proxy and main contract, and possibly others. Notes: The use of the same function names by both the Proxy and a delegated implementation is not possible since calling the implementation functions is done via the default function of the Proxy. For this reason, for example, the implementation of MainContract (MainGovernance) exposes mainIsGovernor, which calls the internal _isGovernor method. */ struct GovernanceInfoStruct { mapping(address => bool) effectiveGovernors; address candidateGovernor; bool initialized; } abstract contract Governance is MGovernance { event LogNominatedGovernor(address nominatedGovernor); event LogNewGovernorAccepted(address acceptedGovernor); event LogRemovedGovernor(address removedGovernor); event LogNominationCancelled(); function getGovernanceInfo() internal view virtual returns (GovernanceInfoStruct storage); /* Current code intentionally prevents governance re-initialization. This may be a problem in an upgrade situation, in a case that the upgrade-to implementation performs an initialization (for real) and within that calls initGovernance(). Possible workarounds: 1. Clearing the governance info altogether by changing the MAIN_GOVERNANCE_INFO_TAG. This will remove existing main governance information. 2. Modify the require part in this function, so that it will exit quietly when trying to re-initialize (uncomment the lines below). */ function initGovernance() internal { GovernanceInfoStruct storage gub = getGovernanceInfo(); require(!gub.initialized, "ALREADY_INITIALIZED"); gub.initialized = true; // to ensure acceptNewGovernor() won't fail. // Add the initial governer. acceptNewGovernor(msg.sender); } function _isGovernor(address user) internal view override returns (bool) { GovernanceInfoStruct storage gub = getGovernanceInfo(); return gub.effectiveGovernors[user]; } /* Cancels the nomination of a governor candidate. */ function _cancelNomination() internal onlyGovernance { GovernanceInfoStruct storage gub = getGovernanceInfo(); if (gub.candidateGovernor != address(0x0)) { gub.candidateGovernor = address(0x0); emit LogNominationCancelled(); } } function _nominateNewGovernor(address newGovernor) internal onlyGovernance { GovernanceInfoStruct storage gub = getGovernanceInfo(); require(newGovernor != address(0x0), "BAD_ADDRESS"); require(!_isGovernor(newGovernor), "ALREADY_GOVERNOR"); require(gub.candidateGovernor == address(0x0), "OTHER_CANDIDATE_PENDING"); gub.candidateGovernor = newGovernor; emit LogNominatedGovernor(newGovernor); } /* The acceptNewGovernor is called in two cases: 1. by _acceptGovernance when a new governor accepts its role. 2. by initGovernance to add the initial governor. The difference is that the init path skips the nominate step that would fail because of the onlyGovernance modifier. */ function acceptNewGovernor(address newGovernor) private { require(!_isGovernor(newGovernor), "ALREADY_GOVERNOR"); GovernanceInfoStruct storage gub = getGovernanceInfo(); gub.effectiveGovernors[newGovernor] = true; // Emit governance information. emit LogNewGovernorAccepted(newGovernor); } function _acceptGovernance() internal { // The new governor was proposed as a candidate by the current governor. GovernanceInfoStruct storage gub = getGovernanceInfo(); require(msg.sender == gub.candidateGovernor, "ONLY_CANDIDATE_GOVERNOR"); // Update state. acceptNewGovernor(msg.sender); gub.candidateGovernor = address(0x0); } /* Remove a governor from office. */ function _removeGovernor(address governorForRemoval) internal onlyGovernance { require(msg.sender != governorForRemoval, "GOVERNOR_SELF_REMOVE"); GovernanceInfoStruct storage gub = getGovernanceInfo(); require(_isGovernor(governorForRemoval), "NOT_GOVERNOR"); gub.effectiveGovernors[governorForRemoval] = false; emit LogRemovedGovernor(governorForRemoval); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/interfaces/MGovernance.sol"; import "starkware/solidity/libraries/NamedStorage8.sol"; /** A Governor controlled finalizable contract. The inherited contract (the one that is GovernedFinalizable) implements the Governance. */ abstract contract GovernedFinalizable is MGovernance { event Finalized(); string constant STORAGE_TAG = "STARKWARE_CONTRACTS_GOVERENED_FINALIZABLE_1.0_TAG"; function isFinalized() public view returns (bool) { return NamedStorage.getBoolValue(STORAGE_TAG); } modifier notFinalized() { require(!isFinalized(), "FINALIZED"); _; } function finalize() external onlyGovernance notFinalized { NamedStorage.setBoolValue(STORAGE_TAG, true); emit Finalized(); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; /* The Fact Registry design pattern is a way to separate cryptographic verification from the business logic of the contract flow. A fact registry holds a hash table of verified "facts" which are represented by a hash of claims that the registry hash check and found valid. This table may be queried by accessing the isValid() function of the registry with a given hash. In addition, each fact registry exposes a registry specific function for submitting new claims together with their proofs. The information submitted varies from one registry to the other depending of the type of fact requiring verification. For further reading on the Fact Registry design pattern see this `StarkWare blog post <https://medium.com/starkware/the-fact-registry-a64aafb598b6>`_. */ interface IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns (bool); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; import "./IStarknetMessagingEvents.sol"; interface IStarknetMessaging is IStarknetMessagingEvents { /** Returns the max fee (in Wei) that StarkNet will accept per single message. */ function getMaxL1MsgFee() external pure returns (uint256); /** Returns `msg_fee + 1` if there is a pending message associated with the given 'msgHash', otherwise, returns 0. */ function l1ToL2Messages(bytes32 msgHash) external view returns (uint256); /** Sends a message to an L2 contract. This function is payable, the payed amount is the message fee. Returns the hash of the message and the nonce of the message. */ function sendMessageToL2( uint256 toAddress, uint256 selector, uint256[] calldata payload ) external payable returns (bytes32, uint256); /** Consumes a message that was sent from an L2 contract. Returns the hash of the message. */ function consumeMessageFromL2(uint256 fromAddress, uint256[] calldata payload) external returns (bytes32); /** Starts the cancellation of an L1 to L2 message. A message can be canceled messageCancellationDelay() seconds after this function is called. Note: This function may only be called for a message that is currently pending and the caller must be the sender of the that message. */ function startL1ToL2MessageCancellation( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external returns (bytes32); /** Cancels an L1 to L2 message, this function should be called at least messageCancellationDelay() seconds after the call to startL1ToL2MessageCancellation(). A message may only be cancelled by its sender. If the message is missing, the call will revert. Note that the message fee is not refunded. */ function cancelL1ToL2Message( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external returns (bytes32); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; interface IStarknetMessagingEvents { // This event needs to be compatible with the one defined in Output.sol. event LogMessageToL1(uint256 indexed fromAddress, address indexed toAddress, uint256[] payload); // An event that is raised when a message is sent from L1 to L2. event LogMessageToL2( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce, uint256 fee ); // An event that is raised when a message from L2 to L1 is consumed. event ConsumedMessageToL1( uint256 indexed fromAddress, address indexed toAddress, uint256[] payload ); // An event that is raised when a message from L1 to L2 is consumed. event ConsumedMessageToL2( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); // An event that is raised when a message from L1 to L2 Cancellation is started. event MessageToL2CancellationStarted( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); // An event that is raised when a message from L1 to L2 is canceled. event MessageToL2Canceled( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; interface Identity { /* Allows a caller to ensure that the provided address is of the expected type and version. */ function identify() external pure returns (string memory); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; abstract contract MGovernance { function _isGovernor(address user) internal view virtual returns (bool); /* Allows calling the function only by a Governor. */ modifier onlyGovernance() { require(_isGovernor(msg.sender), "ONLY_GOVERNANCE"); _; } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; import "./MGovernance.sol"; abstract contract MOperator { event LogOperatorAdded(address operator); event LogOperatorRemoved(address operator); function isOperator(address user) public view virtual returns (bool); modifier onlyOperator() { require(isOperator(msg.sender), "ONLY_OPERATOR"); _; } function registerOperator(address newOperator) external virtual; function unregisterOperator(address removedOperator) external virtual; function getOperators() internal view virtual returns (mapping(address => bool) storage); } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; /* Library to provide basic storage, in storage location out of the low linear address space. New types of storage variables should be added here upon need. */ library NamedStorage { function bytes32ToUint256Mapping(string memory tag_) internal pure returns (mapping(bytes32 => uint256) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function bytes32ToAddressMapping(string memory tag_) internal pure returns (mapping(bytes32 => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function uintToAddressMapping(string memory tag_) internal pure returns (mapping(uint256 => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function addressToAddressMapping(string memory tag_) internal pure returns (mapping(address => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function addressToBoolMapping(string memory tag_) internal pure returns (mapping(address => bool) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable.slot := location } } function getUintValue(string memory tag_) internal view returns (uint256 retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setUintValue(string memory tag_, uint256 value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } function setUintValueOnce(string memory tag_, uint256 value) internal { require(getUintValue(tag_) == 0, "ALREADY_SET"); setUintValue(tag_, value); } function getAddressValue(string memory tag_) internal view returns (address retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setAddressValue(string memory tag_, address value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } function setAddressValueOnce(string memory tag_, address value) internal { require(getAddressValue(tag_) == address(0x0), "ALREADY_SET"); setAddressValue(tag_, value); } function getBoolValue(string memory tag_) internal view returns (bool retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setBoolValue(string memory tag_, bool value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; library OnchainDataFactTreeEncoder { struct DataAvailabilityFact { uint256 onchainDataHash; uint256 onchainDataSize; } // The number of additional words appended to the public input when using the // OnchainDataFactTreeEncoder format. uint256 internal constant ONCHAIN_DATA_FACT_ADDITIONAL_WORDS = 2; /* Encodes a GPS fact Merkle tree where the root has two children. The left child contains the data we care about and the right child contains on-chain data for the fact. */ function encodeFactWithOnchainData( uint256[] calldata programOutput, DataAvailabilityFact memory factData ) internal pure returns (bytes32) { // The state transition fact is computed as a Merkle tree, as defined in // GpsOutputParser. // // In our case the fact tree looks as follows: // The root has two children. // The left child is a leaf that includes the main part - the information regarding // the state transition required by this contract. // The right child contains the onchain-data which shouldn't be accessed by this // contract, so we are only given its hash and length // (it may be a leaf or an inner node, this has no effect on this contract). // Compute the hash without the two additional fields. uint256 mainPublicInputLen = programOutput.length; bytes32 mainPublicInputHash = hashMainPublicInput(programOutput); // Compute the hash of the fact Merkle tree. bytes32 hashResult = keccak256( abi.encodePacked( mainPublicInputHash, mainPublicInputLen, factData.onchainDataHash, mainPublicInputLen + factData.onchainDataSize ) ); // Add one to the hash to indicate it represents an inner node, rather than a leaf. return bytes32(uint256(hashResult) + 1); } /* Hashes the main public input. */ function hashMainPublicInput(uint256[] calldata programOutput) internal pure returns (bytes32) { return keccak256(abi.encodePacked(programOutput)); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; import "../interfaces/MOperator.sol"; import "../interfaces/MGovernance.sol"; /** The Operator of the contract is the entity entitled to submit state update requests by calling :sol:func:`updateState`. An Operator may be instantly appointed or removed by the contract Governor (see :sol:mod:`Governance`). Typically, the Operator is the hot wallet of the service submitting proofs for state updates. */ abstract contract Operator is MGovernance, MOperator { function registerOperator(address newOperator) external override onlyGovernance { if (!isOperator(newOperator)) { getOperators()[newOperator] = true; emit LogOperatorAdded(newOperator); } } function unregisterOperator(address removedOperator) external override onlyGovernance { if (isOperator(removedOperator)) { getOperators()[removedOperator] = false; emit LogOperatorRemoved(removedOperator); } } function isOperator(address user) public view override returns (bool) { return getOperators()[user]; } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "./IStarknetMessagingEvents.sol"; library CommitmentTreeUpdateOutput { /** Returns the previous commitment tree root. */ function getPrevRoot(uint256[] calldata commitmentTreeUpdateData) internal pure returns (uint256) { return commitmentTreeUpdateData[0]; } /** Returns the new commitment tree root. */ function getNewRoot(uint256[] calldata commitmentTreeUpdateData) internal pure returns (uint256) { return commitmentTreeUpdateData[1]; } } library StarknetOutput { uint256 internal constant MERKLE_UPDATE_OFFSET = 0; uint256 internal constant BLOCK_NUMBER_OFFSET = 2; uint256 internal constant BLOCK_HASH_OFFSET = 3; uint256 internal constant CONFIG_HASH_OFFSET = 4; uint256 internal constant USE_KZG_DA_OFFSET = 5; uint256 internal constant HEADER_SIZE = 6; uint256 internal constant KZG_SEGMENT_SIZE = 5; uint256 constant MESSAGE_TO_L1_FROM_ADDRESS_OFFSET = 0; uint256 constant MESSAGE_TO_L1_TO_ADDRESS_OFFSET = 1; uint256 constant MESSAGE_TO_L1_PAYLOAD_SIZE_OFFSET = 2; uint256 constant MESSAGE_TO_L1_PREFIX_SIZE = 3; uint256 constant MESSAGE_TO_L2_FROM_ADDRESS_OFFSET = 0; uint256 constant MESSAGE_TO_L2_TO_ADDRESS_OFFSET = 1; uint256 constant MESSAGE_TO_L2_NONCE_OFFSET = 2; uint256 constant MESSAGE_TO_L2_SELECTOR_OFFSET = 3; uint256 constant MESSAGE_TO_L2_PAYLOAD_SIZE_OFFSET = 4; uint256 constant MESSAGE_TO_L2_PREFIX_SIZE = 5; /** Returns the offset of the messages segment in the output_data. */ function messageSegmentOffset(uint256 use_kzg_da) internal pure returns (uint256) { return HEADER_SIZE + (use_kzg_da == 1 ? KZG_SEGMENT_SIZE : 0); } /** Returns a slice of the 'output_data' with the commitment tree update information. */ function getMerkleUpdate(uint256[] calldata output_data) internal pure returns (uint256[] calldata) { return output_data[MERKLE_UPDATE_OFFSET:MERKLE_UPDATE_OFFSET + 2]; } /** Processes a message segment from the program output. The format of a message segment is the length of the messages in words followed by the concatenation of all the messages. The 'messages' mapping is updated according to the messages and the direction ('isL2ToL1'). */ function processMessages( bool isL2ToL1, uint256[] calldata programOutputSlice, mapping(bytes32 => uint256) storage messages ) internal returns (uint256) { uint256 messageSegmentSize = programOutputSlice[0]; require(messageSegmentSize < 2**30, "INVALID_MESSAGE_SEGMENT_SIZE"); uint256 offset = 1; uint256 messageSegmentEnd = offset + messageSegmentSize; uint256 payloadSizeOffset = ( isL2ToL1 ? MESSAGE_TO_L1_PAYLOAD_SIZE_OFFSET : MESSAGE_TO_L2_PAYLOAD_SIZE_OFFSET ); uint256 totalMsgFees = 0; while (offset < messageSegmentEnd) { uint256 payloadLengthOffset = offset + payloadSizeOffset; require(payloadLengthOffset < programOutputSlice.length, "MESSAGE_TOO_SHORT"); uint256 payloadLength = programOutputSlice[payloadLengthOffset]; require(payloadLength < 2**30, "INVALID_PAYLOAD_LENGTH"); uint256 endOffset = payloadLengthOffset + 1 + payloadLength; require(endOffset <= programOutputSlice.length, "TRUNCATED_MESSAGE_PAYLOAD"); if (isL2ToL1) { bytes32 messageHash = keccak256( abi.encodePacked(programOutputSlice[offset:endOffset]) ); emit IStarknetMessagingEvents.LogMessageToL1( // from= programOutputSlice[offset + MESSAGE_TO_L1_FROM_ADDRESS_OFFSET], // to= address(uint160(programOutputSlice[offset + MESSAGE_TO_L1_TO_ADDRESS_OFFSET])), // payload= (uint256[])(programOutputSlice[offset + MESSAGE_TO_L1_PREFIX_SIZE:endOffset]) ); messages[messageHash] += 1; } else { { bytes32 messageHash = keccak256( abi.encodePacked(programOutputSlice[offset:endOffset]) ); uint256 msgFeePlusOne = messages[messageHash]; require(msgFeePlusOne > 0, "INVALID_MESSAGE_TO_CONSUME"); totalMsgFees += msgFeePlusOne - 1; messages[messageHash] = 0; } uint256 nonce = programOutputSlice[offset + MESSAGE_TO_L2_NONCE_OFFSET]; uint256[] memory messageSlice = (uint256[])( programOutputSlice[offset + MESSAGE_TO_L2_PREFIX_SIZE:endOffset] ); emit IStarknetMessagingEvents.ConsumedMessageToL2( // from= address( uint160(programOutputSlice[offset + MESSAGE_TO_L2_FROM_ADDRESS_OFFSET]) ), // to= programOutputSlice[offset + MESSAGE_TO_L2_TO_ADDRESS_OFFSET], // selector= programOutputSlice[offset + MESSAGE_TO_L2_SELECTOR_OFFSET], // payload= messageSlice, // nonce = nonce ); } offset = endOffset; } require(offset == messageSegmentEnd, "INVALID_MESSAGE_SEGMENT_SIZE"); if (totalMsgFees > 0) { // NOLINTNEXTLINE: low-level-calls. (bool success, ) = msg.sender.call{value: totalMsgFees}(""); require(success, "ETH_TRANSFER_FAILED"); } return offset; } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; import "../components/Governance.sol"; import "../libraries/Addresses.sol"; import "./BlockDirectCall.sol"; import "./ContractInitializer.sol"; /** This contract contains the code commonly needed for a contract to be deployed behind an upgradability proxy. It perform the required semantics of the proxy pattern, but in a generic manner. Instantiation of the Governance and of the ContractInitializer, that are the app specific part of initialization, has to be done by the using contract. */ abstract contract ProxySupport is Governance, BlockDirectCall, ContractInitializer { using Addresses for address; // The two function below (isFrozen & initialize) needed to bind to the Proxy. function isFrozen() external view virtual returns (bool) { return false; } /* The initialize() function serves as an alternative constructor for a proxied deployment. Flow and notes: 1. This function cannot be called directly on the deployed contract, but only via delegate call. 2. If an EIC is provided - init is passed onto EIC and the standard init flow is skipped. This true for both first intialization or a later one. 3. The data passed to this function is as follows: [sub_contracts addresses, eic address, initData]. When calling on an initialized contract (no EIC scenario), initData.length must be 0. */ function initialize(bytes calldata data) external notCalledDirectly { uint256 eicOffset = 32 * numOfSubContracts(); uint256 expectedBaseSize = eicOffset + 32; require(data.length >= expectedBaseSize, "INIT_DATA_TOO_SMALL"); address eicAddress = abi.decode(data[eicOffset:expectedBaseSize], (address)); bytes calldata subContractAddresses = data[:eicOffset]; processSubContractAddresses(subContractAddresses); bytes calldata initData = data[expectedBaseSize:]; // EIC Provided - Pass initData to EIC and the skip standard init flow. if (eicAddress != address(0x0)) { callExternalInitializer(eicAddress, initData); return; } if (isInitialized()) { require(initData.length == 0, "UNEXPECTED_INIT_DATA"); } else { // Contract was not initialized yet. validateInitData(initData); initializeContractState(initData); initGovernance(); } } function callExternalInitializer(address externalInitializerAddr, bytes calldata eicData) private { require(externalInitializerAddr.isContract(), "EIC_NOT_A_CONTRACT"); // NOLINTNEXTLINE: low-level-calls, controlled-delegatecall. (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall( abi.encodeWithSelector(this.initialize.selector, eicData) ); require(success, string(returndata)); require(returndata.length == 0, string(returndata)); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.24; import "./Output.sol"; import "./StarknetGovernance.sol"; import "./StarknetMessaging.sol"; import "./StarknetOperator.sol"; import "./StarknetState.sol"; import "starkware/solidity/components/GovernedFinalizable.sol"; import "starkware/solidity/components/OnchainDataFactTreeEncoder.sol"; import "starkware/solidity/interfaces/ContractInitializer.sol"; import "starkware/solidity/interfaces/Identity.sol"; import "starkware/solidity/interfaces/IFactRegistry.sol"; import "starkware/solidity/interfaces/ProxySupport.sol"; import "starkware/solidity/libraries/NamedStorage8.sol"; contract Starknet is Identity, StarknetMessaging, StarknetGovernance, GovernedFinalizable, StarknetOperator, ContractInitializer, ProxySupport { using StarknetState for StarknetState.State; // Indicates a change of the Starknet config hash. event ConfigHashChanged( address indexed changedBy, uint256 oldConfigHash, uint256 newConfigHash ); // Logs the new state following a state update. event LogStateUpdate(uint256 globalRoot, int256 blockNumber, uint256 blockHash); // Logs a stateTransitionFact that was used to update the state. event LogStateTransitionFact(bytes32 stateTransitionFact); // Indicates a change of the Starknet OS program hash. event ProgramHashChanged( address indexed changedBy, uint256 oldProgramHash, uint256 newProgramHash ); // Random storage slot tags. string internal constant PROGRAM_HASH_TAG = "STARKNET_1.0_INIT_PROGRAM_HASH_UINT"; string internal constant VERIFIER_ADDRESS_TAG = "STARKNET_1.0_INIT_VERIFIER_ADDRESS"; string internal constant STATE_STRUCT_TAG = "STARKNET_1.0_INIT_STARKNET_STATE_STRUCT"; // The hash of the StarkNet config. string internal constant CONFIG_HASH_TAG = "STARKNET_1.0_STARKNET_CONFIG_HASH"; // EIP-4844 constants. address internal constant POINT_EVALUATION_PRECOMPILE_ADDRESS = address(0x0A); // The precompile expected output: // Web3.keccak(FIELD_ELEMENTS_PER_BLOB.to_bytes(32, "big") + BLS_PRIME.to_bytes(32, "big")). bytes32 internal constant POINT_EVALUATION_PRECOMPILE_OUTPUT = 0xb2157d3a40131b14c4c675335465dffde802f0ce5218ad012284d7f275d1b37c; uint256 internal constant PROOF_BYTES_LENGTH = 48; bytes1 internal constant VERSIONED_HASH_VERSION_KZG = bytes1(0x01); function setProgramHash(uint256 newProgramHash) external notFinalized onlyGovernance { emit ProgramHashChanged(msg.sender, programHash(), newProgramHash); programHash(newProgramHash); } function setConfigHash(uint256 newConfigHash) external notFinalized onlyGovernance { emit ConfigHashChanged(msg.sender, configHash(), newConfigHash); configHash(newConfigHash); } function setMessageCancellationDelay(uint256 delayInSeconds) external notFinalized onlyGovernance { messageCancellationDelay(delayInSeconds); } // State variable "programHash" read-access function. function programHash() public view returns (uint256) { return NamedStorage.getUintValue(PROGRAM_HASH_TAG); } // State variable "programHash" write-access function. function programHash(uint256 value) internal { NamedStorage.setUintValue(PROGRAM_HASH_TAG, value); } // State variable "verifier" access function. function verifier() internal view returns (address) { return NamedStorage.getAddressValue(VERIFIER_ADDRESS_TAG); } // State variable "configHash" write-access function. function configHash(uint256 value) internal { NamedStorage.setUintValue(CONFIG_HASH_TAG, value); } // State variable "configHash" read-access function. function configHash() public view returns (uint256) { return NamedStorage.getUintValue(CONFIG_HASH_TAG); } function setVerifierAddress(address value) internal { NamedStorage.setAddressValueOnce(VERIFIER_ADDRESS_TAG, value); } // State variable "state" access function. function state() internal pure returns (StarknetState.State storage stateStruct) { bytes32 location = keccak256(abi.encodePacked(STATE_STRUCT_TAG)); assembly { stateStruct.slot := location } } function isInitialized() internal view override returns (bool) { return programHash() != 0; } function numOfSubContracts() internal pure override returns (uint256) { return 0; } function validateInitData(bytes calldata data) internal view override { require(data.length == 6 * 32, "ILLEGAL_INIT_DATA_SIZE"); uint256 programHash_ = abi.decode(data[:32], (uint256)); require(programHash_ != 0, "BAD_INITIALIZATION"); } function processSubContractAddresses(bytes calldata subContractAddresses) internal override {} function initializeContractState(bytes calldata data) internal override { ( uint256 programHash_, address verifier_, uint256 configHash_, StarknetState.State memory initialState ) = abi.decode(data, (uint256, address, uint256, StarknetState.State)); programHash(programHash_); setVerifierAddress(verifier_); state().copy(initialState); configHash(configHash_); messageCancellationDelay(5 days); } /** Verifies p(z) = y given z, y, a commitment to p in the kzgSegment, and a KZG proof. The verification is done by calling Ethereum's point evaluation precompile. */ function verifyKzgProof(uint256[] calldata kzgSegment, bytes calldata kzgProof) internal { require(kzgSegment.length == StarknetOutput.KZG_SEGMENT_SIZE, "INVALID_KZG_SEGMENT_SIZE"); require(kzgProof.length == PROOF_BYTES_LENGTH, "INVALID_KZG_PROOF_SIZE"); bytes32 blobHash = blobhash( // blobIndex= 0 ); require(blobHash[0] == VERSIONED_HASH_VERSION_KZG, "UNEXPECTED_BLOB_HASH_VERSION"); bytes memory kzgCommitment; bytes32 y; { uint256 kzgCommitmentLow = kzgSegment[0]; uint256 kzgCommitmentHigh = kzgSegment[1]; uint256 yLow = kzgSegment[3]; uint256 yHigh = kzgSegment[4]; require(kzgCommitmentLow <= type(uint192).max, "INVALID_KZG_COMMITMENT"); require(kzgCommitmentHigh <= type(uint192).max, "INVALID_KZG_COMMITMENT"); require(yLow <= type(uint128).max, "INVALID_Y_VALUE"); require(yHigh <= type(uint128).max, "INVALID_Y_VALUE"); kzgCommitment = abi.encodePacked(uint192(kzgCommitmentHigh), uint192(kzgCommitmentLow)); y = bytes32((yHigh << 128) + yLow); } bytes32 z = bytes32(kzgSegment[2]); (bool ok, bytes memory precompile_output) = POINT_EVALUATION_PRECOMPILE_ADDRESS.staticcall( abi.encodePacked(blobHash, z, y, kzgCommitment, kzgProof) ); require(ok, "POINT_EVALUATION_PRECOMPILE_CALL_FAILED"); require( keccak256(precompile_output) == POINT_EVALUATION_PRECOMPILE_OUTPUT, "UNEXPECTED_POINT_EVALUATION_PRECOMPILE_OUTPUT" ); } /** Performs the actual state update of Starknet, based on a proof of the Starknet OS that the state transition is valid. Arguments: programOutput - The main part of the StarkNet OS program output. stateTransitionFact - An encoding of the 'programOutput' (including on-chain data, if available). */ function updateStateInternal(uint256[] calldata programOutput, bytes32 stateTransitionFact) internal { // Validate config hash. require( programOutput[StarknetOutput.CONFIG_HASH_OFFSET] == configHash(), "INVALID_CONFIG_HASH" ); bytes32 sharpFact = keccak256(abi.encode(programHash(), stateTransitionFact)); require(IFactRegistry(verifier()).isValid(sharpFact), "NO_STATE_TRANSITION_PROOF"); emit LogStateTransitionFact(stateTransitionFact); // Perform state update. state().update(programOutput); // Process the messages after updating the state. // This is safer, as there is a call to transfer the fees during // the processing of the L1 -> L2 messages. // Process L2 -> L1 messages. uint256 outputOffset = StarknetOutput.messageSegmentOffset( programOutput[StarknetOutput.USE_KZG_DA_OFFSET] ); outputOffset += StarknetOutput.processMessages( // isL2ToL1= true, programOutput[outputOffset:], l2ToL1Messages() ); // Process L1 -> L2 messages. outputOffset += StarknetOutput.processMessages( // isL2ToL1= false, programOutput[outputOffset:], l1ToL2Messages() ); require(outputOffset == programOutput.length, "STARKNET_OUTPUT_TOO_LONG"); // Note that processing L1 -> L2 messages does an external call, and it shouldn't be // followed by storage changes. StarknetState.State storage state_ = state(); emit LogStateUpdate(state_.globalRoot, state_.blockNumber, state_.blockHash); } /** Returns a string that identifies the contract. */ function identify() external pure override returns (string memory) { return "StarkWare_Starknet_2024_8"; } /** Returns the current state root. */ function stateRoot() external view returns (uint256) { return state().globalRoot; } /** Returns the current block number. */ function stateBlockNumber() external view returns (int256) { return state().blockNumber; } /** Returns the current block hash. */ function stateBlockHash() external view returns (uint256) { return state().blockHash; } /** Updates the state of the Starknet, based on a proof of the Starknet OS that the state transition is valid. Data availability is provided on-chain. Arguments: programOutput - The main part of the StarkNet OS program output. data_availability_fact - An encoding of the on-chain data associated with the 'programOutput'. */ function updateState( uint256[] calldata programOutput, uint256 onchainDataHash, uint256 onchainDataSize ) external onlyOperator { // We protect against re-entrancy attacks by reading the block number at the beginning // and validating that we have the expected block number at the end. int256 initialBlockNumber = state().blockNumber; // Validate program output. require(programOutput.length > StarknetOutput.HEADER_SIZE, "STARKNET_OUTPUT_TOO_SHORT"); // Validate KZG DA flag. require(programOutput[StarknetOutput.USE_KZG_DA_OFFSET] == 0, "UNEXPECTED_KZG_DA_FLAG"); bytes32 stateTransitionFact = OnchainDataFactTreeEncoder.encodeFactWithOnchainData( programOutput, OnchainDataFactTreeEncoder.DataAvailabilityFact(onchainDataHash, onchainDataSize) ); updateStateInternal(programOutput, stateTransitionFact); // Note that updateStateInternal does an external call, and it shouldn't be followed by // storage changes. // Re-entrancy protection (see above). require(state().blockNumber == initialBlockNumber + 1, "INVALID_FINAL_BLOCK_NUMBER"); } /** Updates the state of the StarkNet, based on a proof of the StarkNet OS that the state transition is valid. Data availability is committed with KZG and provided in a blob. Arguments: programOutput - The main part of the StarkNet OS program output. kzgProof - a KZG proof which is validated together with the StarkNet OS data commitment given in 'programOutput'. */ function updateStateKzgDA(uint256[] calldata programOutput, bytes calldata kzgProof) external onlyOperator { // We protect against re-entrancy attacks by reading the block number at the beginning // and validating that we have the expected block number at the end. int256 initialBlockNumber = state().blockNumber; // Validate program output. require( programOutput.length > StarknetOutput.HEADER_SIZE + StarknetOutput.KZG_SEGMENT_SIZE, "STARKNET_OUTPUT_TOO_SHORT" ); // Verify the KZG Proof. require(programOutput[StarknetOutput.USE_KZG_DA_OFFSET] == 1, "UNEXPECTED_KZG_DA_FLAG"); verifyKzgProof( programOutput[StarknetOutput.HEADER_SIZE:][:StarknetOutput.KZG_SEGMENT_SIZE], kzgProof ); bytes32 stateTransitionFact = OnchainDataFactTreeEncoder.hashMainPublicInput(programOutput); updateStateInternal(programOutput, stateTransitionFact); // Note that updateStateInternal does an external call, and it shouldn't be followed by // storage changes. // Re-entrancy protection (see above). require(state().blockNumber == initialBlockNumber + 1, "INVALID_FINAL_BLOCK_NUMBER"); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/components/Governance.sol"; contract StarknetGovernance is Governance { string constant STARKNET_GOVERNANCE_INFO_TAG = "STARKNET_1.0_GOVERNANCE_INFO"; /* Returns the GovernanceInfoStruct associated with the governance tag. */ function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage gub) { bytes32 location = keccak256(abi.encodePacked(STARKNET_GOVERNANCE_INFO_TAG)); assembly { gub.slot := location } } function starknetIsGovernor(address user) external view returns (bool) { return _isGovernor(user); } function starknetNominateNewGovernor(address newGovernor) external { _nominateNewGovernor(newGovernor); } function starknetRemoveGovernor(address governorForRemoval) external { _removeGovernor(governorForRemoval); } function starknetAcceptGovernance() external { _acceptGovernance(); } function starknetCancelNomination() external { _cancelNomination(); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "./IStarknetMessaging.sol"; import "starkware/solidity/libraries/NamedStorage8.sol"; /** Implements sending messages to L2 by adding them to a pipe and consuming messages from L2 by removing them from a different pipe. A deriving contract can handle the former pipe and add items to the latter pipe while interacting with L2. */ contract StarknetMessaging is IStarknetMessaging { /* Random slot storage elements and accessors. */ string constant L1L2_MESSAGE_MAP_TAG = "STARKNET_1.0_MSGING_L1TOL2_MAPPPING_V2"; string constant L2L1_MESSAGE_MAP_TAG = "STARKNET_1.0_MSGING_L2TOL1_MAPPPING"; string constant L1L2_MESSAGE_NONCE_TAG = "STARKNET_1.0_MSGING_L1TOL2_NONCE"; string constant L1L2_MESSAGE_CANCELLATION_MAP_TAG = ( "STARKNET_1.0_MSGING_L1TOL2_CANCELLATION_MAPPPING" ); string constant L1L2_MESSAGE_CANCELLATION_DELAY_TAG = ( "STARKNET_1.0_MSGING_L1TOL2_CANCELLATION_DELAY" ); uint256 constant MAX_L1_MSG_FEE = 1 ether; function getMaxL1MsgFee() public pure override returns (uint256) { return MAX_L1_MSG_FEE; } /** Returns the msg_fee + 1 for the message with the given 'msgHash', or 0 if no message with such a hash is pending. */ function l1ToL2Messages(bytes32 msgHash) external view override returns (uint256) { return l1ToL2Messages()[msgHash]; } function l2ToL1Messages(bytes32 msgHash) external view returns (uint256) { return l2ToL1Messages()[msgHash]; } function l1ToL2Messages() internal pure returns (mapping(bytes32 => uint256) storage) { return NamedStorage.bytes32ToUint256Mapping(L1L2_MESSAGE_MAP_TAG); } function l2ToL1Messages() internal pure returns (mapping(bytes32 => uint256) storage) { return NamedStorage.bytes32ToUint256Mapping(L2L1_MESSAGE_MAP_TAG); } function l1ToL2MessageNonce() public view returns (uint256) { return NamedStorage.getUintValue(L1L2_MESSAGE_NONCE_TAG); } function messageCancellationDelay() public view returns (uint256) { return NamedStorage.getUintValue(L1L2_MESSAGE_CANCELLATION_DELAY_TAG); } function messageCancellationDelay(uint256 delayInSeconds) internal { NamedStorage.setUintValue(L1L2_MESSAGE_CANCELLATION_DELAY_TAG, delayInSeconds); } /** Returns the timestamp at the time cancelL1ToL2Message was called with a message matching 'msgHash'. The function returns 0 if cancelL1ToL2Message was never called. */ function l1ToL2MessageCancellations(bytes32 msgHash) external view returns (uint256) { return l1ToL2MessageCancellations()[msgHash]; } function l1ToL2MessageCancellations() internal pure returns (mapping(bytes32 => uint256) storage) { return NamedStorage.bytes32ToUint256Mapping(L1L2_MESSAGE_CANCELLATION_MAP_TAG); } /** Returns the hash of an L1 -> L2 message from msg.sender. */ function getL1ToL2MsgHash( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( uint256(uint160(msg.sender)), toAddress, nonce, selector, payload.length, payload ) ); } /** Sends a message to an L2 contract. */ function sendMessageToL2( uint256 toAddress, uint256 selector, uint256[] calldata payload ) external payable override returns (bytes32, uint256) { require(msg.value > 0, "L1_MSG_FEE_MUST_BE_GREATER_THAN_0"); require(msg.value <= getMaxL1MsgFee(), "MAX_L1_MSG_FEE_EXCEEDED"); uint256 nonce = l1ToL2MessageNonce(); NamedStorage.setUintValue(L1L2_MESSAGE_NONCE_TAG, nonce + 1); emit LogMessageToL2(msg.sender, toAddress, selector, payload, nonce, msg.value); bytes32 msgHash = getL1ToL2MsgHash(toAddress, selector, payload, nonce); // Note that the inclusion of the unique nonce in the message hash implies that // l1ToL2Messages()[msgHash] was not accessed before. l1ToL2Messages()[msgHash] = msg.value + 1; return (msgHash, nonce); } /** Consumes a message that was sent from an L2 contract. Returns the hash of the message. */ function consumeMessageFromL2(uint256 fromAddress, uint256[] calldata payload) external override returns (bytes32) { bytes32 msgHash = keccak256( abi.encodePacked(fromAddress, uint256(uint160(msg.sender)), payload.length, payload) ); require(l2ToL1Messages()[msgHash] > 0, "INVALID_MESSAGE_TO_CONSUME"); emit ConsumedMessageToL1(fromAddress, msg.sender, payload); l2ToL1Messages()[msgHash] -= 1; return msgHash; } function startL1ToL2MessageCancellation( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external override returns (bytes32) { emit MessageToL2CancellationStarted(msg.sender, toAddress, selector, payload, nonce); bytes32 msgHash = getL1ToL2MsgHash(toAddress, selector, payload, nonce); uint256 msgFeePlusOne = l1ToL2Messages()[msgHash]; require(msgFeePlusOne > 0, "NO_MESSAGE_TO_CANCEL"); l1ToL2MessageCancellations()[msgHash] = block.timestamp; return msgHash; } function cancelL1ToL2Message( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external override returns (bytes32) { emit MessageToL2Canceled(msg.sender, toAddress, selector, payload, nonce); // Note that the message hash depends on msg.sender, which prevents one contract from // cancelling another contract's message. // Trying to do so will result in NO_MESSAGE_TO_CANCEL. bytes32 msgHash = getL1ToL2MsgHash(toAddress, selector, payload, nonce); uint256 msgFeePlusOne = l1ToL2Messages()[msgHash]; require(msgFeePlusOne != 0, "NO_MESSAGE_TO_CANCEL"); uint256 requestTime = l1ToL2MessageCancellations()[msgHash]; require(requestTime != 0, "MESSAGE_CANCELLATION_NOT_REQUESTED"); uint256 cancelAllowedTime = requestTime + messageCancellationDelay(); require(cancelAllowedTime >= requestTime, "CANCEL_ALLOWED_TIME_OVERFLOW"); require(block.timestamp >= cancelAllowedTime, "MESSAGE_CANCELLATION_NOT_ALLOWED_YET"); l1ToL2Messages()[msgHash] = 0; return (msgHash); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "starkware/solidity/components/Operator.sol"; import "starkware/solidity/libraries/NamedStorage8.sol"; abstract contract StarknetOperator is Operator { string constant OPERATORS_MAPPING_TAG = "STARKNET_1.0_ROLES_OPERATORS_MAPPING_TAG"; function getOperators() internal view override returns (mapping(address => bool) storage) { return NamedStorage.addressToBoolMapping(OPERATORS_MAPPING_TAG); } } /* Copyright 2019-2024 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.8.0; import "./Output.sol"; library StarknetState { struct State { uint256 globalRoot; int256 blockNumber; uint256 blockHash; } function copy(State storage state, State memory stateFrom) internal { state.globalRoot = stateFrom.globalRoot; state.blockNumber = stateFrom.blockNumber; state.blockHash = stateFrom.blockHash; } /** Validates that the 'blockNumber' and the previous root are consistent with the current state and updates the state. */ function update(State storage state, uint256[] calldata starknetOutput) internal { // Check the blockNumber first as the error is less ambiguous then INVALID_PREVIOUS_ROOT. state.blockNumber += 1; require( uint256(state.blockNumber) == starknetOutput[StarknetOutput.BLOCK_NUMBER_OFFSET], "INVALID_BLOCK_NUMBER" ); state.blockHash = starknetOutput[StarknetOutput.BLOCK_HASH_OFFSET]; uint256[] calldata commitment_tree_update = StarknetOutput.getMerkleUpdate(starknetOutput); require( state.globalRoot == CommitmentTreeUpdateOutput.getPrevRoot(commitment_tree_update), "INVALID_PREVIOUS_ROOT" ); state.globalRoot = CommitmentTreeUpdateOutput.getNewRoot(commitment_tree_update); } }