zellic-audit
Initial commit
f998fcd
raw
history blame
67 kB
{
"language": "Solidity",
"sources": {
"AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"IAccessControl.sol\";\nimport \"Context.sol\";\nimport \"Strings.sol\";\nimport \"ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(uint160(account), 20),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n"
},
"Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"CommonConstants.sol": {
"content": "/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.8.16;\n\n// The locked tokens from the grant are released gradually over 4 years.\nuint256 constant GRANT_LOCKUP_PERIOD = 1461 days; // 4 years.\nuint256 constant DEFAULT_DURATION_GLOBAL_TIMELOCK = 365 days; // 1 years.\nuint256 constant MAX_DURATION_GLOBAL_TIMELOCK = 731 days; // 2 years.\nuint256 constant MIN_UNLOCK_DELAY = 7 days; // 1 week.\nbytes32 constant LOCKED_GRANT_ADMIN_ROLE = keccak256(\"LOCKED_GRANT_ADMIN_ROLE\");\nbytes32 constant GLOBAL_TIMELOCK_ADMIN_ROLE = keccak256(\"GLOBAL_TIMELOCK_ADMIN_ROLE\");\n\n// This hash value is used as an ID for `DelegateRegistry`\n// If the recipient delegates this ID to an agent address,\n// that agent can trigger token release.\nbytes32 constant LOCKED_TOKEN_RELEASE_AGENT = keccak256(\"STARKNET_LOCKED_TOKEN_RELEASE_AGENT\");\n\n// This hash value is used as an ID for `DelegateRegistry`\n// If the recipient delegates this ID to an agent address,\n// that agent can submit delegation related transactions.\nbytes32 constant LOCKED_TOKEN_DELEGATION_AGENT = keccak256(\n \"STARKNET_LOCKED_TOKEN_DELEGATION_AGENT\"\n);\n\n// The start time of a LockedGrant (T), at the time of granting (t) must be in the time window\n// (t - LOCKED_GRANT_MAX_START_PAST_OFFSET, t + LOCKED_GRANT_MAX_START_FUTURE_OFFSET)\n// i.e. t - LOCKED_GRANT_MAX_START_PAST_OFFSET < T < t + LOCKED_GRANT_MAX_START_FUTURE_OFFSET.\nuint256 constant LOCKED_GRANT_MAX_START_PAST_OFFSET = 182 days; // 6 months.\nuint256 constant LOCKED_GRANT_MAX_START_FUTURE_OFFSET = 31 days; // 1 month.\n"
},
"Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"DelegationSupport.sol": {
"content": "/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.8.16;\n\nimport \"CommonConstants.sol\";\nimport \"IVotes.sol\";\n\n/**\n A subset of the Gnosis DelegateRegistry ABI.\n*/\ninterface IDelegateRegistry {\n function setDelegate(bytes32 id, address delegate) external;\n\n function delegation(address delegator, bytes32 id) external view returns (address);\n\n function clearDelegate(bytes32 id) external;\n}\n\n/**\n This contract implements the delegations made on behalf of the token grant contract.\n Two types of delegation are supported:\n 1. Delegation using Gnosis DelegateRegistry.\n 2. IVotes (Compound like) delegation, done directly on the ERC20 token.\n\n Upon construction, the {LockedTokenGrant} is provided with an address of the\n Gnosis DelegateRegistry. In addition, if a different DelegateRegistry is used,\n it can be passed in explicitly as an argument.\n\n Compound like vote delegation can be done on the StarkNet token, and on the Staking contract,\n assuming it will support that.\n*/\nabstract contract DelegationSupport {\n address public immutable recipient;\n\n // A Gnosis DelegateRegistry contract, provided by the common contract.\n // Used for delegation of votes, and also to permit token release and delegation actions.\n IDelegateRegistry public immutable defaultRegistry;\n\n // StarkNet Token.\n address public immutable token;\n\n // StarkNet Token Staking contract.\n address public immutable stakingContract;\n\n modifier onlyRecipient() {\n require(msg.sender == recipient, \"ONLY_RECIPIENT\");\n _;\n }\n\n modifier onlyAllowedAgent(bytes32 agentId) {\n require(\n msg.sender == recipient || msg.sender == defaultRegistry.delegation(recipient, agentId),\n \"ONLY_RECIPIENT_OR_APPROVED_AGENT\"\n );\n _;\n }\n\n constructor(\n address defaultRegistry_,\n address recipient_,\n address token_,\n address stakingContract_\n ) {\n defaultRegistry = IDelegateRegistry(defaultRegistry_);\n recipient = recipient_;\n token = token_;\n stakingContract = stakingContract_;\n }\n\n /*\n Clears the {LockedTokenGrant} Gnosis delegation on the provided DelegateRegistry,\n for the ID provided.\n The call is restricted to the recipient or to the appointed delegation agent.\n */\n function clearDelegate(bytes32 id, IDelegateRegistry registry)\n public\n onlyAllowedAgent(LOCKED_TOKEN_DELEGATION_AGENT)\n {\n registry.clearDelegate(id);\n }\n\n /*\n Sets the {LockedTokenGrant} Gnosis delegation on the provided DelegateRegistry,\n for the ID provided.\n The call is restricted to the recipient or to the appointed delegation agent.\n */\n function setDelegate(\n bytes32 id,\n address delegate,\n IDelegateRegistry registry\n ) public onlyAllowedAgent(LOCKED_TOKEN_DELEGATION_AGENT) {\n registry.setDelegate(id, delegate);\n }\n\n /*\n Clears the {LockedTokenGrant} Gnosis delegation on the default DelegateRegistry,\n for the ID provided.\n The call is restricted to the recipient or to the appointed delegation agent.\n */\n function clearDelegate(bytes32 id) external {\n clearDelegate(id, defaultRegistry);\n }\n\n /*\n Sets the {LockedTokenGrant} Gnosis delegation on the default DelegateRegistry,\n for the ID provided.\n The call is restricted to the recipient or to the appointed delegation agent.\n */\n function setDelegate(bytes32 id, address delegate) external {\n setDelegate(id, delegate, defaultRegistry);\n }\n\n /*\n Sets the {LockedTokenGrant} IVotes delegation on the token.\n The call is restricted to the recipient or to the appointed delegation agent.\n */\n function setDelegateOnToken(address delegatee)\n external\n onlyAllowedAgent(LOCKED_TOKEN_DELEGATION_AGENT)\n {\n _setIVotesDelegation(token, delegatee);\n }\n\n /*\n Sets the {LockedTokenGrant} IVotes delegation on the staking contract.\n The call is restricted to the recipient or to the appointed delegation agent.\n */\n function setDelegateOnStaking(address delegatee)\n external\n onlyAllowedAgent(LOCKED_TOKEN_DELEGATION_AGENT)\n {\n _setIVotesDelegation(stakingContract, delegatee);\n }\n\n function _setIVotesDelegation(address target, address delegatee) private {\n IVotes(target).delegate(delegatee);\n }\n}\n"
},
"ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"GlobalUnlock.sol": {
"content": "/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.8.16;\n\nimport \"CommonConstants.sol\";\nimport \"AccessControl.sol\";\n\n/**\n This contract handles the StarkNet Token global timelock.\n The Global Timelock is applied on all the locked token grants.\n Before the global timelock expires, all the locked token grants, are 100% locked,\n regardless of grant size and elapsed time since grant start time.\n Once the timelock expires, the amount of locked tokens in the grant is determined by the size\n of the grant and its start time.\n\n The global time-lock can be changed by an admin. To perform that,\n the admin must hold the GLOBAL_TIMELOCK_ADMIN_ROLE rights on the `LockedTokenCommon` contract.\n The global time-lock can be reset to a new timestamp as long as the following conditions are met:\n i. The new timestamp is in the future with at least a minimal margin.\n ii. The new timestamp does not exceed the global time-lock upper bound.\n iii. The global time-lock has not expired yet.\n\n The deployed LockedTokenGrant contracts query this contract to read the global timelock.\n*/\nabstract contract GlobalUnlock is AccessControl {\n uint256 internal immutable UPPER_LIMIT_GLOBAL_TIME_LOCK;\n uint256 public globalUnlockTime;\n\n event GlobalUnlockTimeUpdate(\n uint256 oldUnlockTime,\n uint256 newUnlockTime,\n address indexed sender\n );\n\n constructor() {\n UPPER_LIMIT_GLOBAL_TIME_LOCK = block.timestamp + MAX_DURATION_GLOBAL_TIMELOCK;\n _updateGlobalLock(block.timestamp + DEFAULT_DURATION_GLOBAL_TIMELOCK);\n }\n\n function updateGlobalLock(uint256 unlockTime) external onlyRole(GLOBAL_TIMELOCK_ADMIN_ROLE) {\n require(unlockTime > block.timestamp + MIN_UNLOCK_DELAY, \"SELECTED_TIME_TOO_EARLY\");\n require(unlockTime < UPPER_LIMIT_GLOBAL_TIME_LOCK, \"SELECTED_TIME_EXCEED_LIMIT\");\n\n require(block.timestamp < globalUnlockTime, \"GLOBAL_LOCK_ALREADY_EXPIRED\");\n _updateGlobalLock(unlockTime);\n }\n\n /*\n Setter for the globalUnlockTime.\n See caller function code for update logic, validation and restrictions.\n */\n function _updateGlobalLock(uint256 newUnlockTime) internal {\n emit GlobalUnlockTimeUpdate(globalUnlockTime, newUnlockTime, msg.sender);\n globalUnlockTime = newUnlockTime;\n }\n}\n"
},
"IAccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n"
},
"IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"IVotes.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)\npragma solidity ^0.8.0;\n\n/**\n * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.\n *\n * _Available since v4.5._\n */\ninterface IVotes {\n /**\n * @dev Emitted when an account changes their delegate.\n */\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n\n /**\n * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.\n */\n event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);\n\n /**\n * @dev Returns the current amount of votes that `account` has.\n */\n function getVotes(address account) external view returns (uint256);\n\n /**\n * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).\n */\n function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);\n\n /**\n * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).\n *\n * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.\n * Votes that have not been delegated are still part of total supply, even though they would not participate in a\n * vote.\n */\n function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);\n\n /**\n * @dev Returns the delegate that `account` has chosen.\n */\n function delegates(address account) external view returns (address);\n\n /**\n * @dev Delegates votes from the sender to `delegatee`.\n */\n function delegate(address delegatee) external;\n\n /**\n * @dev Delegates votes from signer to `delegatee`.\n */\n function delegateBySig(\n address delegatee,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n}\n"
},
"LockedTokenCommon.sol": {
"content": "/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.8.16;\n\nimport \"GlobalUnlock.sol\";\nimport \"LockedTokenGrant.sol\";\nimport \"Address.sol\";\n\n/**\n The {LockedTokenCommon} contract serves two purposes:\n 1. Maintain the StarkNetToken global timelock (see {GlobalUnlock})\n 2. Allocate locked token grants in {LockedTokenGrant} contracts.\n\n Roles:\n =====\n 1. At initializtion time, the msg.sender of the initialize tx, is defined as DEFAULT_ADMIN_ROLE.\n 2. LOCKED_GRANT_ADMIN_ROLE is required to call `grantLockedTokens`.\n 3. GLOBAL_TIMELOCK_ADMIN_ROLE is reqiured to call the `updateGlobalLock`.\n Two special roles must be granted\n\n Grant Locked Tokens:\n ===================\n Locked token grants are granted using the `grantLockedTokens` here.\n The arguments passed are:\n - recipient - The address of the tokens \"owner\". When the tokens get unlocked, they can be released\n to the recipient address, and only there.\n - amount - The number of tokens to be transfered onto the grant contract upon creation.\n - startTime - The timestamp of the beginning of the 4 years unlock period over which the tokens\n gradually unlock. The startTime can be anytime within the margins specified in the {CommonConstants}.\n - allocationPool - The {LockedTokenCommon} doesn't hold liquidity from which it can grant the tokens,\n but rather uses an external LP for that. The `allocationPool` is the address of the LP\n from which the tokens shall be allocated. The {LockedTokenCommon} must have sufficient allowance\n on the `allocationPool` so it can transfer funds from it onto the creatred grant contract.\n\n Flow: The {LockedTokenCommon} deploys the contract of the new {LockedTokenGrant},\n transfer the grant amount from the allocationPool onto the new grant,\n and register the new grant in a mapping.\n*/\ncontract LockedTokenCommon is GlobalUnlock {\n // Maps recipient to its locked grant contract.\n mapping(address => address) public grantByRecipient;\n IERC20 internal immutable tokenContract;\n address internal immutable stakingContract;\n address internal immutable defaultRegistry;\n\n event LockedTokenGranted(\n address indexed recipient,\n address indexed grantContract,\n uint256 grantAmount,\n uint256 startTime\n );\n\n constructor(\n address tokenAddress_,\n address stakingContract_,\n address defaultRegistry_\n ) {\n require(Address.isContract(tokenAddress_), \"NOT_A_CONTRACT\");\n require(Address.isContract(stakingContract_), \"NOT_A_CONTRACT\");\n require(Address.isContract(defaultRegistry_), \"NOT_A_CONTRACT\");\n _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());\n tokenContract = IERC20(tokenAddress_);\n stakingContract = stakingContract_;\n defaultRegistry = defaultRegistry_;\n }\n\n /**\n Deploys a LockedTokenGrant and transfers `grantAmount` tokens onto it.\n Returns the address of the LockedTokenGrant contract.\n\n Tokens owned by the {LockedTokenGrant} are initially locked, and can only be used for staking.\n The tokens gradually unlocked and can be transferred to the `recipient`.\n */\n function grantLockedTokens(\n address recipient,\n uint256 grantAmount,\n uint256 startTime,\n address allocationPool\n ) external onlyRole(LOCKED_GRANT_ADMIN_ROLE) returns (address) {\n require(grantByRecipient[recipient] == address(0x0), \"ALREADY_GRANTED\");\n require(\n startTime < block.timestamp + LOCKED_GRANT_MAX_START_FUTURE_OFFSET,\n \"START_TIME_TOO_LATE\"\n );\n require(\n startTime > block.timestamp - LOCKED_GRANT_MAX_START_PAST_OFFSET,\n \"START_TIME_TOO_EARLY\"\n );\n\n address grantAddress = address(\n new LockedTokenGrant(\n address(tokenContract),\n stakingContract,\n defaultRegistry,\n recipient,\n grantAmount,\n startTime\n )\n );\n require(\n tokenContract.transferFrom(allocationPool, grantAddress, grantAmount),\n \"TRANSFER_FROM_FAILED\"\n );\n grantByRecipient[recipient] = grantAddress;\n emit LockedTokenGranted(recipient, grantAddress, grantAmount, startTime);\n return grantAddress;\n }\n}\n"
},
"LockedTokenGrant.sol": {
"content": "/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.8.16;\n\nimport \"TimeLockedTokens.sol\";\nimport \"CommonConstants.sol\";\nimport \"DelegationSupport.sol\";\nimport \"IERC20.sol\";\nimport \"Math.sol\";\n\n/**\n This Contract holds a grant of locked tokens and gradually releases the tokens to its recipient.\n\n This contract should be deployed through the {LockedTokenCommon} contract,\n The global lock expiration time may be adjusted through the {LockedTokenCommon} contract.\n\n The {LockedTokenGrant} is initialized with the following parameters:\n `address token_`: The address of StarkNet token ERC20 contract.\n `address stakingContract_`: The address of the contrtact used for staking StarkNet token.\n `address defaultRegistry_`: Address of Gnosis DelegateRegistry.\n `address recipient_`: The owner of the grant.\n `uint256 grantAmount_`: The amount of tokens granted in this grant.\n `uint256 startTime`: The grant time-lock start timestamp.\n\n Token Gradual Release behavior:\n ==============================\n - Until the global timelock expires all the tokens are locked.\n - After the expiration of the global timelock tokens are gradually unlocked.\n - The amount of token unlocked is proportional to the time passed from startTime.\n - The grant is fully unlocked in 4 years.\n - to sum it up:\n ```\n // 0 <= elapsedTime <= 4_YEARS\n elapsedTime = min(4_YEARS, max(0, currentTime - startTime))\n unlocked = globalTimelockExpired ? grantAmount * (elapsedTime / 4_YEARS): 0;\n ```\n - If the total balance of the grant address is larger than `grantAmount` - then the extra\n tokens on top of the grantAmount is available for release ONLY after the grant is fully\n unlocked.\n\n Global Time Lock:\n ================\n StarkNet token has a global timelock. Before that timelock expires, all the tokens in the grant\n are fully locked. The global timelock can be modified post-deployment (to some extent).\n Therefore, the lock is maintained on a different contract that is centralized, and serves\n as a \"timelock oracle\" for all the {LockedTokenGrant} instances. I.e. whenever an instance of this\n contract needs to calculate the available tokens, it checks on the {LockedTokenCommon} contract\n if the global lock expired. See {LockedTokenCommon} for addtional details on the global timelock.\n\n Token Release Operation:\n ======================\n - Tokens are owned by the `recipient`. They cannot be revoked.\n - At any given time the recipient can release any amount of tokens\n as long as the specified amount is available for release.\n - The amount of tokens available for release is the following:\n ```\n availableAmount = min(token.balanceOf(this), (unlocked - alreadyReleased));\n ```\n The `min` is used here, because a part of the grant balance might be staked.\n - Only the recipient or an appointed {LOCKED_TOKEN_RELEASE_AGENT} are allowed to trigger\n release of tokens.\n - The released tokens can be transferred ONLY to the recipient address.\n\n Appointing agents for actions:\n ========================\n Certain activities on this contract can be done not only by the grant recipient, but also by a delegate,\n appointed by the recipient.\n The delegation is done on a Gnosis DelegateRegistry contract, that was given to this contract\n in construction. The address of the {DelegateRegistry} is stored in the public variable named\n `defaultRegistry`.\n 1. The function `releaseTokens` can be called by the account (we use the term agent for this) whose address\n was delegated for this ID:\n 0x07238b05622b6f7e824800927d4f7786fca234153c28aeae2fa6fad5361ef6e7 [= keccak(text=\"LOCKED_TOKEN_RELEASE_AGENT\")]\n 2. The functions `setDelegate` `clearDelegate` `setDelegationOnToken` `setDelegationOnStaking` can be called\n by the agent whose address was delegated for this ID:\n 0x477b64bf0d3f527eb7f7efeb334cf2ba231a93256d546759ad12a5add2734fb1 [= keccak(text=\"LOCKED_TOKEN_DELEGATION_AGENT\")]\n\n Staking:\n =======\n Staking of StarkNet tokens are exempted from the lock. I.e. Tokens from the locked grant\n can be staked, even up to the full grant amount, at any given time.\n However, the exect interface of the staking contract is not finalized yet.\n Therefore, the {LockedTokenGrant} way support staking is by a dedicated approval function `approveForStaking`.\n This function can be called only the recipient, and sets the allowace to the specified amount on the staking contract.\n This function is limited such that it approves only the staking contract, and no other address.\n The staking contract will support staking from a {LockedTokenGrant} using a dedicated API.\n\n Voting Delegation:\n =================\n The {LockedTokenGrant} suports both Compound like delegation and delegation using Gnosis DelegateRegistry.\n These functions set the delegation of the Grant address (the address of the grant contract).\n Only the recipient and a LOCKED_TOKEN_DELEGATION_AGENT (if appointed) can call these functions.\n*/\ncontract LockedTokenGrant is TimeLockedTokens, DelegationSupport {\n uint256 public releasedTokens;\n\n event TokensSentToRecipient(\n address indexed recipient,\n address indexed grantContract,\n uint256 amountSent,\n uint256 aggregateSent\n );\n\n event TokenAllowanceForStaking(\n address indexed grantContract,\n address indexed stakingContract,\n uint256 allowanceSet\n );\n\n constructor(\n address token_,\n address stakingContract_,\n address defaultRegistry_,\n address recipient_,\n uint256 grantAmount_,\n uint256 startTime_\n )\n DelegationSupport(defaultRegistry_, recipient_, address(token_), stakingContract_)\n TimeLockedTokens(grantAmount_, startTime_)\n {}\n\n /*\n Returns the available tokens for release.\n Once the grant lock is fully expired - the entire balance is always available.\n Until then, only the relative part of the grant grantAmount is available.\n However, given staking, the actual balance may be smaller.\n Note that any excessive tokens (beyond grantAmount) transferred to this contract\n are going to be locked until the grant lock fully expires.\n */\n function availableTokens() public view returns (uint256) {\n uint256 currentBalance = IERC20(token).balanceOf(address(this));\n return\n isGrantFullyUnlocked()\n ? currentBalance\n : Math.min(currentBalance, (unlockedTokens() - releasedTokens));\n }\n\n /*\n Transfers `requestedAmount` tokens (if available) to the `recipient`.\n */\n function releaseTokens(uint256 requestedAmount)\n external\n onlyAllowedAgent(LOCKED_TOKEN_RELEASE_AGENT)\n {\n require(requestedAmount <= availableTokens(), \"REQUESTED_AMOUNT_UNAVAILABLE\");\n releasedTokens += requestedAmount;\n IERC20(token).transfer(recipient, requestedAmount);\n emit TokensSentToRecipient(recipient, address(this), requestedAmount, releasedTokens);\n }\n\n /*\n Sets the allowance of the staking contract address to `approvedAmount`.\n to allow staking up to that amount of tokens.\n */\n function approveForStaking(uint256 approvedAmount) external onlyRecipient {\n IERC20(token).approve(stakingContract, approvedAmount);\n emit TokenAllowanceForStaking(address(this), stakingContract, approvedAmount);\n }\n}\n"
},
"Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`.\n // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.\n // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.\n // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a\n // good first aproximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1;\n uint256 x = a;\n if (x >> 128 > 0) {\n x >>= 128;\n result <<= 64;\n }\n if (x >> 64 > 0) {\n x >>= 64;\n result <<= 32;\n }\n if (x >> 32 > 0) {\n x >>= 32;\n result <<= 16;\n }\n if (x >> 16 > 0) {\n x >>= 16;\n result <<= 8;\n }\n if (x >> 8 > 0) {\n x >>= 8;\n result <<= 4;\n }\n if (x >> 4 > 0) {\n x >>= 4;\n result <<= 2;\n }\n if (x >> 2 > 0) {\n result <<= 1;\n }\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n uint256 result = sqrt(a);\n if (rounding == Rounding.Up && result * result < a) {\n result += 1;\n }\n return result;\n }\n}\n"
},
"Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"TimeLockedTokens.sol": {
"content": "/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.8.16;\n\nimport \"CommonConstants.sol\";\nimport \"LockedTokenCommon.sol\";\nimport \"Math.sol\";\n\n/**\n This contract provides the number of unlocked tokens,\n and indicates if the grant has fully unlocked.\n*/\nabstract contract TimeLockedTokens {\n // The lockedCommon is the central contract that provisions the locked grants.\n // It also used to maintain the token global timelock.\n LockedTokenCommon immutable lockedCommon;\n\n // The grant start time. This is the start time of the grant 4 years gradual unlock.\n // Grant can be deployed with startTime in the past or in the future.\n // The range of allowed past/future spread is defined in {CommonConstants}.\n // and validated in the constructor.\n uint256 public immutable startTime;\n\n // The amount of tokens in the locked grant.\n uint256 public immutable grantAmount;\n\n constructor(uint256 grantAmount_, uint256 startTime_) {\n lockedCommon = LockedTokenCommon(msg.sender);\n grantAmount = grantAmount_;\n startTime = startTime_;\n }\n\n /*\n Indicates whether the grant has fully unlocked.\n */\n function isGrantFullyUnlocked() public view returns (bool) {\n return block.timestamp >= startTime + GRANT_LOCKUP_PERIOD;\n }\n\n /*\n The number of locked tokens that were unlocked so far.\n */\n function unlockedTokens() public view returns (uint256) {\n // Before globalUnlockTime passes, The entire grant is locked.\n if (block.timestamp <= lockedCommon.globalUnlockTime()) return 0;\n\n uint256 cappedElapsedTime = Math.min(elapsedTime(), GRANT_LOCKUP_PERIOD);\n return (grantAmount * cappedElapsedTime) / GRANT_LOCKUP_PERIOD;\n }\n\n /*\n Returns the time passed (in seconds) since grant start time.\n Returns 0 if start time is in the future.\n */\n function elapsedTime() public view returns (uint256) {\n return block.timestamp > startTime ? block.timestamp - startTime : 0;\n }\n}\n"
}
},
"settings": {
"metadata": {
"useLiteralContent": true
},
"libraries": {},
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 1000000
},
"evmVersion": "istanbul",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}