Transaction Hash:
Block:
21880264 at Feb-19-2025 11:58:35 AM +UTC
Transaction Fee:
0.00035269155729223 ETH
$0.90
Gas Used:
188,110 Gas / 1.874921893 Gwei
Emitted Events:
31 |
MiniMeToken.Transfer( _from=[Receiver] Proxy, _to=[Sender] 0x96288df1058f7eb065fd60a53aad6ed78aead527, _amount=14054156239990000000000 )
|
32 |
Proxy.0xb7477a7b93b2addc5272bbd7ad0986ef1c0d0bd265f26c3dc4bbe42727c2ac0c( 0xb7477a7b93b2addc5272bbd7ad0986ef1c0d0bd265f26c3dc4bbe42727c2ac0c, 00000000000000000000000096288df1058f7eb065fd60a53aad6ed78aead527, 0025e64a8b06180f3dcb014ae5a60455cc8c676d9ad46cef9a54a5a903381b7e, 0000000000000000000000000000000000000000000002f9e0991e28eb811c00, 00000000000000000000000000000000000000000000000000000147394c8d3f, 00000000000000000000000096288df1058f7eb065fd60a53aad6ed78aead527 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x5A98FcBE...A3beF1B32 | |||||
0x5d22045D...Fad24609b | (Rhino.fi: Bridge) | ||||
0x758A4A45...3fB1A4F42
Miner
| (Fee Recipient: 0x75...F42) | 99.15619132445335265 Eth | 99.15637943445335265 Eth | 0.00018811 | |
0x96288dF1...78aeAD527 |
0.636230497980278934 Eth
Nonce: 45
|
0.635877806422986704 Eth
Nonce: 46
| 0.00035269155729223 |
Execution Trace
Proxy.441a3e70( )
StarkExchange.441a3e70( )
TokensAndRamping.withdraw( ownerKey=857253010279275167690605901999550632812882875687, assetType=66962752733530879963215482042035904536217176403634565065350631987028171646 )
-
MiniMeToken.balanceOf( _owner=0x5d22045DAcEAB03B158031eCB7D9d06Fad24609b ) => ( balance=32329091680510000000000 )
MiniMeToken.transfer( _to=0x96288dF1058F7eB065Fd60A53aad6Ed78aeAD527, _amount=14054156239990000000000 ) => ( success=True )
AppProxyUpgradeable.4a393149( )
KernelProxy.be00bbd8( )
-
Kernel.getApp( _namespace=F1F3EB40F5BC1AD1344716CED8B8A0431D840B5783AEA1FD01786BC26F35AC0F, _appId=CD567BDF93DD0F6ACC3BC7F2155F83244D56A65ABBFBEFB763E015420102C67B ) => ( 0xde3A93028F2283cc28756B3674BD657eaFB992f4 )
-
TokenManager.onTransfer( _from=0x5d22045DAcEAB03B158031eCB7D9d06Fad24609b, _to=0x96288dF1058F7eB065Fd60A53aad6Ed78aeAD527, _amount=14054156239990000000000 ) => ( True )
-
MiniMeToken.balanceOf( _owner=0x5d22045DAcEAB03B158031eCB7D9d06Fad24609b ) => ( balance=18274935440520000000000 )
-
File 1 of 8: Proxy
File 2 of 8: MiniMeToken
File 3 of 8: StarkExchange
File 4 of 8: TokensAndRamping
File 5 of 8: AppProxyUpgradeable
File 6 of 8: KernelProxy
File 7 of 8: Kernel
File 8 of 8: TokenManager
{"Common.sol":{"content":"/*\n Copyright 2019,2020 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*/\npragma solidity ^0.5.2;\n\n/*\n Common Utility libraries.\n 1. Addresses (extending address).\n*/\nlibrary Addresses {\n function isContract(address account) internal view returns (bool) {\n uint256 size;\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n size := extcodesize(account)\n }\n return size \u003e 0;\n }\n}\n"},"Governance.sol":{"content":"/*\n Copyright 2019,2020 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*/\npragma solidity ^0.5.2;\n\nimport \"GovernanceStorage.sol\";\nimport \"MGovernance.sol\";\n\n/*\n Implements Generic Governance, applicable for both proxy and main contract, and possibly others.\n Notes:\n 1. This class is virtual (getGovernanceTag is not implemented).\n 2. 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*/\ncontract Governance is GovernanceStorage, MGovernance {\n event LogNominatedGovernor(address nominatedGovernor);\n event LogNewGovernorAccepted(address acceptedGovernor);\n event LogRemovedGovernor(address removedGovernor);\n event LogNominationCancelled();\n\n address internal constant ZERO_ADDRESS = address(0x0);\n\n /*\n Returns a string which uniquely identifies the type of the governance mechanism.\n */\n function getGovernanceTag()\n internal\n view\n returns (string memory);\n\n /*\n Returns the GovernanceInfoStruct associated with the governance tag.\n */\n function contractGovernanceInfo()\n internal\n view\n returns (GovernanceInfoStruct storage) {\n string memory tag = getGovernanceTag();\n GovernanceInfoStruct storage gub = governanceInfo[tag];\n require(gub.initialized == true, \"NOT_INITIALIZED\");\n return gub;\n }\n\n function initGovernance()\n internal\n {\n string memory tag = getGovernanceTag();\n GovernanceInfoStruct storage gub = governanceInfo[tag];\n require(gub.initialized == false, \"ALREADY_INITIALIZED\");\n gub.initialized = true; // to ensure addGovernor() won\u0027t fail.\n // Add the initial governer.\n addGovernor(msg.sender);\n }\n\n modifier onlyGovernance()\n {\n require(isGovernor(msg.sender), \"ONLY_GOVERNANCE\");\n _;\n }\n\n function isGovernor(address testGovernor)\n internal view\n returns (bool addressIsGovernor){\n GovernanceInfoStruct storage gub = contractGovernanceInfo();\n addressIsGovernor = gub.effectiveGovernors[testGovernor];\n }\n\n /*\n Cancels the nomination of a governor condidate.\n */\n function cancelNomination() internal onlyGovernance() {\n GovernanceInfoStruct storage gub = contractGovernanceInfo();\n gub.candidateGovernor = ZERO_ADDRESS;\n emit LogNominationCancelled();\n }\n\n function nominateNewGovernor(address newGovernor) internal onlyGovernance() {\n GovernanceInfoStruct storage gub = contractGovernanceInfo();\n require(isGovernor(newGovernor) == false, \"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) == false, \"ALREADY_GOVERNOR\");\n GovernanceInfoStruct storage gub = contractGovernanceInfo();\n gub.effectiveGovernors[newGovernor] = true;\n }\n\n function acceptGovernance()\n internal\n {\n // The new governor was proposed as a candidate by the current governor.\n GovernanceInfoStruct storage gub = contractGovernanceInfo();\n require(msg.sender == gub.candidateGovernor, \"ONLY_CANDIDATE_GOVERNOR\");\n\n // Update state.\n addGovernor(gub.candidateGovernor);\n gub.candidateGovernor = ZERO_ADDRESS;\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 = contractGovernanceInfo();\n require (isGovernor(governorForRemoval), \"NOT_GOVERNOR\");\n gub.effectiveGovernors[governorForRemoval] = false;\n emit LogRemovedGovernor(governorForRemoval);\n }\n}\n"},"GovernanceStorage.sol":{"content":"/*\n Copyright 2019,2020 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*/\npragma solidity ^0.5.2;\n\n/*\n Holds the governance slots for ALL entities, including proxy and the main contract.\n*/\ncontract GovernanceStorage {\n\n struct GovernanceInfoStruct {\n mapping (address =\u003e bool) effectiveGovernors;\n address candidateGovernor;\n bool initialized;\n }\n\n // A map from a Governor tag to its own GovernanceInfoStruct.\n mapping (string =\u003e GovernanceInfoStruct) internal governanceInfo;\n}\n"},"MGovernance.sol":{"content":"/*\n Copyright 2019,2020 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*/\npragma solidity ^0.5.2;\n\ncontract MGovernance {\n /*\n Allows calling the function only by a Governor.\n */\n modifier onlyGovernance()\n {\n // Pure modifier declarations are not supported. Instead we provide\n // a dummy definition.\n revert(\"UNIMPLEMENTED\");\n _;\n }\n}\n"},"Proxy.sol":{"content":"/*\n Copyright 2019,2020 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*/\npragma solidity ^0.5.2;\n\nimport \"ProxyGovernance.sol\";\nimport \"ProxyStorage.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 {\n\n // Emitted when the active implementation is replaced.\n event Upgraded(address indexed implementation);\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);\n\n // Emitted when the implementation is finalized.\n event FinalizedImplementation(address indexed implementation);\n\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 implementaiton (the proxied contract).\n bytes32 internal constant IMPLEMENTATION_SLOT =\n 0x177667240aeeea7e35eabe3a35e18306f336219e1386f7710a6bf8783f761b24;\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 uint256 public constant UPGRADE_ACTIVATION_DELAY = 28 days;\n\n using Addresses for address;\n\n constructor ( )\n public\n {\n initGovernance();\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 == ZERO_ADDRESS) {\n return false;\n }\n // solium-disable-next-line security/no-low-level-calls\n (bool success, bytes memory returndata) = _implementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\"));\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(bytes calldata /*data*/)\n external pure\n {\n revert(\"CANNOT_CALL_INITIALIZE\");\n }\n\n modifier notFinalized()\n {\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 {\n require(implementationIsFrozen() == false, \"STATE_IS_FROZEN\");\n _;\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 function () external payable {\n address _implementation = implementation();\n require (_implementation != ZERO_ADDRESS, \"MISSING_IMPLEMENTATION\");\n\n // solium-disable-next-line security/no-inline-assembly\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 { revert(0, returndatasize) }\n default { return(0, returndatasize) }\n }\n }\n\n /*\n Returns the address of the current implementation.\n */\n function implementation() public view returns (address _implementation) {\n bytes32 slot = IMPLEMENTATION_SLOT;\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n _implementation := sload(slot)\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 // solium-disable-next-line security/no-inline-assembly\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 // solium-disable-next-line security/no-inline-assembly\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 // solium-disable-next-line security/no-inline-assembly\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(address newImplementation, bytes calldata data, bool finalize)\n external onlyGovernance {\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n\n bytes32 init_hash = keccak256(abi.encode(data, finalize));\n initializationHash[newImplementation] = init_hash;\n\n // solium-disable-next-line security/no-block-members\n uint256 activation_time = now + UPGRADE_ACTIVATION_DELAY;\n\n // First implementation should not have time-lock.\n if (implementation() == ZERO_ADDRESS) {\n // solium-disable-next-line security/no-block-members\n activation_time = now;\n }\n\n enabledTime[newImplementation] = activation_time;\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(address newImplementation)\n external onlyGovernance {\n\n // If we have initializer, we set the hash of it.\n uint256 activation_time = enabledTime[newImplementation];\n\n require(activation_time \u003e 0, \"ADDRESS_NOT_UPGRADE_CANDIDATE\");\n\n enabledTime[newImplementation] = 0;\n\n initializationHash[newImplementation] = 0;\n emit ImplementationRemoved(newImplementation);\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 inititalizing vector (even if empty).\n Therefore, the implementatin MUST must have such a method.\n */\n function upgradeTo(address newImplementation, bytes calldata data, bool finalize)\n external payable onlyGovernance notFinalized notFrozen {\n uint256 activation_time = enabledTime[newImplementation];\n\n require(activation_time \u003e 0, \"ADDRESS_NOT_UPGRADE_CANDIDATE\");\n // solium-disable-next-line security/no-block-members\n require(activation_time \u003c= now, \"UPGRADE_NOT_ENABLED_YET\");\n\n bytes32 init_vector_hash = initializationHash[newImplementation];\n require(init_vector_hash == keccak256(abi.encode(data, finalize)), \"CHANGED_INITIALIZER\");\n setImplementation(newImplementation);\n\n // solium-disable-next-line security/no-low-level-calls\n (bool success, bytes memory returndata) = newImplementation.delegatecall(\n abi.encodeWithSelector(this.initialize.selector, data));\n require(success, string(returndata));\n\n // Verify that the new implementation is not frozen post initialization.\n (success, returndata) = newImplementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\"));\n require(success, \"CALL_TO_ISFROZEN_REVERTED\");\n require(abi.decode(returndata, (bool)) == false, \"NEW_IMPLEMENTATION_FROZEN\");\n\n if (finalize == true) {\n setFinalizedFlag();\n emit FinalizedImplementation(newImplementation);\n }\n\n emit Upgraded(newImplementation);\n }\n}\n"},"ProxyGovernance.sol":{"content":"/*\n Copyright 2019,2020 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*/\npragma solidity ^0.5.2;\n\nimport \"Governance.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 Governance {\n\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 function getGovernanceTag()\n internal\n view\n returns (string memory tag) {\n tag = 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()\n external\n {\n acceptGovernance();\n }\n\n function proxyCancelNomination() external {\n cancelNomination();\n }\n}\n"},"ProxyStorage.sol":{"content":"/*\n Copyright 2019,2020 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*/\npragma solidity ^0.5.2;\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\n // Stores the hash of the initialization vector of the added implementation.\n // Upon upgradeTo the implementation, the initialization vector is verified\n // to be identical to the one submitted when adding the implementaion.\n mapping (address =\u003e bytes32) internal initializationHash;\n\n // The time after which we can switch to the implementation.\n mapping (address =\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 accomodate multiple level of initialization\n // (i.e. using different key salting schemes for different initialization levels).\n mapping (bytes32 =\u003e bool) internal initialized;\n}\n"}}
File 2 of 8: MiniMeToken
pragma solidity ^0.4.24; // File: @aragon/apps-shared-minime/contracts/ITokenController.sol /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } }
File 3 of 8: StarkExchange
/* 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.6.12; /* 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.6.12; /* Common Utility librarries. I. Addresses (extending address). */ library Addresses { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function performEthTransfer(address recipient, uint256 amount) internal { (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"); } } /* Validates that the passed contract address is of a real contract, and that its id hash (as infered fromn identify()) matched the expected one. */ function validateContractId(address contractAddress, bytes32 expectedIdHash) internal { require(isContract(contractAddress), "ADDRESS_NOT_CONTRACT"); (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls. abi.encodeWithSignature("identify()") ); require(success, "FAILED_TO_IDENTIFY_CONTRACT"); string memory realContractId = abi.decode(returndata, (string)); require( keccak256(abi.encodePacked(realContractId)) == expectedIdHash, "UNEXPECTED_CONTRACT_IDENTIFIER" ); } } /* II. StarkExTypes - Common data types. */ library StarkExTypes { // Structure representing a list of verifiers (validity/availability). // A statement is valid only if all the verifiers in the list agree on it. // Adding a verifier to the list is immediate - this is used for fast resolution of // any soundness issues. // Removing from the list is time-locked, to ensure that any user of the system // not content with the announced removal has ample time to leave the system before it is // removed. struct ApprovalChainData { address[] list; // Represents the time after which the verifier with the given address can be removed. // Removal of the verifier with address A is allowed only in the case the value // of unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] < (current time). mapping(address => uint256) unlockedForRemovalTime; } } /* 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.6.12; import "../interfaces/MGovernance.sol"; /* Holds the governance slots for ALL entities, including proxy and the main contract. */ contract GovernanceStorage { // A map from a Governor tag to its own GovernanceInfoStruct. mapping(string => GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state. } /* 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.6.12; /* Interface for a generic dispatcher to use, which the concrete dispatcher must implement. It contains the functions that are specific to the concrete dispatcher instance. The interface is implemented as contract, because interface implies all methods external. */ abstract contract IDispatcherBase { function getSubContract(bytes4 selector) public view virtual returns (address); function setSubContractAddress(uint256 index, address subContract) internal virtual; function getNumSubcontracts() internal pure virtual returns (uint256); function validateSubContractIndex(uint256 index, address subContract) internal pure virtual; /* Ensures initializer can be called. Reverts otherwise. */ function initializationSentinel() internal view 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.6.12; interface Identity { /* Allows a caller, typically another contract, 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.6.12; struct GovernanceInfoStruct { mapping(address => bool) effectiveGovernors; address candidateGovernor; bool initialized; } abstract contract MGovernance { function _isGovernor(address testGovernor) 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.6.12; import "../components/MainStorage.sol"; import "./MainDispatcherBase.sol"; abstract contract MainDispatcher is MainStorage, MainDispatcherBase { uint256 constant SUBCONTRACT_BITS = 4; function magicSalt() internal pure virtual returns (uint256); function handlerMapSection(uint256 section) internal pure virtual returns (uint256); function expectedIdByIndex(uint256 index) internal pure virtual returns (string memory id); function validateSubContractIndex(uint256 index, address subContract) internal pure override { string memory id = SubContractor(subContract).identify(); bytes32 hashed_expected_id = keccak256(abi.encodePacked(expectedIdByIndex(index))); require( hashed_expected_id == keccak256(abi.encodePacked(id)), "MISPLACED_INDEX_OR_BAD_CONTRACT_ID" ); // Gets the list of critical selectors from the sub-contract and checks that the selector // is mapped to that sub-contract. bytes4[] memory selectorsToValidate = SubContractor(subContract).validatedSelectors(); for (uint256 i = 0; i < selectorsToValidate.length; i++) { require( getSubContractIndex(selectorsToValidate[i]) == index, "INCONSISTENT_DISPATCHER_MAP" ); } } function handlingContractId(bytes4 selector) external pure virtual returns (string memory id) { uint256 index = getSubContractIndex(selector); return expectedIdByIndex(index); } /* Returns the index in subContracts where the address of the sub-contract implementing the function with the queried selector is held. Note: The nature of the sub-contracts handler map is such that all the required selectors are mapped. However, other selectors, such that are not implemented in any subcontract, may also return a sub-contract address. This behavior is by-design, and not a problem. */ function getSubContractIndex(bytes4 selector) internal pure returns (uint256) { uint256 location = 0xFF & uint256(keccak256(abi.encodePacked(selector, magicSalt()))); uint256 offset = (SUBCONTRACT_BITS * location) % 256; // We have 64 locations in each register, hence the >> 6 (i.e. location // 64). return (handlerMapSection(location >> 6) >> offset) & 0xF; } /* Returns the address of the sub-contract that would be delegated to handle a call with the queried selector. (see note above). */ function getSubContract(bytes4 selector) public view override returns (address) { return subContracts[getSubContractIndex(selector)]; } function setSubContractAddress(uint256 index, address subContractAddress) internal override { subContracts[index] = subContractAddress; } } /* 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.6.12; import "./SubContractor.sol"; import "./IDispatcherBase.sol"; import "../interfaces/BlockDirectCall.sol"; import "../libraries/Common.sol"; abstract contract MainDispatcherBase is IDispatcherBase, BlockDirectCall { using Addresses for address; /* This entry point serves only transactions with empty calldata. (i.e. pure value transfer tx). We don't expect to receive such, thus block them. */ receive() external payable { revert("CONTRACT_NOT_EXPECTED_TO_RECEIVE"); } fallback() external payable { address subContractAddress = getSubContract(msg.sig); require(subContractAddress != address(0x0), "NO_CONTRACT_FOR_FUNCTION"); assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 for now, as we don"t know the out size yet. let result := delegatecall(gas(), subContractAddress, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /* 1. Extract subcontracts. 2. Verify correct sub-contract initializer size. 3. Extract sub-contract initializer data. 4. Call sub-contract initializer. The init data bytes passed to initialize are structed as following: I. N slots (uin256 size) addresses of the deployed sub-contracts. II. An address of an external initialization contract (optional, or ZERO_ADDRESS). III. (Up to) N bytes sections of the sub-contracts initializers. If already initialized (i.e. upgrade) we expect the init data to be consistent with this. and if a different size of init data is expected when upgrading, the initializerSize should reflect this. If an external initializer contract is not used, ZERO_ADDRESS is passed in its slot. If the external initializer contract is used, all the remaining init data is passed to it, and internal initialization will not occur. External Initialization Contract -------------------------------- External Initialization Contract (EIC) is a hook for custom initialization. Typically in an upgrade flow, the expected initialization contains only the addresses of the sub-contracts. Normal initialization of the sub-contracts is such that is not needed in an upgrade, and actually may be very dangerous, as changing of state on a working system may corrupt it. In the event that some state initialization is required, the EIC is a hook that allows this. It may be deployed and called specifically for this purpose. The address of the EIC must be provided (if at all) when a new implementation is added to a Proxy contract (as part of the initialization vector). Hence, it is considered part of the code open to reviewers prior to a time-locked upgrade. When a custom initialization is performed using an EIC, the main dispatcher initialize extracts and stores the sub-contracts addresses, and then yields to the EIC, skipping the rest of its initialization code. Flow of MainDispatcher initialize --------------------------------- 1. Extraction and assignment of subcontracts addresses Main dispatcher expects a valid and consistent set of addresses in the passed data. It validates that, extracts the addresses from the data, and validates that the addresses are of the expected type and order. Then those addresses are stored. 2. Extraction of EIC address The address of the EIC is extracted from the data. External Initializer Contract is optional. ZERO_ADDRESS indicates it is not used. 3a. EIC is used Dispatcher calls the EIC initialize function with the remaining data. Note - In this option 3b is not performed. 3b. EIC is not used If there is additional initialization data then: I. Sentitenl function is called to permit subcontracts initialization. II. Dispatcher loops through the subcontracts and for each one it extracts the initializing data and passes it to the subcontract's initialize function. */ function initialize(bytes calldata data) external virtual notCalledDirectly { // Number of sub-contracts. uint256 nSubContracts = getNumSubcontracts(); // We support currently 4 bits per contract, i.e. 16, reserving 00 leads to 15. require(nSubContracts <= 15, "TOO_MANY_SUB_CONTRACTS"); // Sum of subcontract initializers. Aggregated for verification near the end. uint256 totalInitSizes = 0; // Offset (within data) of sub-contract initializer vector. // Just past the sub-contract+eic addresses. uint256 initDataContractsOffset = 32 * (nSubContracts + 1); // Init data MUST include addresses for all sub-contracts + EIC. require(data.length >= initDataContractsOffset, "SUB_CONTRACTS_NOT_PROVIDED"); // Size of passed data, excluding sub-contract addresses. uint256 additionalDataSize = data.length - initDataContractsOffset; // Extract & update contract addresses. for (uint256 nContract = 1; nContract <= nSubContracts; nContract++) { // Extract sub-contract address. address contractAddress = abi.decode( data[32 * (nContract - 1):32 * nContract], (address) ); validateSubContractIndex(nContract, contractAddress); // Contracts are indexed from 1 and 0 is not in use here. setSubContractAddress(nContract, contractAddress); } // Check if we have an external initializer contract. address externalInitializerAddr = abi.decode( data[initDataContractsOffset - 32:initDataContractsOffset], (address) ); // 3(a). Yield to EIC initialization. if (externalInitializerAddr != address(0x0)) { callExternalInitializer(externalInitializerAddr, data[initDataContractsOffset:]); return; } // 3(b). Subcontracts initialization. // I. If no init data passed besides sub-contracts, return. if (additionalDataSize == 0) { return; } // Just to be on the safe side. assert(externalInitializerAddr == address(0x0)); // II. Gate further initialization. initializationSentinel(); // III. Loops through the subcontracts, extracts their data and calls their initializer. for (uint256 nContract = 1; nContract <= nSubContracts; nContract++) { // Extract sub-contract address. address contractAddress = abi.decode( data[32 * (nContract - 1):32 * nContract], (address) ); // The initializerSize is called via delegatecall, so that it can relate to the state, // and not only to the new contract code. (e.g. return 0 if state-intialized else 192). // NOLINTNEXTLINE: controlled-delegatecall low-level-calls calls-loop. (bool success, bytes memory returndata) = contractAddress.delegatecall( abi.encodeWithSelector(SubContractor(contractAddress).initializerSize.selector) ); require(success, string(returndata)); uint256 initSize = abi.decode(returndata, (uint256)); require(initSize <= additionalDataSize, "INVALID_INITIALIZER_SIZE"); require(totalInitSizes + initSize <= additionalDataSize, "INVALID_INITIALIZER_SIZE"); if (initSize == 0) { continue; } // Call sub-contract initializer. // NOLINTNEXTLINE: controlled-delegatecall calls-loop. (success, returndata) = contractAddress.delegatecall( abi.encodeWithSelector( this.initialize.selector, data[initDataContractsOffset:initDataContractsOffset + initSize] ) ); require(success, string(returndata)); totalInitSizes += initSize; initDataContractsOffset += initSize; } require(additionalDataSize == totalInitSizes, "MISMATCHING_INIT_DATA_SIZE"); } function callExternalInitializer(address externalInitializerAddr, bytes calldata extInitData) private { require(externalInitializerAddr.isContract(), "NOT_A_CONTRACT"); // NOLINTNEXTLINE: low-level-calls, controlled-delegatecall. (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall( abi.encodeWithSelector(this.initialize.selector, extInitData) ); 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.6.12; import "../upgrade/ProxyStorage.sol"; import "../libraries/Common.sol"; /* Holds ALL the main contract state (storage) variables. */ contract MainStorage is ProxyStorage { uint256 internal constant LAYOUT_LENGTH = 2**64; address escapeVerifierAddress; // NOLINT: constable-states. // Global dex-frozen flag. bool stateFrozen; // NOLINT: constable-states. // Time when unFreeze can be successfully called (UNFREEZE_DELAY after freeze). uint256 unFreezeTime; // NOLINT: constable-states. // Pending deposits. // A map STARK key => asset id => vault id => quantized amount. mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) pendingDeposits; // Cancellation requests. // A map STARK key => asset id => vault id => request timestamp. mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) cancellationRequests; // Pending withdrawals. // A map STARK key => asset id => quantized amount. mapping(uint256 => mapping(uint256 => uint256)) pendingWithdrawals; // vault_id => escape used boolean. mapping(uint256 => bool) escapesUsed; // Number of escapes that were performed when frozen. uint256 escapesUsedCount; // NOLINT: constable-states. // NOTE: fullWithdrawalRequests is deprecated, and replaced by forcedActionRequests. // NOLINTNEXTLINE naming-convention. mapping(uint256 => mapping(uint256 => uint256)) fullWithdrawalRequests_DEPRECATED; // State sequence number. uint256 sequenceNumber; // NOLINT: constable-states uninitialized-state. // Validium Vaults Tree Root & Height. uint256 validiumVaultRoot; // NOLINT: constable-states uninitialized-state. uint256 validiumTreeHeight; // NOLINT: constable-states uninitialized-state. // Order Tree Root & Height. uint256 orderRoot; // NOLINT: constable-states uninitialized-state. uint256 orderTreeHeight; // NOLINT: constable-states uninitialized-state. // True if and only if the address is allowed to add tokens. mapping(address => bool) tokenAdmins; // This mapping is no longer in use, remains for backwards compatibility. mapping(address => bool) userAdmins_DEPRECATED; // NOLINT: naming-convention. // True if and only if the address is an operator (allowed to update state). mapping(address => bool) operators; // NOLINT: uninitialized-state. // Mapping of contract ID to asset data. mapping(uint256 => bytes) assetTypeToAssetInfo; // NOLINT: uninitialized-state. // Mapping of registered contract IDs. mapping(uint256 => bool) registeredAssetType; // NOLINT: uninitialized-state. // Mapping from contract ID to quantum. mapping(uint256 => uint256) assetTypeToQuantum; // NOLINT: uninitialized-state. // This mapping is no longer in use, remains for backwards compatibility. mapping(address => uint256) starkKeys_DEPRECATED; // NOLINT: naming-convention. // Mapping from STARK public key to the Ethereum public key of its owner. mapping(uint256 => address) ethKeys; // NOLINT: uninitialized-state. // Timelocked state transition and availability verification chain. StarkExTypes.ApprovalChainData verifiersChain; StarkExTypes.ApprovalChainData availabilityVerifiersChain; // Batch id of last accepted proof. uint256 lastBatchId; // NOLINT: constable-states uninitialized-state. // Mapping between sub-contract index to sub-contract address. mapping(uint256 => address) subContracts; // NOLINT: uninitialized-state. mapping(uint256 => bool) permissiveAssetType_DEPRECATED; // NOLINT: naming-convention. // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX2.0 ---- // Onchain-data version configured for the system. uint256 onchainDataVersion_DEPRECATED; // NOLINT: naming-convention constable-states. // Counter of forced action request in block. The key is the block number. mapping(uint256 => uint256) forcedRequestsInBlock; // ForcedAction requests: actionHash => requestTime. mapping(bytes32 => uint256) forcedActionRequests; // Mapping for timelocked actions. // A actionKey => activation time. mapping(bytes32 => uint256) actionsTimeLock; // Append only list of requested forced action hashes. bytes32[] actionHashList; // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX3.0 ---- // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX4.0 ---- // Rollup Vaults Tree Root & Height. uint256 rollupVaultRoot; // NOLINT: constable-states uninitialized-state. uint256 rollupTreeHeight; // NOLINT: constable-states uninitialized-state. uint256 globalConfigCode; // NOLINT: constable-states uninitialized-state. // Mapping of owner keys that are blocked from withdrawals. mapping(uint256 => uint256) internal blockListed; // Reserved storage space for Extensibility. // Every added MUST be added above the end gap, and the __endGap size must be reduced // accordingly. // NOLINTNEXTLINE: naming-convention. uint256[LAYOUT_LENGTH - 41] private __endGap; // __endGap complements layout to LAYOUT_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.6.12; import "../components/GovernanceStorage.sol"; /* Holds the Proxy-specific state variables. This contract is inherited by the GovernanceStorage (and indirectly by MainStorage) to prevent collision hazard. */ contract ProxyStorage is GovernanceStorage { // NOLINTNEXTLINE: naming-convention uninitialized-state. mapping(address => bytes32) internal initializationHash_DEPRECATED; // The time after which we can switch to the implementation. // Hash(implementation, data, finalize) => time. mapping(bytes32 => uint256) internal enabledTime; // A central storage of the flags whether implementation has been initialized. // Note - it can be used flexibly enough to accommodate multiple levels of initialization // (i.e. using different key salting schemes for different initialization levels). mapping(bytes32 => bool) internal initialized; } /* 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.6.12; import "../interfaces/MainDispatcher.sol"; contract StarkExchange is MainDispatcher { string public constant VERSION = "4.5.3-blc"; // Salt for a 8 bit unique spread of all relevant selectors. Pre-caclulated. // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- uint256 constant MAGIC_SALT = 4259003; uint256 constant IDX_MAP_0 = 0x1030220010120000001021030000002223022000021220125001010000021300; uint256 constant IDX_MAP_1 = 0x2023105020000205000002451020200305120020000000000002230015000201; uint256 constant IDX_MAP_2 = 0x1000000030000003000002000000020000500100500230025010222000010; uint256 constant IDX_MAP_3 = 0x420002010300345030000000005010021020004000000050002052300060001; // ---------- End of auto-generated code. ---------- function getNumSubcontracts() internal pure override returns (uint256) { return 6; } function magicSalt() internal pure override returns (uint256) { return MAGIC_SALT; } function handlerMapSection(uint256 section) internal pure override returns (uint256) { if (section == 0) { return IDX_MAP_0; } else if (section == 1) { return IDX_MAP_1; } else if (section == 2) { return IDX_MAP_2; } else if (section == 3) { return IDX_MAP_3; } revert("BAD_IDX_MAP_SECTION"); } function expectedIdByIndex(uint256 index) internal pure override returns (string memory id) { if (index == 1) { id = "StarkWare_AllVerifiers_2022_2"; } else if (index == 2) { id = "StarkWare_TokensAndRamping_2024_4"; } else if (index == 3) { id = "StarkWare_StarkExState_2022_5"; } else if (index == 4) { id = "StarkWare_ForcedActions_2022_3"; } else if (index == 5) { id = "StarkWare_OnchainVaults_2022_2"; } else if (index == 6) { id = "StarkWare_ProxyUtils_2022_2"; } else { revert("UNEXPECTED_INDEX"); } } function initializationSentinel() internal view override { string memory REVERT_MSG = "INITIALIZATION_BLOCKED"; // This initializer sets roots etc. It must not be applied twice. // I.e. it can run only when the state is still empty. require(validiumVaultRoot == 0, REVERT_MSG); require(validiumTreeHeight == 0, REVERT_MSG); require(rollupVaultRoot == 0, REVERT_MSG); require(rollupTreeHeight == 0, REVERT_MSG); require(orderRoot == 0, REVERT_MSG); require(orderTreeHeight == 0, REVERT_MSG); } } /* 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.6.12; import "./Identity.sol"; interface SubContractor is Identity { function initialize(bytes calldata data) external; function initializerSize() external view returns (uint256); /* Returns an array with selectors for validation. These selectors are the critical ones for maintaining self custody and anti censorship. During the upgrade process, as part of the sub-contract validation, the MainDispatcher validates that the selectos are mapped to the correct sub-contract. */ function validatedSelectors() external pure returns (bytes4[] memory); }
File 4 of 8: TokensAndRamping
/* 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.6.12; import "../libraries/LibConstants.sol"; import "../interfaces/MAcceptModifications.sol"; import "../interfaces/MTokenQuantization.sol"; import "../components/MainStorage.sol"; /* Interface containing actions a verifier can invoke on the state. The contract containing the state should implement these and verify correctness. */ abstract contract AcceptModifications is MainStorage, LibConstants, MAcceptModifications, MTokenQuantization { event LogWithdrawalAllowed( uint256 ownerKey, uint256 assetType, uint256 nonQuantizedAmount, uint256 quantizedAmount ); event LogNftWithdrawalAllowed(uint256 ownerKey, uint256 assetId); event LogAssetWithdrawalAllowed(uint256 ownerKey, uint256 assetId, uint256 quantizedAmount); event LogMintableWithdrawalAllowed(uint256 ownerKey, uint256 assetId, uint256 quantizedAmount); /* Transfers funds from the on-chain deposit area to the off-chain area. Implemented in the Deposits contracts. */ function acceptDeposit( uint256 ownerKey, uint256 vaultId, uint256 assetId, uint256 quantizedAmount ) internal virtual override { // Fetch deposit. require( pendingDeposits[ownerKey][assetId][vaultId] >= quantizedAmount, "DEPOSIT_INSUFFICIENT" ); // Subtract accepted quantized amount. pendingDeposits[ownerKey][assetId][vaultId] -= quantizedAmount; } /* Transfers funds from the off-chain area to the on-chain withdrawal area. */ function allowWithdrawal( uint256 ownerKey, uint256 assetId, uint256 quantizedAmount ) internal override { // Fetch withdrawal. uint256 withdrawal = pendingWithdrawals[ownerKey][assetId]; // Add accepted quantized amount. withdrawal += quantizedAmount; require(withdrawal >= quantizedAmount, "WITHDRAWAL_OVERFLOW"); // Store withdrawal. pendingWithdrawals[ownerKey][assetId] = withdrawal; // Log event. uint256 presumedAssetType = assetId; if (registeredAssetType[presumedAssetType]) { emit LogWithdrawalAllowed( ownerKey, presumedAssetType, fromQuantized(presumedAssetType, quantizedAmount), quantizedAmount ); } else if (assetId == ((assetId & MASK_240) | MINTABLE_ASSET_ID_FLAG)) { emit LogMintableWithdrawalAllowed(ownerKey, assetId, quantizedAmount); } else { // Default case is Non-Mintable ERC721 or ERC1155 asset id. // In ERC721 and ERC1155 cases, assetId is not the assetType. require(assetId == assetId & MASK_250, "INVALID_ASSET_ID"); // If withdrawal amount is 1, the asset could be either NFT or SFT. In that case, both // NFT and general events will be emitted so that the listened for event is captured. // When withdrawal is greater than 1, it must be SFT and only one event will be emitted. if (withdrawal <= 1) { emit LogNftWithdrawalAllowed(ownerKey, assetId); } emit LogAssetWithdrawalAllowed(ownerKey, assetId, quantizedAmount); } } // Verifier authorizes withdrawal. function acceptWithdrawal( uint256 ownerKey, uint256 assetId, uint256 quantizedAmount ) internal virtual override { allowWithdrawal(ownerKey, assetId, quantizedAmount); } } /* 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.6.12; import "../components/MainStorage.sol"; import "../libraries/LibConstants.sol"; /* Calculation action hash for the various forced actions in a generic manner. */ contract ActionHash is MainStorage, LibConstants { function getActionHash(string memory actionName, bytes memory packedActionParameters) internal pure returns (bytes32 actionHash) { actionHash = keccak256(abi.encodePacked(actionName, packedActionParameters)); } function setActionHash(bytes32 actionHash, bool premiumCost) internal { // The rate of forced trade requests is restricted. // First restriction is by capping the number of requests in a block. // User can override this cap by requesting with a permium flag set, // in this case, the gas cost is high (~1M) but no "technical" limit is set. // However, the high gas cost creates an obvious limitation due to the block gas limit. if (premiumCost) { for (uint256 i = 0; i < 21129; i++) {} } else { require( forcedRequestsInBlock[block.number] < MAX_FORCED_ACTIONS_REQS_PER_BLOCK, "MAX_REQUESTS_PER_BLOCK_REACHED" ); forcedRequestsInBlock[block.number] += 1; } forcedActionRequests[actionHash] = block.timestamp; actionHashList.push(actionHash); } function getActionCount() external view returns (uint256) { return actionHashList.length; } function getActionHashByIndex(uint256 actionIndex) external view returns (bytes32) { require(actionIndex < actionHashList.length, "ACTION_INDEX_TOO_HIGH"); return actionHashList[actionIndex]; } } /* 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.6.12; import "../components/MainStorage.sol"; import "../interfaces/MBlocklist.sol"; abstract contract Blocklist is MainStorage, MBlocklist { uint256 constant CLEARANCE_DELAY = 2 weeks; // NOLINTNEXTLINE: external-function. function isBlockListed(uint256 ownerKey) public view override returns (bool) { return blockListed[ownerKey] > 0; } function readyForClearance(uint256 ownerKey) public view override returns (bool) { return isBlockListed(ownerKey) && blockListed[ownerKey] <= block.timestamp; } function addToBlockedList(uint256 ownerKey) public override onlyBlockAdmin { if (!isBlockListed(ownerKey)) { emit BlockPlaced(ownerKey); } blockListed[ownerKey] = block.timestamp + CLEARANCE_DELAY; } function removeFromBlockedList(uint256 ownerKey) public override onlyBlockAdmin { if (isBlockListed(ownerKey)) { emit BlockReleased(ownerKey); } blockListed[ownerKey] = 0; } } /* 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.6.12; /* Common Utility librarries. I. Addresses (extending address). */ library Addresses { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function performEthTransfer(address recipient, uint256 amount) internal { (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"); } } /* Validates that the passed contract address is of a real contract, and that its id hash (as infered fromn identify()) matched the expected one. */ function validateContractId(address contractAddress, bytes32 expectedIdHash) internal { require(isContract(contractAddress), "ADDRESS_NOT_CONTRACT"); (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls. abi.encodeWithSignature("identify()") ); require(success, "FAILED_TO_IDENTIFY_CONTRACT"); string memory realContractId = abi.decode(returndata, (string)); require( keccak256(abi.encodePacked(realContractId)) == expectedIdHash, "UNEXPECTED_CONTRACT_IDENTIFIER" ); } } /* II. StarkExTypes - Common data types. */ library StarkExTypes { // Structure representing a list of verifiers (validity/availability). // A statement is valid only if all the verifiers in the list agree on it. // Adding a verifier to the list is immediate - this is used for fast resolution of // any soundness issues. // Removing from the list is time-locked, to ensure that any user of the system // not content with the announced removal has ample time to leave the system before it is // removed. struct ApprovalChainData { address[] list; // Represents the time after which the verifier with the given address can be removed. // Removal of the verifier with address A is allowed only in the case the value // of unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] < (current time). mapping(address => uint256) unlockedForRemovalTime; } } /* 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.6.12; import "../libraries/LibConstants.sol"; import "../interfaces/MAcceptModifications.sol"; import "../interfaces/MDeposits.sol"; import "../interfaces/MTokenQuantization.sol"; import "../interfaces/MTokenAssetData.sol"; import "../interfaces/MFreezable.sol"; import "../interfaces/MKeyGetters.sol"; import "../interfaces/MTokenTransfers.sol"; import "../components/MainStorage.sol"; /** For a user to perform a deposit to the contract two calls need to take place: 1. A call to an ERC20 contract, authorizing this contract to transfer funds on behalf of the user. 2. A call to :sol:func:`deposit` indicating the starkKey, amount, asset type and target vault ID to which to send the deposit. The amount should be quantized, according to the specific quantization defined for the asset type. The result of the operation, assuming all requirements are met, is that an amount of ERC20 tokens equaling the amount specified in the :sol:func:`deposit` call times the quantization factor is transferred on behalf of the user to the contract. In addition, the contract adds the funds to an accumulator of pending deposits for the provided user, asset ID and vault ID. Once a deposit is made, the exchange may include it in a proof which will result in addition of the amount(s) deposited to the off-chain vault with the specified ID. When the contract receives such valid proof, it deducts the transfered funds from the pending deposits for the specified Stark key, asset ID and vault ID. The exchange will not be able to move the deposited funds to the off-chain vault if the Stark key is not registered in the system. Until that point, the user may cancel the deposit by performing a time-locked cancel-deposit operation consisting of two calls: 1. A call to :sol:func:`depositCancel`, setting a timer to enable reclaiming the deposit. Until this timer expires the user cannot reclaim funds as the exchange may still be processing the deposit for inclusion in the off chain vault. 2. A call to :sol:func:`depositReclaim`, to perform the actual transfer of funds from the contract back to the ERC20 contract. This will only succeed if the timer set in the previous call has expired. The result should be the transfer of all funds not accounted for in proofs for off-chain inclusion, back to the user account on the ERC20 contract. Calling depositCancel and depositReclaim can only be done via an ethKey that is associated with that vault's starkKey. This is enforced by the contract. */ abstract contract Deposits is MainStorage, LibConstants, MAcceptModifications, MDeposits, MTokenQuantization, MTokenAssetData, MFreezable, MKeyGetters, MTokenTransfers { event LogDeposit( address depositorEthKey, uint256 starkKey, uint256 vaultId, uint256 assetType, uint256 nonQuantizedAmount, uint256 quantizedAmount ); event LogNftDeposit( address depositorEthKey, uint256 starkKey, uint256 vaultId, uint256 assetType, uint256 tokenId, uint256 assetId ); event LogDepositWithTokenId( address depositorEthKey, uint256 starkKey, uint256 vaultId, uint256 assetType, uint256 tokenId, uint256 assetId, uint256 nonQuantizedAmount, uint256 quantizedAmount ); event LogDepositCancel(uint256 starkKey, uint256 vaultId, uint256 assetId); event LogDepositCancelReclaimed( uint256 starkKey, uint256 vaultId, uint256 assetType, uint256 nonQuantizedAmount, uint256 quantizedAmount ); event LogDepositNftCancelReclaimed( uint256 starkKey, uint256 vaultId, uint256 assetType, uint256 tokenId, uint256 assetId ); event LogDepositWithTokenIdCancelReclaimed( uint256 starkKey, uint256 vaultId, uint256 assetType, uint256 tokenId, uint256 assetId, uint256 nonQuantizedAmount, uint256 quantizedAmount ); function getDepositBalance( uint256 starkKey, uint256 assetId, uint256 vaultId ) external view returns (uint256) { uint256 presumedAssetType = assetId; return fromQuantized(presumedAssetType, pendingDeposits[starkKey][assetId][vaultId]); } function getQuantizedDepositBalance( uint256 starkKey, uint256 assetId, uint256 vaultId ) external view returns (uint256) { return pendingDeposits[starkKey][assetId][vaultId]; } function depositNft( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 tokenId ) external notFrozen { require(isERC721(assetType), "NOT_ERC721_TOKEN"); depositWithTokenId(starkKey, assetType, tokenId, vaultId, 1); } function depositERC1155( uint256 starkKey, uint256 assetType, uint256 tokenId, uint256 vaultId, uint256 quantizedAmount ) external notFrozen { require(isERC1155(assetType), "NOT_ERC1155_TOKEN"); depositWithTokenId(starkKey, assetType, tokenId, vaultId, quantizedAmount); } function depositStateUpdate( uint256 starkKey, uint256 assetId, uint256 vaultId, uint256 quantizedAmount ) private returns (uint256) { // Checks for overflow and updates the pendingDeposits balance. uint256 vaultBalance = pendingDeposits[starkKey][assetId][vaultId]; vaultBalance += quantizedAmount; require(vaultBalance >= quantizedAmount, "DEPOSIT_OVERFLOW"); pendingDeposits[starkKey][assetId][vaultId] = vaultBalance; // Disable the cancellationRequest timeout when users deposit into their own account. if ( isMsgSenderKeyOwner(starkKey) && cancellationRequests[starkKey][assetId][vaultId] != 0 ) { delete cancellationRequests[starkKey][assetId][vaultId]; } // Returns the updated vault balance. return vaultBalance; } function depositWithTokenId( uint256 starkKey, uint256 assetType, uint256 tokenId, uint256 vaultId, uint256 quantizedAmount ) public notFrozen { // The vaultId is not validated but should be in the allowed range supported by the // exchange. If not, it will be ignored by the exchange and the starkKey owner may reclaim // the funds by using depositCancel + depositReclaim. require(isAssetTypeWithTokenId(assetType), "INVALID_ASSET_TYPE"); uint256 assetId = calculateAssetIdWithTokenId(assetType, tokenId); // Updates the pendingDeposits balance and clears cancellationRequests when applicable. uint256 newVaultBalance = depositStateUpdate(starkKey, assetId, vaultId, quantizedAmount); // No need to verify amount > 0, a deposit with amount = 0 can be used to undo cancellation. if (isERC721(assetType)) { require(newVaultBalance <= 1, "ILLEGAL_ERC721_AMOUNT"); emit LogNftDeposit(msg.sender, starkKey, vaultId, assetType, tokenId, assetId); } // Transfer the tokens to the Deposit contract. transferInWithTokenId(assetType, tokenId, quantizedAmount); // Log event. emit LogDepositWithTokenId( msg.sender, starkKey, vaultId, assetType, tokenId, assetId, fromQuantized(assetType, quantizedAmount), quantizedAmount ); } function getCancellationRequest( uint256 starkKey, uint256 assetId, uint256 vaultId ) external view returns (uint256 request) { request = cancellationRequests[starkKey][assetId][vaultId]; } function depositERC20( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 quantizedAmount ) public override { deposit(starkKey, assetType, vaultId, quantizedAmount); } // NOLINTNEXTLINE: locked-ether. function depositEth( uint256 starkKey, uint256 assetType, uint256 vaultId ) public payable override { require(isEther(assetType), "INVALID_ASSET_TYPE"); deposit(starkKey, assetType, vaultId, toQuantized(assetType, msg.value)); } function deposit( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 quantizedAmount ) public notFrozen { // The vaultId is not validated but should be in the allowed range supported by the // exchange. If not, it will be ignored by the exchange and the starkKey owner may reclaim // the funds by using depositCancel + depositReclaim. // No need to verify amount > 0, a deposit with amount = 0 can be used to undo cancellation. require(!isMintableAssetType(assetType), "MINTABLE_ASSET_TYPE"); require(isFungibleAssetType(assetType), "NON_FUNGIBLE_ASSET_TYPE"); uint256 assetId = assetType; // Updates the pendingDeposits balance and clears cancellationRequests when applicable. depositStateUpdate(starkKey, assetId, vaultId, quantizedAmount); // Transfer the tokens to the Deposit contract. transferIn(assetType, quantizedAmount); // Log event. emit LogDeposit( msg.sender, starkKey, vaultId, assetType, fromQuantized(assetType, quantizedAmount), quantizedAmount ); } function deposit( // NOLINT: locked-ether. uint256 starkKey, uint256 assetType, uint256 vaultId ) external payable { require(isEther(assetType), "INVALID_ASSET_TYPE"); deposit(starkKey, assetType, vaultId, toQuantized(assetType, msg.value)); } function depositCancel( uint256 starkKey, uint256 assetId, uint256 vaultId ) external onlyKeyOwner(starkKey) // No notFrozen modifier: This function can always be used, even when frozen. { // Allow cancellation only for real deposit that were placed. require(pendingDeposits[starkKey][assetId][vaultId] > 0, "DEPOSIT_DOESNT_EXIST"); // Start the timeout. cancellationRequests[starkKey][assetId][vaultId] = block.timestamp; // Log event. emit LogDepositCancel(starkKey, vaultId, assetId); } function clearCancelledDeposit( uint256 starkKey, uint256 assetId, uint256 vaultId ) private returns (uint256) { // Make sure enough time has passed. uint256 requestTime = cancellationRequests[starkKey][assetId][vaultId]; require(requestTime != 0, "DEPOSIT_NOT_CANCELED"); uint256 freeTime = requestTime + DEPOSIT_CANCEL_DELAY; assert(freeTime >= DEPOSIT_CANCEL_DELAY); require(block.timestamp >= freeTime, "DEPOSIT_LOCKED"); // NOLINT: timestamp. // Clear deposit. uint256 quantizedAmount = pendingDeposits[starkKey][assetId][vaultId]; delete pendingDeposits[starkKey][assetId][vaultId]; delete cancellationRequests[starkKey][assetId][vaultId]; // Return the cleared amount so it can be transferred back to the reclaimer. return quantizedAmount; } function depositReclaim( uint256 starkKey, uint256 assetType, uint256 vaultId ) external onlyKeyOwner(starkKey) // No notFrozen modifier: This function can always be used, even when frozen. { require(isFungibleAssetType(assetType), "NON_FUNGIBLE_ASSET_TYPE"); // Clear deposit and attain the cleared amount to be transferred out. uint256 assetId = assetType; uint256 quantizedAmount = clearCancelledDeposit(starkKey, assetId, vaultId); // Refund deposit. transferOut(msg.sender, assetType, quantizedAmount); // Log event. emit LogDepositCancelReclaimed( starkKey, vaultId, assetType, fromQuantized(assetType, quantizedAmount), quantizedAmount ); } function depositWithTokenIdReclaim( uint256 starkKey, uint256 assetType, uint256 tokenId, uint256 vaultId ) public onlyKeyOwner(starkKey) // No notFrozen modifier: This function can always be used, even when frozen. { require(isAssetTypeWithTokenId(assetType), "INVALID_ASSET_TYPE"); // Clear deposit and attain the cleared amount to be transferred out. uint256 assetId = calculateAssetIdWithTokenId(assetType, tokenId); uint256 quantizedAmount = clearCancelledDeposit(starkKey, assetId, vaultId); if (quantizedAmount > 0) { // Refund deposit. transferOutWithTokenId(msg.sender, assetType, tokenId, quantizedAmount); } // Log event. if (isERC721(assetType)) { emit LogDepositNftCancelReclaimed(starkKey, vaultId, assetType, tokenId, assetId); } emit LogDepositWithTokenIdCancelReclaimed( starkKey, vaultId, assetType, tokenId, assetId, fromQuantized(assetType, quantizedAmount), quantizedAmount ); } function depositNftReclaim( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 tokenId ) external onlyKeyOwner(starkKey) // No notFrozen modifier: This function can always be used, even when frozen. { depositWithTokenIdReclaim(starkKey, assetType, tokenId, vaultId); } } /* 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.6.12; import "../tokens/ERC1155/IERC1155Receiver.sol"; /* ERC1155 token receiver interface. EIP-1155 requires any contract receiving ERC1155 tokens to implement IERC1155Receiver interface. By EIP: 1. safeTransferFrom API of ERC1155 shall call onERC1155Received on the receiving contract. 2. safeBatchTransferFrom API of ERC1155 to call onERC1155BatchReceived on the receiving contract. Have the receiving contract failed to respond as expected, the safe transfer functions shall be reverted. */ contract ERC1155Receiver is IERC1155Receiver { /** Handles the receipt of a single ERC1155 token type. @param `operator` The address which called `safeTransferFrom` function @param `from` The address which previously owned the token @param `id` The identifier of the token which is being transferred @param `value` the amount of token units being transferred @param `data` Additional data with no specified format Returns: When invoked by the receiving contract, satisfying the deposit pattern (i.e. operator == this) `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` is returned. In all other cases returns `bytes4(0)`, which should invoke an error of the form `ERC1155: ERC1155Receiver rejected tokens`. */ function onERC1155Received( address operator, address, // from uint256, // id uint256, // value bytes calldata // data ) external override returns (bytes4) { return (operator == address(this) ? this.onERC1155Received.selector : bytes4(0)); } /** Handles the receipt of multiple ERC1155 token types. @param `operator` The address which called `safeBatchTransferFrom` function @param `from` The address which previously owned the token @param `ids` The identifier of the token which is being transferred @param `values` the amount of token units being transferred @param `data` Additional data with no specified format Returns: When invoked by the receiving contract, satisfying the deposit pattern (i.e. operator == this) `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256,uint256,bytes)"))` is returned. In all other cases returns `bytes4(0)`, which should invoke an error of the form `ERC1155: ERC1155Receiver rejected tokens`. Note: a rejection value `bytes4(0)` is to be expected. Batch deposits are unsupported by StarkEx. */ function onERC1155BatchReceived( address operator, address, // from uint256[] calldata, // ids uint256[] calldata, // values bytes calldata // data ) external override returns (bytes4) { return (operator == address(this) ? this.onERC1155BatchReceived.selector : bytes4(0)); } } /* 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.6.12; import "../tokens/ERC721/IERC721Receiver.sol"; /* ERC721 token receiver interface EIP-721 requires any contract receiving ERC721 tokens to implement IERC721Receiver interface. By EIP, safeTransferFrom API of ERC721 shall call onERC721Received on the receiving contract. Have the receiving contract failed to respond as expected, the safeTransferFrom shall be reverted. Params: `operator` The address which called `safeTransferFrom` function `from` The address which previously owned the token `tokenId` The NFT identifier which is being transferred `data` Additional data with no specified format Returns: When invoked by the main contract, following the deposit pattern: `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, which indicates success. In all other cases: `bytes4(0)`, which should fail ERC721's safeTransferFrom. */ contract ERC721Receiver is IERC721Receiver { function onERC721Received( address operator, // The address which called `safeTransferFrom` function. address, // from - The address which previously owned the token. uint256, // tokenId - The NFT identifier which is being transferred. bytes calldata // data - Additional data with no specified format. ) external override returns (bytes4) { return (operator == address(this) ? this.onERC721Received.selector : bytes4(0)); } } /* 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.6.12; import "../libraries/LibConstants.sol"; import "../interfaces/MFreezable.sol"; import "../interfaces/MGovernance.sol"; import "./MainStorage.sol"; /* Implements MFreezable. */ abstract contract Freezable is MainStorage, LibConstants, MGovernance, MFreezable { event LogFrozen(); event LogUnFrozen(); function isFrozen() public view override returns (bool) { return stateFrozen; } function validateFreezeRequest(uint256 requestTime) internal override { require(requestTime != 0, "FORCED_ACTION_UNREQUESTED"); // Verify timer on escape request. uint256 freezeTime = requestTime + FREEZE_GRACE_PERIOD; // Prevent wraparound. assert(freezeTime >= FREEZE_GRACE_PERIOD); require(block.timestamp >= freezeTime, "FORCED_ACTION_PENDING"); // NOLINT: timestamp. // Forced action requests placed before freeze, are no longer valid after the un-freeze. require(freezeTime > unFreezeTime, "REFREEZE_ATTEMPT"); } function freeze() internal override notFrozen { unFreezeTime = block.timestamp + UNFREEZE_DELAY; // Update state. stateFrozen = true; // Log event. emit LogFrozen(); } function unFreeze() external onlyFrozen onlyGovernance { require(block.timestamp >= unFreezeTime, "UNFREEZE_NOT_ALLOWED_YET"); // Update state. stateFrozen = false; // Increment roots to invalidate them, w/o losing information. validiumVaultRoot += 1; rollupVaultRoot += 1; orderRoot += 1; // Log event. emit LogUnFrozen(); } } /* 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.6.12; 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. */ 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 addGovernor() won't fail. // Add the initial governer. addGovernor(msg.sender); } function _isGovernor(address testGovernor) internal view override returns (bool) { GovernanceInfoStruct storage gub = getGovernanceInfo(); return gub.effectiveGovernors[testGovernor]; } /* Cancels the nomination of a governor candidate. */ function _cancelNomination() internal onlyGovernance { GovernanceInfoStruct storage gub = getGovernanceInfo(); gub.candidateGovernor = address(0x0); emit LogNominationCancelled(); } function _nominateNewGovernor(address newGovernor) internal onlyGovernance { GovernanceInfoStruct storage gub = getGovernanceInfo(); require(!_isGovernor(newGovernor), "ALREADY_GOVERNOR"); gub.candidateGovernor = newGovernor; emit LogNominatedGovernor(newGovernor); } /* The addGovernor 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 addGovernor(address newGovernor) private { require(!_isGovernor(newGovernor), "ALREADY_GOVERNOR"); GovernanceInfoStruct storage gub = getGovernanceInfo(); gub.effectiveGovernors[newGovernor] = true; } 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. addGovernor(gub.candidateGovernor); gub.candidateGovernor = address(0x0); // Send a notification about the change of governor. emit LogNewGovernorAccepted(msg.sender); } /* 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.6.12; import "../interfaces/MGovernance.sol"; /* Holds the governance slots for ALL entities, including proxy and the main contract. */ contract GovernanceStorage { // A map from a Governor tag to its own GovernanceInfoStruct. mapping(string => GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state. } /* 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. pragma solidity ^0.6.12; /** Required interface of an ERC1155 compliant contract, as defined in the https://eips.ethereum.org/EIPS/eip-1155[EIP]. _Available since v3.1. */ interface IERC1155 { /** Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /** Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. If an {URI} event was emitted for `id`, the standard https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** Returns the amount of tokens of token type `id` owned by `account`. Requirements: - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** Requirements: - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, Emits an {ApprovalForAll} event. Requirements: - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** Returns true if `operator` is approved to transfer ``account``'s tokens. See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** Transfers `amount` tokens of token type `id` from `from` to `to`. Emits a {TransferSingle} event. Requirements: - `to` cannot be the zero address. - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. - `from` must have a balance of tokens of type `id` of at least `amount`. - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** Emits a {TransferBatch} event. Requirements: - `ids` and `amounts` must have the same length. - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) 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.6.12; /** Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface IERC1155Receiver { /** Handles the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` . */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** Handles the receipt of multiple ERC1155 token types. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` . */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } /* 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.6.12; /** 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.6.12; interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /* 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.6.12; interface Identity { /* Allows a caller, typically another contract, 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.6.12; import "../components/MainStorage.sol"; import "../interfaces/MKeyGetters.sol"; /* Implements MKeyGetters. */ contract KeyGetters is MainStorage, MKeyGetters { uint256 internal constant MASK_ADDRESS = (1 << 160) - 1; /* Returns the Ethereum public key (address) that owns the given ownerKey. If the ownerKey size is within the range of an Ethereum address (i.e. < 2**160) it returns the owner key itself. If the ownerKey is larger than a potential eth address, the eth address for which the starkKey was registered is returned, and 0 if the starkKey is not registered. Note - prior to version 4.0 this function reverted on an unregistered starkKey. For a variant of this function that reverts on an unregistered starkKey, use strictGetEthKey. */ function getEthKey(uint256 ownerKey) public view override returns (address) { address registeredEth = ethKeys[ownerKey]; if (registeredEth != address(0x0)) { return registeredEth; } return ownerKey == (ownerKey & MASK_ADDRESS) ? address(ownerKey) : address(0x0); } /* Same as getEthKey, but fails when a stark key is not registered. */ function strictGetEthKey(uint256 ownerKey) internal view override returns (address ethKey) { ethKey = getEthKey(ownerKey); require(ethKey != address(0x0), "USER_UNREGISTERED"); } function isMsgSenderKeyOwner(uint256 ownerKey) internal view override returns (bool) { return msg.sender == getEthKey(ownerKey); } } /* 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.6.12; contract LibConstants { // Durations for time locked mechanisms (in seconds). // Note that it is known that miners can manipulate block timestamps // up to a deviation of a few seconds. // This mechanism should not be used for fine grained timing. // The time required to cancel a deposit, in the case the operator does not move the funds // to the off-chain storage. uint256 public constant DEPOSIT_CANCEL_DELAY = 2 days; // The time required to freeze the exchange, in the case the operator does not execute a // requested full withdrawal. uint256 public constant FREEZE_GRACE_PERIOD = 7 days; // The time after which the exchange may be unfrozen after it froze. This should be enough time // for users to perform escape hatches to get back their funds. uint256 public constant UNFREEZE_DELAY = 365 days; // Maximal number of verifiers which may co-exist. uint256 public constant MAX_VERIFIER_COUNT = uint256(64); // The time required to remove a verifier in case of a verifier upgrade. uint256 public constant VERIFIER_REMOVAL_DELAY = FREEZE_GRACE_PERIOD + (21 days); address constant ZERO_ADDRESS = address(0x0); uint256 constant K_MODULUS = 0x800000000000011000000000000000000000000000000000000000000000001; uint256 constant K_BETA = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89; uint256 internal constant MASK_250 = 0x03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint256 internal constant MASK_240 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint256 public constant MAX_FORCED_ACTIONS_REQS_PER_BLOCK = 10; uint256 constant QUANTUM_UPPER_BOUND = 2**128; uint256 internal constant MINTABLE_ASSET_ID_FLAG = 1 << 250; // The 64th bit (indexed 63, counting from 0) is a flag indicating a rollup vault id. uint256 constant ROLLUP_VAULTS_BIT = 63; } /* 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.6.12; /* Interface containing actions a verifier can invoke on the state. The contract containing the state should implement these and verify correctness. */ abstract contract MAcceptModifications { function acceptDeposit( uint256 ownerKey, uint256 vaultId, uint256 assetId, uint256 quantizedAmount ) internal virtual; function allowWithdrawal( uint256 ownerKey, uint256 assetId, uint256 quantizedAmount ) internal virtual; function acceptWithdrawal( uint256 ownerKey, uint256 assetId, uint256 quantizedAmount ) 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.6.12; abstract contract MBlocklist { event BlockPlaced(uint256 indexed ownerKey); event BlockReleased(uint256 indexed ownerKey); event AdminForcedWithdrawal(uint256 indexed ownerKey, address indexed destination); address internal constant BLOCK_ADMIN = 0x520Cf70a2D0B3dfB7386A2Bc9F800321F62a5c3a; // NOLINTNEXTLINE: external-function. function isBlockListed(uint256 ownerKey) public view virtual returns (bool); // NOLINTNEXTLINE: external-function. function readyForClearance(uint256 ownerKey) public view virtual returns (bool); function addToBlockedList(uint256 ownerKey) external virtual; function removeFromBlockedList(uint256 ownerKey) external virtual; /** Reverts if called by a blocked account. */ modifier onlyNotBlocked(uint256 ownerKey) { require(!isBlockListed(ownerKey), "USER_BLOCK_LISTED"); _; } modifier onlyBlockAdmin() { require(msg.sender == BLOCK_ADMIN, "ONLY_BLOCK_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.6.12; abstract contract MDeposits { function depositERC20( // NOLINT external-function. uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 quantizedAmount ) public virtual; function depositEth( // NOLINT external-function. uint256 starkKey, uint256 assetType, uint256 vaultId ) public payable 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.6.12; abstract contract MFreezable { /* Returns true if the exchange is frozen. */ function isFrozen() public view virtual returns (bool); // NOLINT: external-function. /* Forbids calling the function if the exchange is frozen. */ modifier notFrozen() { require(!isFrozen(), "STATE_IS_FROZEN"); _; } function validateFreezeRequest(uint256 requestTime) internal virtual; /* Allows calling the function only if the exchange is frozen. */ modifier onlyFrozen() { require(isFrozen(), "STATE_NOT_FROZEN"); _; } /* Freezes the exchange. */ function freeze() 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.6.12; struct GovernanceInfoStruct { mapping(address => bool) effectiveGovernors; address candidateGovernor; bool initialized; } abstract contract MGovernance { function _isGovernor(address testGovernor) 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.6.12; abstract contract MKeyGetters { // NOLINTNEXTLINE: external-function. function getEthKey(uint256 ownerKey) public view virtual returns (address); function strictGetEthKey(uint256 ownerKey) internal view virtual returns (address); function isMsgSenderKeyOwner(uint256 ownerKey) internal view virtual returns (bool); /* Allows calling the function only if ownerKey is registered to msg.sender. */ modifier onlyKeyOwner(uint256 ownerKey) { // Require the calling user to own the stark key. require(msg.sender == strictGetEthKey(ownerKey), "MISMATCHING_STARK_ETH_KEYS"); _; } } /* 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.6.12; abstract contract MStarkExForcedActionState { function fullWithdrawActionHash(uint256 ownerKey, uint256 vaultId) internal pure virtual returns (bytes32); function clearFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal virtual; // NOLINTNEXTLINE: external-function. function getFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) public view virtual returns (uint256); function setFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) 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.6.12; abstract contract MTokenAssetData { // NOLINTNEXTLINE: external-function. function getAssetInfo(uint256 assetType) public view virtual returns (bytes memory); function isEther(uint256 assetType) internal view virtual returns (bool); function isERC20(uint256 assetType) internal view virtual returns (bool); function isERC721(uint256 assetType) internal view virtual returns (bool); function isERC1155(uint256 assetType) internal view virtual returns (bool); function isFungibleAssetType(uint256 assetType) internal view virtual returns (bool); function isMintableAssetType(uint256 assetType) internal view virtual returns (bool); function isAssetTypeWithTokenId(uint256 assetType) internal view virtual returns (bool); function extractContractAddress(uint256 assetType) internal view virtual returns (address); function verifyAssetInfo(bytes memory assetInfo) internal view virtual; function isNonFungibleAssetInfo(bytes memory assetInfo) internal pure virtual returns (bool); function calculateAssetIdWithTokenId(uint256 assetType, uint256 tokenId) public view virtual returns (uint256); function calculateMintableAssetId(uint256 assetType, bytes memory mintingBlob) public pure virtual returns (uint256); } /* 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.6.12; abstract contract MTokenQuantization { function fromQuantized(uint256 presumedAssetType, uint256 quantizedAmount) internal view virtual returns (uint256 amount); // NOLINTNEXTLINE: external-function. function getQuantum(uint256 presumedAssetType) public view virtual returns (uint256 quantum); function toQuantized(uint256 presumedAssetType, uint256 amount) internal view virtual returns (uint256 quantizedAmount); } /* 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.6.12; abstract contract MTokenTransfers { function transferIn(uint256 assetType, uint256 quantizedAmount) internal virtual; function transferInWithTokenId( uint256 assetType, uint256 tokenId, uint256 quantizedAmount ) internal virtual; function transferOut( address payable recipient, uint256 assetType, uint256 quantizedAmount ) internal virtual; function transferOutWithTokenId( address recipient, uint256 assetType, uint256 tokenId, uint256 quantizedAmount ) internal virtual; function transferOutMint( uint256 assetType, uint256 quantizedAmount, address recipient, bytes calldata mintingBlob ) 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.6.12; import "./Governance.sol"; import "./GovernanceStorage.sol"; /** The StarkEx contract is governed by one or more Governors of which the initial one is the deployer of the contract. A governor has the sole authority to perform the following operations: 1. Nominate additional governors (:sol:func:`mainNominateNewGovernor`) 2. Remove other governors (:sol:func:`mainRemoveGovernor`) 3. Add new :sol:mod:`Verifiers` and :sol:mod:`AvailabilityVerifiers` 4. Remove :sol:mod:`Verifiers` and :sol:mod:`AvailabilityVerifiers` after a timelock allows it 5. Nominate Operators (see :sol:mod:`Operator`) and Token Administrators (see :sol:mod:`TokenRegister`) Adding governors is performed in a two step procedure: 1. First, an existing governor nominates a new governor (:sol:func:`mainNominateNewGovernor`) 2. Then, the new governor must accept governance to become a governor (:sol:func:`mainAcceptGovernance`) This two step procedure ensures that a governor public key cannot be nominated unless there is an entity that has the corresponding private key. This is intended to prevent errors in the addition process. The governor private key should typically be held in a secure cold wallet. */ /* Implements Governance for the StarkDex main contract. The wrapper methods (e.g. mainIsGovernor wrapping _isGovernor) are needed to give the method unique names. Both Proxy and StarkExchange inherit from Governance. Thus, the logical contract method names must have unique names in order for the proxy to successfully delegate to them. */ contract MainGovernance is GovernanceStorage, Governance { // The tag is the sting key that is used in the Governance storage mapping. string public constant MAIN_GOVERNANCE_INFO_TAG = "StarkEx.Main.2019.GovernorsInformation"; /* Returns the GovernanceInfoStruct associated with the governance tag. */ function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) { return governanceInfo[MAIN_GOVERNANCE_INFO_TAG]; } function mainIsGovernor(address testGovernor) external view returns (bool) { return _isGovernor(testGovernor); } function mainNominateNewGovernor(address newGovernor) external { _nominateNewGovernor(newGovernor); } function mainRemoveGovernor(address governorForRemoval) external { _removeGovernor(governorForRemoval); } function mainAcceptGovernance() external { _acceptGovernance(); } function mainCancelNomination() 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.6.12; import "../upgrade/ProxyStorage.sol"; import "../libraries/Common.sol"; /* Holds ALL the main contract state (storage) variables. */ contract MainStorage is ProxyStorage { uint256 internal constant LAYOUT_LENGTH = 2**64; address escapeVerifierAddress; // NOLINT: constable-states. // Global dex-frozen flag. bool stateFrozen; // NOLINT: constable-states. // Time when unFreeze can be successfully called (UNFREEZE_DELAY after freeze). uint256 unFreezeTime; // NOLINT: constable-states. // Pending deposits. // A map STARK key => asset id => vault id => quantized amount. mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) pendingDeposits; // Cancellation requests. // A map STARK key => asset id => vault id => request timestamp. mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) cancellationRequests; // Pending withdrawals. // A map STARK key => asset id => quantized amount. mapping(uint256 => mapping(uint256 => uint256)) pendingWithdrawals; // vault_id => escape used boolean. mapping(uint256 => bool) escapesUsed; // Number of escapes that were performed when frozen. uint256 escapesUsedCount; // NOLINT: constable-states. // NOTE: fullWithdrawalRequests is deprecated, and replaced by forcedActionRequests. // NOLINTNEXTLINE naming-convention. mapping(uint256 => mapping(uint256 => uint256)) fullWithdrawalRequests_DEPRECATED; // State sequence number. uint256 sequenceNumber; // NOLINT: constable-states uninitialized-state. // Validium Vaults Tree Root & Height. uint256 validiumVaultRoot; // NOLINT: constable-states uninitialized-state. uint256 validiumTreeHeight; // NOLINT: constable-states uninitialized-state. // Order Tree Root & Height. uint256 orderRoot; // NOLINT: constable-states uninitialized-state. uint256 orderTreeHeight; // NOLINT: constable-states uninitialized-state. // True if and only if the address is allowed to add tokens. mapping(address => bool) tokenAdmins; // This mapping is no longer in use, remains for backwards compatibility. mapping(address => bool) userAdmins_DEPRECATED; // NOLINT: naming-convention. // True if and only if the address is an operator (allowed to update state). mapping(address => bool) operators; // NOLINT: uninitialized-state. // Mapping of contract ID to asset data. mapping(uint256 => bytes) assetTypeToAssetInfo; // NOLINT: uninitialized-state. // Mapping of registered contract IDs. mapping(uint256 => bool) registeredAssetType; // NOLINT: uninitialized-state. // Mapping from contract ID to quantum. mapping(uint256 => uint256) assetTypeToQuantum; // NOLINT: uninitialized-state. // This mapping is no longer in use, remains for backwards compatibility. mapping(address => uint256) starkKeys_DEPRECATED; // NOLINT: naming-convention. // Mapping from STARK public key to the Ethereum public key of its owner. mapping(uint256 => address) ethKeys; // NOLINT: uninitialized-state. // Timelocked state transition and availability verification chain. StarkExTypes.ApprovalChainData verifiersChain; StarkExTypes.ApprovalChainData availabilityVerifiersChain; // Batch id of last accepted proof. uint256 lastBatchId; // NOLINT: constable-states uninitialized-state. // Mapping between sub-contract index to sub-contract address. mapping(uint256 => address) subContracts; // NOLINT: uninitialized-state. mapping(uint256 => bool) permissiveAssetType_DEPRECATED; // NOLINT: naming-convention. // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX2.0 ---- // Onchain-data version configured for the system. uint256 onchainDataVersion_DEPRECATED; // NOLINT: naming-convention constable-states. // Counter of forced action request in block. The key is the block number. mapping(uint256 => uint256) forcedRequestsInBlock; // ForcedAction requests: actionHash => requestTime. mapping(bytes32 => uint256) forcedActionRequests; // Mapping for timelocked actions. // A actionKey => activation time. mapping(bytes32 => uint256) actionsTimeLock; // Append only list of requested forced action hashes. bytes32[] actionHashList; // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX3.0 ---- // ---- END OF MAIN STORAGE AS DEPLOYED IN STARKEX4.0 ---- // Rollup Vaults Tree Root & Height. uint256 rollupVaultRoot; // NOLINT: constable-states uninitialized-state. uint256 rollupTreeHeight; // NOLINT: constable-states uninitialized-state. uint256 globalConfigCode; // NOLINT: constable-states uninitialized-state. // Mapping of owner keys that are blocked from withdrawals. mapping(uint256 => uint256) internal blockListed; // Reserved storage space for Extensibility. // Every added MUST be added above the end gap, and the __endGap size must be reduced // accordingly. // NOLINTNEXTLINE: naming-convention. uint256[LAYOUT_LENGTH - 41] private __endGap; // __endGap complements layout to LAYOUT_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.6.12; import "../components/GovernanceStorage.sol"; /* Holds the Proxy-specific state variables. This contract is inherited by the GovernanceStorage (and indirectly by MainStorage) to prevent collision hazard. */ contract ProxyStorage is GovernanceStorage { // NOLINTNEXTLINE: naming-convention uninitialized-state. mapping(address => bytes32) internal initializationHash_DEPRECATED; // The time after which we can switch to the implementation. // Hash(implementation, data, finalize) => time. mapping(bytes32 => uint256) internal enabledTime; // A central storage of the flags whether implementation has been initialized. // Note - it can be used flexibly enough to accommodate multiple levels of initialization // (i.e. using different key salting schemes for different initialization levels). mapping(bytes32 => bool) internal initialized; } /* 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.6.12; import "../components/StarkExStorage.sol"; import "../interfaces/MStarkExForcedActionState.sol"; import "../../components/ActionHash.sol"; /* StarkExchange specific action hashses. */ contract StarkExForcedActionState is StarkExStorage, ActionHash, MStarkExForcedActionState { function fullWithdrawActionHash(uint256 ownerKey, uint256 vaultId) internal pure override returns (bytes32) { return getActionHash("FULL_WITHDRAWAL", abi.encode(ownerKey, vaultId)); } /* Implemented in the FullWithdrawal contracts. */ function clearFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal virtual override { // Reset escape request. delete forcedActionRequests[fullWithdrawActionHash(ownerKey, vaultId)]; } function getFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) public view override returns (uint256) { // Return request value. Expect zero if the request doesn't exist or has been serviced, and // a non-zero value otherwise. return forcedActionRequests[fullWithdrawActionHash(ownerKey, vaultId)]; } function setFullWithdrawalRequest(uint256 ownerKey, uint256 vaultId) internal override { // FullWithdrawal is always at premium cost, hence the `true`. setActionHash(fullWithdrawActionHash(ownerKey, vaultId), true); } } /* 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.6.12; import "../../components/MainStorage.sol"; /* Extends MainStorage, holds StarkEx App specific state (storage) variables. ALL State variables that are common to all applications, reside in MainStorage, whereas ALL the StarkEx app specific ones reside here. */ contract StarkExStorage is MainStorage { // Onchain vaults balances. // A map eth_address => asset_id => vault_id => quantized amount. mapping(address => mapping(uint256 => mapping(uint256 => uint256))) vaultsBalances; // Onchain vaults withdrawal lock time. // A map eth_address => asset_id => vault_id => lock expiration timestamp. mapping(address => mapping(uint256 => mapping(uint256 => uint256))) vaultsWithdrawalLocks; // Enforces the minimal balance requirement (as output by Cairo) on onchain vault updates. // When disabled, flash loans are enabled. bool strictVaultBalancePolicy; // NOLINT: constable-states, uninitialized-state. // The default time, in seconds, that an onchain vault is locked for withdrawal after a deposit. uint256 public defaultVaultWithdrawalLock; // NOLINT: constable-states. // Address of the message registry contract that is used to sign and verify L1 orders. address public orderRegistryAddress; // NOLINT: constable-states. // Reserved storage space for Extensibility. // Every added MUST be added above the end gap, and the __endGap size must be reduced // accordingly. // NOLINTNEXTLINE: naming-convention shadowing-abstract. uint256[LAYOUT_LENGTH - 5] private __endGap; // __endGap complements layout to LAYOUT_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.6.12; import "./Identity.sol"; interface SubContractor is Identity { function initialize(bytes calldata data) external; function initializerSize() external view returns (uint256); /* Returns an array with selectors for validation. These selectors are the critical ones for maintaining self custody and anti censorship. During the upgrade process, as part of the sub-contract validation, the MainDispatcher validates that the selectos are mapped to the correct sub-contract. */ function validatedSelectors() external pure returns (bytes4[] 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.6.12; import "../components/MainStorage.sol"; import "../interfaces/MTokenAssetData.sol"; import "../libraries/Common.sol"; import "../libraries/LibConstants.sol"; contract TokenAssetData is MainStorage, LibConstants, MTokenAssetData { bytes4 internal constant ERC20_SELECTOR = bytes4(keccak256("ERC20Token(address)")); bytes4 internal constant ETH_SELECTOR = bytes4(keccak256("ETH()")); bytes4 internal constant ERC721_SELECTOR = bytes4(keccak256("ERC721Token(address,uint256)")); bytes4 internal constant ERC1155_SELECTOR = bytes4(keccak256("ERC1155Token(address,uint256)")); bytes4 internal constant MINTABLE_ERC20_SELECTOR = bytes4(keccak256("MintableERC20Token(address)")); bytes4 internal constant MINTABLE_ERC721_SELECTOR = bytes4(keccak256("MintableERC721Token(address,uint256)")); // The selector follows the 0x20 bytes assetInfo.length field. uint256 internal constant SELECTOR_OFFSET = 0x20; uint256 internal constant SELECTOR_SIZE = 4; uint256 internal constant TOKEN_CONTRACT_ADDRESS_OFFSET = SELECTOR_OFFSET + SELECTOR_SIZE; string internal constant NFT_ASSET_ID_PREFIX = "NFT:"; string internal constant NON_MINTABLE_PREFIX = "NON_MINTABLE:"; string internal constant MINTABLE_PREFIX = "MINTABLE:"; using Addresses for address; /* Extract the tokenSelector from assetInfo. Works like bytes4 tokenSelector = abi.decode(assetInfo, (bytes4)) but does not revert when assetInfo.length < SELECTOR_OFFSET. */ function extractTokenSelectorFromAssetInfo(bytes memory assetInfo) private pure returns (bytes4 selector) { assembly { selector := and( 0xffffffff00000000000000000000000000000000000000000000000000000000, mload(add(assetInfo, SELECTOR_OFFSET)) ) } } function getAssetInfo(uint256 assetType) public view override returns (bytes memory assetInfo) { // Verify that the registration is set and valid. require(registeredAssetType[assetType], "ASSET_TYPE_NOT_REGISTERED"); // Retrieve registration. assetInfo = assetTypeToAssetInfo[assetType]; } function extractTokenSelectorFromAssetType(uint256 assetType) private view returns (bytes4) { return extractTokenSelectorFromAssetInfo(getAssetInfo(assetType)); } function isEther(uint256 assetType) internal view override returns (bool) { return extractTokenSelectorFromAssetType(assetType) == ETH_SELECTOR; } function isERC20(uint256 assetType) internal view override returns (bool) { return extractTokenSelectorFromAssetType(assetType) == ERC20_SELECTOR; } function isERC721(uint256 assetType) internal view override returns (bool) { return extractTokenSelectorFromAssetType(assetType) == ERC721_SELECTOR; } function isERC1155(uint256 assetType) internal view override returns (bool) { return extractTokenSelectorFromAssetType(assetType) == ERC1155_SELECTOR; } function isFungibleAssetType(uint256 assetType) internal view override returns (bool) { bytes4 tokenSelector = extractTokenSelectorFromAssetType(assetType); return tokenSelector == ETH_SELECTOR || tokenSelector == ERC20_SELECTOR || tokenSelector == MINTABLE_ERC20_SELECTOR; } function isMintableAssetType(uint256 assetType) internal view override returns (bool) { bytes4 tokenSelector = extractTokenSelectorFromAssetType(assetType); return tokenSelector == MINTABLE_ERC20_SELECTOR || tokenSelector == MINTABLE_ERC721_SELECTOR; } function isAssetTypeWithTokenId(uint256 assetType) internal view override returns (bool) { bytes4 tokenSelector = extractTokenSelectorFromAssetType(assetType); return tokenSelector == ERC721_SELECTOR || tokenSelector == ERC1155_SELECTOR; } function isTokenSupported(bytes4 tokenSelector) private pure returns (bool) { return tokenSelector == ETH_SELECTOR || tokenSelector == ERC20_SELECTOR || tokenSelector == ERC721_SELECTOR || tokenSelector == MINTABLE_ERC20_SELECTOR || tokenSelector == MINTABLE_ERC721_SELECTOR || tokenSelector == ERC1155_SELECTOR; } function extractContractAddressFromAssetInfo(bytes memory assetInfo) private pure returns (address) { uint256 offset = TOKEN_CONTRACT_ADDRESS_OFFSET; uint256 res; assembly { res := mload(add(assetInfo, offset)) } return address(res); } function extractContractAddress(uint256 assetType) internal view override returns (address) { return extractContractAddressFromAssetInfo(getAssetInfo(assetType)); } function verifyAssetInfo(bytes memory assetInfo) internal view override { bytes4 tokenSelector = extractTokenSelectorFromAssetInfo(assetInfo); // Ensure the selector is of an asset type we know. require(isTokenSupported(tokenSelector), "UNSUPPORTED_TOKEN_TYPE"); if (tokenSelector == ETH_SELECTOR) { // Assset info for ETH assetType is only a selector, i.e. 4 bytes length. require(assetInfo.length == 4, "INVALID_ASSET_STRING"); } else { // Assset info for other asset types are a selector + uint256 concatanation. // We pass the address as a uint256 (zero padded), // thus its length is 0x04 + 0x20 = 0x24. require(assetInfo.length == 0x24, "INVALID_ASSET_STRING"); address tokenAddress = extractContractAddressFromAssetInfo(assetInfo); require(tokenAddress.isContract(), "BAD_TOKEN_ADDRESS"); } } function isNonFungibleAssetInfo(bytes memory assetInfo) internal pure override returns (bool) { bytes4 tokenSelector = extractTokenSelectorFromAssetInfo(assetInfo); return tokenSelector == ERC721_SELECTOR || tokenSelector == MINTABLE_ERC721_SELECTOR; } function calculateAssetIdWithTokenId(uint256 assetType, uint256 tokenId) public view override returns (uint256) { require(isAssetTypeWithTokenId(assetType), "ASSET_TYPE_DOES_NOT_TAKE_TOKEN_ID"); string memory prefix = isERC721(assetType) ? NFT_ASSET_ID_PREFIX : NON_MINTABLE_PREFIX; return uint256(keccak256(abi.encodePacked(prefix, assetType, tokenId))) & MASK_250; } function calculateMintableAssetId(uint256 assetType, bytes memory mintingBlob) public pure override returns (uint256 assetId) { uint256 blobHash = uint256(keccak256(mintingBlob)); assetId = (uint256(keccak256(abi.encodePacked(MINTABLE_PREFIX, assetType, blobHash))) & MASK_240) | MINTABLE_ASSET_ID_FLAG; } } /* 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.6.12; import "../components/MainStorage.sol"; import "../interfaces/MTokenQuantization.sol"; contract TokenQuantization is MainStorage, MTokenQuantization { function fromQuantized(uint256 presumedAssetType, uint256 quantizedAmount) internal view override returns (uint256 amount) { uint256 quantum = getQuantum(presumedAssetType); amount = quantizedAmount * quantum; require(amount / quantum == quantizedAmount, "DEQUANTIZATION_OVERFLOW"); } function getQuantum(uint256 presumedAssetType) public view override returns (uint256 quantum) { if (!registeredAssetType[presumedAssetType]) { // Default quantization, for NFTs etc. quantum = 1; } else { // Retrieve registration. quantum = assetTypeToQuantum[presumedAssetType]; } } function toQuantized(uint256 presumedAssetType, uint256 amount) internal view override returns (uint256 quantizedAmount) { uint256 quantum = getQuantum(presumedAssetType); require(amount % quantum == 0, "INVALID_AMOUNT"); quantizedAmount = amount / quantum; } } /* 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.6.12; import "../libraries/LibConstants.sol"; import "../interfaces/MGovernance.sol"; import "../interfaces/MTokenAssetData.sol"; import "../tokens/ERC20/IERC20.sol"; import "./MainStorage.sol"; /** Registration of a new token (:sol:func:`registerToken`) entails defining a new asset type within the system, and associating it with an `assetInfo` array of bytes and a quantization factor (`quantum`). The `assetInfo` is a byte array, with a size depending on the token. For ETH, assetInfo is 4 bytes long. For ERC20 tokens, it is 36 bytes long. For each token type, the following constant 4-byte hash is defined, called the `selector`: | `ETH_SELECTOR = bytes4(keccak256("ETH()"));` | `ERC20_SELECTOR = bytes4(keccak256("ERC20Token(address)"));` | `ERC721_SELECTOR = bytes4(keccak256("ERC721Token(address,uint256)"));` | `MINTABLE_ERC20_SELECTOR = bytes4(keccak256("MintableERC20Token(address)"));` | `MINTABLE_ERC721_SELECTOR = bytes4(keccak256("MintableERC721Token(address,uint256)"));` For each token type, `assetInfo` is defined as follows: The `quantum` quantization factor defines the multiplicative transformation from the native token denomination as a 256b unsigned integer to a 63b unsigned integer representation as used by the Stark exchange. Only amounts in the native representation that represent an integer number of quanta are allowed in the system. The asset type is restricted to be the result of a hash of the `assetInfo` and the `quantum` masked to 250 bits (to be less than the prime used) according to the following formula: | ``uint256 assetType = uint256(keccak256(abi.encodePacked(assetInfo, quantum))) &`` | ``0x03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;`` Once registered, tokens cannot be removed from the system, as their IDs may be used by off-chain accounts. New tokens may only be registered by a Token Administrator. A Token Administrator may be instantly appointed or removed by the contract Governor (see :sol:mod:`MainGovernance`). Typically, the Token Administrator's private key should be kept in a cold wallet. */ abstract contract TokenRegister is MainStorage, LibConstants, MGovernance, MTokenAssetData { event LogTokenRegistered(uint256 assetType, bytes assetInfo, uint256 quantum); event LogTokenAdminAdded(address tokenAdmin); event LogTokenAdminRemoved(address tokenAdmin); modifier onlyTokensAdmin() { require(isTokenAdmin(msg.sender), "ONLY_TOKENS_ADMIN"); _; } function isTokenAdmin(address testedAdmin) public view returns (bool) { return tokenAdmins[testedAdmin]; } function registerTokenAdmin(address newAdmin) external onlyGovernance { tokenAdmins[newAdmin] = true; emit LogTokenAdminAdded(newAdmin); } function unregisterTokenAdmin(address oldAdmin) external onlyGovernance { tokenAdmins[oldAdmin] = false; emit LogTokenAdminRemoved(oldAdmin); } function isAssetRegistered(uint256 assetType) public view returns (bool) { return registeredAssetType[assetType]; } /* Registers a new asset to the system. Once added, it can not be removed and there is a limited number of slots available. */ function registerToken( uint256 assetType, bytes calldata assetInfo, uint256 quantum ) public virtual onlyTokensAdmin { // Make sure it is not invalid or already registered. require(!isAssetRegistered(assetType), "ASSET_ALREADY_REGISTERED"); require(assetType < K_MODULUS, "INVALID_ASSET_TYPE"); require(quantum > 0, "INVALID_QUANTUM"); require(quantum < QUANTUM_UPPER_BOUND, "INVALID_QUANTUM"); // Require that the assetType is the hash of the assetInfo and quantum truncated to 250 bits. uint256 enforcedId = uint256(keccak256(abi.encodePacked(assetInfo, quantum))) & MASK_250; require(assetType == enforcedId, "INVALID_ASSET_TYPE"); verifyAssetInfo(assetInfo); // NFTs quantum must equal one. if (isNonFungibleAssetInfo(assetInfo)) { require(quantum == 1, "INVALID_NFT_QUANTUM"); } // Add token to the in-storage structures. registeredAssetType[assetType] = true; assetTypeToAssetInfo[assetType] = assetInfo; assetTypeToQuantum[assetType] = quantum; // Log the registration of a new token. emit LogTokenRegistered(assetType, assetInfo, quantum); } function registerToken(uint256 assetType, bytes calldata assetInfo) external virtual { registerToken(assetType, assetInfo, 1); } } /* 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.6.12; import "../libraries/Common.sol"; import "../interfaces/MTokenTransfers.sol"; import "../interfaces/MTokenAssetData.sol"; import "../interfaces/MTokenQuantization.sol"; import "../tokens/ERC1155/IERC1155.sol"; import "../tokens/ERC20/IERC20.sol"; /* Implements various transferIn and transferOut functionalities. */ abstract contract TokenTransfers is MTokenQuantization, MTokenAssetData, MTokenTransfers { using Addresses for address; using Addresses for address payable; /* Transfers funds from msg.sender to the exchange. */ function transferIn(uint256 assetType, uint256 quantizedAmount) internal override { uint256 amount = fromQuantized(assetType, quantizedAmount); if (isERC20(assetType)) { if (quantizedAmount == 0) return; address tokenAddress = extractContractAddress(assetType); IERC20 token = IERC20(tokenAddress); uint256 exchangeBalanceBefore = token.balanceOf(address(this)); bytes memory callData = abi.encodeWithSelector( token.transferFrom.selector, msg.sender, address(this), amount ); tokenAddress.safeTokenContractCall(callData); uint256 exchangeBalanceAfter = token.balanceOf(address(this)); require(exchangeBalanceAfter >= exchangeBalanceBefore, "OVERFLOW"); // NOLINTNEXTLINE(incorrect-equality): strict equality needed. require( exchangeBalanceAfter == exchangeBalanceBefore + amount, "INCORRECT_AMOUNT_TRANSFERRED" ); } else if (isEther(assetType)) { require(msg.value == amount, "INCORRECT_DEPOSIT_AMOUNT"); } else { revert("UNSUPPORTED_TOKEN_TYPE"); } } /* Transfers non fungible and semi fungible tokens from a user to the exchange. */ function transferInWithTokenId( uint256 assetType, uint256 tokenId, uint256 quantizedAmount ) internal override { require(isAssetTypeWithTokenId(assetType), "FUNGIBLE_ASSET_TYPE"); if (isERC721(assetType)) { require(quantizedAmount == 1, "ILLEGAL_NFT_BALANCE"); transferInNft(assetType, tokenId); } else if (quantizedAmount > 0) { transferInSft(assetType, tokenId, quantizedAmount); } } function transferInNft(uint256 assetType, uint256 tokenId) private { require(isERC721(assetType), "NOT_ERC721_TOKEN"); address tokenAddress = extractContractAddress(assetType); tokenAddress.safeTokenContractCall( abi.encodeWithSignature( "safeTransferFrom(address,address,uint256)", msg.sender, address(this), tokenId ) ); } function transferInSft( uint256 assetType, uint256 tokenId, uint256 quantizedAmount ) private { require(isERC1155(assetType), "NOT_ERC1155_TOKEN"); if (quantizedAmount == 0) return; uint256 amount = fromQuantized(assetType, quantizedAmount); address tokenAddress = extractContractAddress(assetType); IERC1155 token = IERC1155(tokenAddress); uint256 exchangeBalanceBefore = token.balanceOf(address(this), tokenId); // Call an ERC1155 token transfer. tokenAddress.safeTokenContractCall( abi.encodeWithSelector( token.safeTransferFrom.selector, msg.sender, address(this), tokenId, amount, bytes("") ) ); uint256 exchangeBalanceAfter = token.balanceOf(address(this), tokenId); require(exchangeBalanceAfter >= exchangeBalanceBefore, "OVERFLOW"); // NOLINTNEXTLINE(incorrect-equality): strict equality needed. require( exchangeBalanceAfter == exchangeBalanceBefore + amount, "INCORRECT_AMOUNT_TRANSFERRED" ); } /* Transfers funds from the exchange to recipient. */ function transferOut( address payable recipient, uint256 assetType, uint256 quantizedAmount ) internal override { // Make sure we don't accidentally burn funds. require(recipient != address(0x0), "INVALID_RECIPIENT"); uint256 amount = fromQuantized(assetType, quantizedAmount); if (isERC20(assetType)) { if (quantizedAmount == 0) return; address tokenAddress = extractContractAddress(assetType); IERC20 token = IERC20(tokenAddress); uint256 exchangeBalanceBefore = token.balanceOf(address(this)); bytes memory callData = abi.encodeWithSelector( token.transfer.selector, recipient, amount ); tokenAddress.safeTokenContractCall(callData); uint256 exchangeBalanceAfter = token.balanceOf(address(this)); require(exchangeBalanceAfter <= exchangeBalanceBefore, "UNDERFLOW"); // NOLINTNEXTLINE(incorrect-equality): strict equality needed. require( exchangeBalanceAfter == exchangeBalanceBefore - amount, "INCORRECT_AMOUNT_TRANSFERRED" ); } else if (isEther(assetType)) { if (quantizedAmount == 0) return; recipient.performEthTransfer(amount); } else { revert("UNSUPPORTED_TOKEN_TYPE"); } } /* Transfers non fungible and semi fungible tokens from the exchange to recipient. */ function transferOutWithTokenId( address recipient, uint256 assetType, uint256 tokenId, uint256 quantizedAmount ) internal override { require(isAssetTypeWithTokenId(assetType), "FUNGIBLE_ASSET_TYPE"); if (isERC721(assetType)) { require(quantizedAmount == 1, "ILLEGAL_NFT_BALANCE"); transferOutNft(recipient, assetType, tokenId); } else if (quantizedAmount > 0) { transferOutSft(recipient, assetType, tokenId, quantizedAmount); } } /* Transfers NFT from the exchange to recipient. */ function transferOutNft( address recipient, uint256 assetType, uint256 tokenId ) private { // Make sure we don't accidentally burn funds. require(recipient != address(0x0), "INVALID_RECIPIENT"); require(isERC721(assetType), "NOT_ERC721_TOKEN"); address tokenAddress = extractContractAddress(assetType); tokenAddress.safeTokenContractCall( abi.encodeWithSignature( "safeTransferFrom(address,address,uint256)", address(this), recipient, tokenId ) ); } /* Transfers Semi Fungible Tokens from the exchange to recipient. */ function transferOutSft( address recipient, uint256 assetType, uint256 tokenId, uint256 quantizedAmount ) private { // Make sure we don't accidentally burn funds. require(recipient != address(0x0), "INVALID_RECIPIENT"); require(isERC1155(assetType), "NOT_ERC1155_TOKEN"); if (quantizedAmount == 0) return; uint256 amount = fromQuantized(assetType, quantizedAmount); address tokenAddress = extractContractAddress(assetType); IERC1155 token = IERC1155(tokenAddress); uint256 exchangeBalanceBefore = token.balanceOf(address(this), tokenId); // Call an ERC1155 token transfer. tokenAddress.safeTokenContractCall( abi.encodeWithSelector( token.safeTransferFrom.selector, address(this), recipient, tokenId, amount, bytes("") ) ); uint256 exchangeBalanceAfter = token.balanceOf(address(this), tokenId); require(exchangeBalanceAfter <= exchangeBalanceBefore, "UNDERFLOW"); // NOLINTNEXTLINE(incorrect-equality): strict equality needed. require( exchangeBalanceAfter == exchangeBalanceBefore - amount, "INCORRECT_AMOUNT_TRANSFERRED" ); } function transferOutMint( uint256 assetType, uint256 quantizedAmount, address recipient, bytes calldata mintingBlob ) internal override { // Make sure we don't accidentally burn funds. require(recipient != address(0x0), "INVALID_RECIPIENT"); require(isMintableAssetType(assetType), "NON_MINTABLE_ASSET_TYPE"); require(quantizedAmount > 0, "INVALID_MINT_AMOUNT"); uint256 amount = fromQuantized(assetType, quantizedAmount); address tokenAddress = extractContractAddress(assetType); tokenAddress.safeTokenContractCall( abi.encodeWithSignature( "mintFor(address,uint256,bytes)", recipient, amount, mintingBlob ) ); } } /* 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.6.12; import "../interactions/StarkExForcedActionState.sol"; import "../../components/ERC721Receiver.sol"; import "../../components/ERC1155Receiver.sol"; import "../../components/Freezable.sol"; import "../../components/KeyGetters.sol"; import "../../components/TokenRegister.sol"; import "../../components/TokenTransfers.sol"; import "../../components/MainGovernance.sol"; import "../../interactions/AcceptModifications.sol"; import "../../interactions/Blocklist.sol"; import "../../interactions/Deposits.sol"; import "../../interactions/TokenAssetData.sol"; import "../../interactions/TokenQuantization.sol"; import "../../interactions/Withdrawals.sol"; import "../../interfaces/SubContractor.sol"; contract TokensAndRamping is ERC1155Receiver, ERC721Receiver, SubContractor, Freezable, MainGovernance, AcceptModifications, StarkExForcedActionState, TokenAssetData, TokenQuantization, TokenRegister, TokenTransfers, KeyGetters, Deposits, Withdrawals, Blocklist { function initialize( bytes calldata /* data */ ) external override { revert("NOT_IMPLEMENTED"); } function initializerSize() external view override returns (uint256) { return 0; } function validatedSelectors() external pure override returns (bytes4[] memory selectors) { uint256 len_ = 8; uint256 index_ = 0; selectors = new bytes4[](len_); selectors[index_++] = Deposits.depositCancel.selector; selectors[index_++] = Deposits.depositWithTokenIdReclaim.selector; selectors[index_++] = Deposits.depositReclaim.selector; selectors[index_++] = Withdrawals.withdraw.selector; selectors[index_++] = Withdrawals.withdrawAndMint.selector; selectors[index_++] = Withdrawals.withdrawWithTokenId.selector; selectors[index_++] = Withdrawals.adminForcedWithdraw.selector; selectors[index_++] = Blocklist.addToBlockedList.selector; require(index_ == len_, "INCORRECT_SELECTORS_ARRAY_LENGTH"); } function identify() external pure override returns (string memory) { return "StarkWare_TokensAndRamping_2024_4"; } } /* 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.6.12; import "../interfaces/MAcceptModifications.sol"; import "../interfaces/MBlocklist.sol"; import "../interfaces/MTokenQuantization.sol"; import "../interfaces/MTokenAssetData.sol"; import "../interfaces/MFreezable.sol"; import "../interfaces/MKeyGetters.sol"; import "../interfaces/MTokenTransfers.sol"; import "../components/MainStorage.sol"; /** For a user to perform a withdrawal operation from the Stark Exchange during normal operation two calls are required: 1. A call to an offchain exchange API, requesting a withdrawal from a user account (vault). 2. A call to the on-chain :sol:func:`withdraw` function to perform the actual withdrawal of funds transferring them to the users Eth or ERC20 account (depending on the token type). For simplicity, hereafter it is assumed that all tokens are ERC20 tokens but the text below applies to Eth in the same manner. In the first call mentioned above, anyone can call the API to request the withdrawal of an amount from a given vault. Following the request, the exchange may include the withdrawal in a STARK proof. The submission of a proof then results in the addition of the amount(s) withdrawn to an on-chain pending withdrawals account under the stark key of the vault owner and the appropriate asset ID. At the same time, this also implies that this amount is deducted from the off-chain vault. Once the amount to be withdrawn has been transfered to the on-chain pending withdrawals account, the user may perform the second call mentioned above to complete the transfer of funds from the Stark Exchange contract to the appropriate ERC20 account. Only a user holding the Eth key corresponding to the Stark Key of a pending withdrawals account may perform this operation. It is possible that for multiple withdrawal calls to the API, a single withdrawal call to the contract may retrieve all funds, as long as they are all for the same asset ID. The result of the operation, assuming all requirements are met, is that an amount of ERC20 tokens in the pending withdrawal account times the quantization factor is transferred to the ERC20 account of the user. A withdrawal request cannot be cancelled. Once funds reach the pending withdrawals account on-chain, they cannot be moved back into an off-chain vault before completion of the withdrawal to the ERC20 account of the user. In the event that the exchange reaches a frozen state the user may perform a withdrawal operation via an alternative flow, known as the "Escape" flow. In this flow, the API call above is replaced with an :sol:func:`escape` call to the on-chain contract (see :sol:mod:`Escapes`) proving the ownership of off-chain funds. If such proof is accepted, the user may proceed as above with the :sol:func:`withdraw` call to the contract to complete the operation. */ abstract contract Withdrawals is MainStorage, MAcceptModifications, MTokenQuantization, MTokenAssetData, MFreezable, MKeyGetters, MTokenTransfers, MBlocklist { event LogWithdrawalPerformed( uint256 ownerKey, uint256 assetType, uint256 nonQuantizedAmount, uint256 quantizedAmount, address recipient ); event LogNftWithdrawalPerformed( uint256 ownerKey, uint256 assetType, uint256 tokenId, uint256 assetId, address recipient ); event LogWithdrawalWithTokenIdPerformed( uint256 ownerKey, uint256 assetType, uint256 tokenId, uint256 assetId, uint256 nonQuantizedAmount, uint256 quantizedAmount, address recipient ); event LogMintWithdrawalPerformed( uint256 ownerKey, uint256 assetType, uint256 nonQuantizedAmount, uint256 quantizedAmount, uint256 assetId ); function getWithdrawalBalance(uint256 ownerKey, uint256 assetId) external view returns (uint256) { uint256 presumedAssetType = assetId; return fromQuantized(presumedAssetType, pendingWithdrawals[ownerKey][assetId]); } /* Moves funds from the pending withdrawal account to the owner address. Note: this function can be called by anyone. Can be called normally while frozen. */ function withdraw(uint256 ownerKey, uint256 assetType) external onlyNotBlocked(ownerKey) { address payable recipient = payable(strictGetEthKey(ownerKey)); _withdraw(ownerKey, assetType, recipient); } function adminForcedWithdraw( uint256 ownerKey, uint256 assetType, address payable destination ) external onlyBlockAdmin { require(readyForClearance(ownerKey), "CANNOT_ADMIN_FORCE_WITHDRAW"); emit AdminForcedWithdrawal(ownerKey, destination); _withdraw(ownerKey, assetType, destination); } function _withdraw( uint256 ownerKey, uint256 assetType, address payable recipient ) private { // address payable recipient = payable(strictGetEthKey(ownerKey)); require(!isMintableAssetType(assetType), "MINTABLE_ASSET_TYPE"); require(isFungibleAssetType(assetType), "NON_FUNGIBLE_ASSET_TYPE"); uint256 assetId = assetType; // Fetch and clear quantized amount. uint256 quantizedAmount = pendingWithdrawals[ownerKey][assetId]; pendingWithdrawals[ownerKey][assetId] = 0; // Transfer funds. transferOut(recipient, assetType, quantizedAmount); emit LogWithdrawalPerformed( ownerKey, assetType, fromQuantized(assetType, quantizedAmount), quantizedAmount, recipient ); } /* Allows withdrawal of tokens to their owner's account. Note: this function can be called by anyone. This function can be called normally while frozen. */ function withdrawWithTokenId( uint256 ownerKey, uint256 assetType, uint256 tokenId // No notFrozen modifier: This function can always be used, even when frozen. ) public onlyNotBlocked(ownerKey) { address recipient = strictGetEthKey(ownerKey); _withdrawWithTokenId(ownerKey, assetType, tokenId, recipient); } function adminForcedWithdrawWithTokenId( uint256 ownerKey, uint256 assetType, uint256 tokenId, address destination ) external onlyBlockAdmin { require(readyForClearance(ownerKey), "CANNOT_ADMIN_FORCE_WITHDRAW"); emit AdminForcedWithdrawal(ownerKey, destination); _withdrawWithTokenId(ownerKey, assetType, tokenId, destination); } function _withdrawWithTokenId( uint256 ownerKey, uint256 assetType, uint256 tokenId, address recipient ) private { require(isAssetTypeWithTokenId(assetType), "INVALID_ASSET_TYPE"); uint256 assetId = calculateAssetIdWithTokenId(assetType, tokenId); uint256 quantizedAmount = pendingWithdrawals[ownerKey][assetId]; pendingWithdrawals[ownerKey][assetId] = 0; // Transfer funds. transferOutWithTokenId(recipient, assetType, tokenId, quantizedAmount); if (isERC721(assetType)) { emit LogNftWithdrawalPerformed(ownerKey, assetType, tokenId, assetId, recipient); } emit LogWithdrawalWithTokenIdPerformed( ownerKey, assetType, tokenId, assetId, fromQuantized(assetType, quantizedAmount), quantizedAmount, recipient ); } /* Allows withdrawal of an NFT to its owner's account. Note: this function can be called by anyone. This function can be called normally while frozen. */ function withdrawNft( uint256 ownerKey, uint256 assetType, uint256 tokenId // No notFrozen modifier: This function can always be used, even when frozen. ) external { withdrawWithTokenId(ownerKey, assetType, tokenId); } function withdrawAndMint( uint256 ownerKey, uint256 assetType, bytes calldata mintingBlob ) external onlyNotBlocked(ownerKey) { address recipient = strictGetEthKey(ownerKey); _withdrawAndMint(ownerKey, assetType, mintingBlob, recipient); } function adminForcedWithdrawAndMint( uint256 ownerKey, uint256 assetType, bytes calldata mintingBlob, address destination ) external onlyBlockAdmin { require(readyForClearance(ownerKey), "CANNOT_ADMIN_FORCE_WITHDRAW"); emit AdminForcedWithdrawal(ownerKey, destination); _withdrawAndMint(ownerKey, assetType, mintingBlob, destination); } function _withdrawAndMint( uint256 ownerKey, uint256 assetType, bytes calldata mintingBlob, address recipient ) private { require(registeredAssetType[assetType], "INVALID_ASSET_TYPE"); require(isMintableAssetType(assetType), "NON_MINTABLE_ASSET_TYPE"); uint256 assetId = calculateMintableAssetId(assetType, mintingBlob); require(pendingWithdrawals[ownerKey][assetId] > 0, "NO_PENDING_WITHDRAWAL_BALANCE"); uint256 quantizedAmount = pendingWithdrawals[ownerKey][assetId]; pendingWithdrawals[ownerKey][assetId] = 0; // Transfer funds. transferOutMint(assetType, quantizedAmount, recipient, mintingBlob); emit LogMintWithdrawalPerformed( ownerKey, assetType, fromQuantized(assetType, quantizedAmount), quantizedAmount, assetId ); } }
File 5 of 8: AppProxyUpgradeable
// File: contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { uint256 forwardGasThreshold = FWD_GAS_LIMIT; bytes32 isDepositablePosition = DEPOSITABLE_POSITION; // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity: // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20 assembly { // Continue only if the gas left is lower than the threshold for forwarding to the implementation code, // otherwise continue outside of the assembly block. if lt(gas, forwardGasThreshold) { // Only accept the deposit and emit an event if all of the following are true: // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0 if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) { // Equivalent Solidity code for emitting the event: // emit ProxyDeposit(msg.sender, msg.value); let logData := mload(0x40) // free memory pointer mstore(logData, caller) // add 'msg.sender' to the log data (first event param) mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param) // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1 log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1) stop() // Stop. Exits execution context } // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender) revert(0, 0) } } address target = implementation(); delegatedFwd(target, msg.data); } } // File: contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } }
File 6 of 8: KernelProxy
/** *Submitted for verification at Etherscan.io on 2020-02-06 */ // File: contracts/acl/IACL.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: contracts/kernel/IKernel.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: contracts/kernel/KernelConstants.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: contracts/common/IsContract.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: contracts/common/TimeHelpers.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: contracts/common/Initializable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: contracts/common/Petrifiable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } /** * @dev Static call into ERC20.totalSupply(). * Reverts if the call fails for some reason (should never fail). */ function staticTotalSupply(ERC20 _token) internal view returns (uint256) { bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector); (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return totalSupply; } } // File: contracts/common/VaultRecoverable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: contracts/apps/AppStorage.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { uint256 forwardGasThreshold = FWD_GAS_LIMIT; bytes32 isDepositablePosition = DEPOSITABLE_POSITION; // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity: // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20 assembly { // Continue only if the gas left is lower than the threshold for forwarding to the implementation code, // otherwise continue outside of the assembly block. if lt(gas, forwardGasThreshold) { // Only accept the deposit and emit an event if all of the following are true: // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0 if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) { // Equivalent Solidity code for emitting the event: // emit ProxyDeposit(msg.sender, msg.value); let logData := mload(0x40) // free memory pointer mstore(logData, caller) // add 'msg.sender' to the log data (first event param) mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param) // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1 log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1) stop() // Stop. Exits execution context } // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender) revert(0, 0) } } address target = implementation(); delegatedFwd(target, msg.data); } } // File: contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: contracts/common/Autopetrified.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: contracts/apps/AragonApp.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: contracts/acl/IACLOracle.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); bool ok; assembly { // send all available gas; if the oracle eats up all the gas, we will eventually revert // note that we are currently guaranteed to still have some gas after the call from // EIP-150's 63/64 gas forward rule ok := staticcall(gas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } }
File 7 of 8: Kernel
// File: contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } /** * @dev Static call into ERC20.totalSupply(). * Reverts if the call fails for some reason (should never fail). */ function staticTotalSupply(ERC20 _token) internal view returns (uint256) { bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector); (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return totalSupply; } } // File: contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { uint256 forwardGasThreshold = FWD_GAS_LIMIT; bytes32 isDepositablePosition = DEPOSITABLE_POSITION; // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity: // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20 assembly { // Continue only if the gas left is lower than the threshold for forwarding to the implementation code, // otherwise continue outside of the assembly block. if lt(gas, forwardGasThreshold) { // Only accept the deposit and emit an event if all of the following are true: // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0 if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) { // Equivalent Solidity code for emitting the event: // emit ProxyDeposit(msg.sender, msg.value); let logData := mload(0x40) // free memory pointer mstore(logData, caller) // add 'msg.sender' to the log data (first event param) mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param) // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1 log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1) stop() // Stop. Exits execution context } // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender) revert(0, 0) } } address target = implementation(); delegatedFwd(target, msg.data); } } // File: contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } }
File 8 of 8: TokenManager
// File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } }