zellic-audit
Initial commit
f998fcd
raw
history blame
50.8 kB
{
"language": "Solidity",
"sources": {
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal onlyInitializing {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n function __Pausable_init() internal onlyInitializing {\n __Pausable_init_unchained();\n }\n\n function __Pausable_init_unchained() internal onlyInitializing {\n _paused = false;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n require(!paused(), \"Pausable: paused\");\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n require(paused(), \"Pausable: not paused\");\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.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 IERC20Upgradeable {\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"
},
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.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 AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @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"
},
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"contracts/PresaleV6.sol": {
"content": "//SPDX-License-Identifier: MIT\n/*\n $$$$$$$$\\ $$$$$$\\ $$$$$$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ $$\\ $$\\ $$$$$$$$\\ \n $$ _____|\\_$$ _|$$ __$$\\ $$ | $$ |\\__$$ __|$$ __$$\\ $$ | $$ |\\__$$ __|\n $$ | $$ | $$ / \\__|$$ | $$ | $$ | $$ / $$ |$$ | $$ | $$ | \n $$$$$\\ $$ | $$ |$$$$\\ $$$$$$$$ | $$ | $$ | $$ |$$ | $$ | $$ | \n $$ __| $$ | $$ |\\_$$ |$$ __$$ | $$ | $$ | $$ |$$ | $$ | $$ | \n $$ | $$ | $$ | $$ |$$ | $$ | $$ | $$ | $$ |$$ | $$ | $$ | \n $$ | $$$$$$\\ \\$$$$$$ |$$ | $$ | $$ | $$$$$$ |\\$$$$$$ | $$ | \n \\__| \\______| \\______/ \\__| \\__| \\__| \\______/ \\______/ \\__| \n*/\n\npragma solidity 0.8.9;\n\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';\nimport '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';\n\ninterface Aggregator {\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n}\n\ncontract PresaleV7 is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable, PausableUpgradeable {\n uint256 public totalTokensSold;\n uint256 public totalBonus;\n uint256 public startTime;\n uint256 public endTime;\n uint256 public claimStart;\n address public saleToken;\n uint256 public baseDecimals;\n uint256 public maxTokensToBuy;\n uint256 public currentStep;\n\n IERC20Upgradeable public USDTInterface;\n Aggregator public aggregatorInterface;\n // https://docs.chain.link/docs/ethereum-addresses/ => (ETH / USD)\n\n uint256[1][2] public rounds;\n\n uint256[][2] public token_quantity_bonus;\n uint256 public default_lockup;\n uint256 public MONTH;\n uint256 public initialClaimPercent;\n\n struct UserDeposits {\n uint256 depositAmount;\n uint256 bonusAmount;\n uint256 initialClaim;\n uint256 claimedAmount;\n uint256 claimTime;\n }\n\n mapping(address => UserDeposits[]) public userDeposits;\n mapping(uint256 => uint256) public lockup_bonus;\n uint256 public linearStartTime;\n mapping(address => bool) public isBlacklisted;\n mapping(address => bool) public isWhitelisted;\n bool public whitelistClaimOnly;\n uint256 public increment;\n uint256 public linearPriceUsdRaised;\n mapping(address => bool) public wertWhitelisted;\n mapping(address => mapping(uint256 => bool)) public newUser;\n\n event SaleTimeSet(uint256 _start, uint256 _end, uint256 timestamp);\n\n event SaleTimeUpdated(bytes32 indexed key, uint256 prevValue, uint256 newValue, uint256 timestamp);\n\n event TokensBought(address indexed user, uint256 indexed tokensBought, address indexed purchaseToken, uint256 bonus, uint256 amountPaid, uint256 usdEq, uint256 timestamp);\n\n event TokensAdded(address indexed token, uint256 noOfTokens, uint256 timestamp);\n event TokensClaimed(address indexed user, uint256 indexed id, uint256 amount, uint256 timestamp);\n\n event ClaimStartUpdated(uint256 prevValue, uint256 newValue, uint256 timestamp);\n\n event MaxTokensUpdated(uint256 prevValue, uint256 newValue, uint256 timestamp);\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() initializer {}\n\n /**\n * @dev To pause the presale\n */\n function pause() external onlyOwner {\n _pause();\n }\n\n /**\n * @dev To unpause the presale\n */\n function unpause() external onlyOwner {\n _unpause();\n }\n\n /**\n * @dev To calculate the price in USD for given amount of tokens.\n * @param _amount No of tokens\n * @notice Since this presale has only one round, current step should not go above 0\n * in case of multiple rounds, current step has to be set accordingly\n */\n function calculatePrice(uint256 _amount) public view returns (uint256 totalValue) {\n uint256 USDTAmount;\n require(_amount <= maxTokensToBuy, 'Amount exceeds max tokens to buy');\n if (_amount + totalTokensSold > rounds[0][currentStep]) {\n require(currentStep < 0, 'Insufficient token amount.');\n uint256 tokenAmountForCurrentPrice = rounds[0][currentStep] - totalTokensSold;\n USDTAmount = tokenAmountForCurrentPrice * rounds[1][currentStep] + (_amount - tokenAmountForCurrentPrice) * rounds[1][currentStep + 1];\n } else {\n if (linearStartTime == 0 || linearStartTime >= block.timestamp) {\n USDTAmount = _amount * rounds[1][currentStep];\n } else {\n uint256 priceStep = (block.timestamp - linearStartTime) / (12 * 60 * 60);\n priceStep += 1;\n USDTAmount = (rounds[1][currentStep] + (priceStep * increment)) * _amount;\n }\n }\n return USDTAmount;\n }\n\n /**\n * @dev To update the sale times\n * @param _startTime New start time\n * @param _endTime New end time\n */\n function changeSaleTimes(uint256 _startTime, uint256 _endTime) external onlyOwner {\n require(_startTime > 0 || _endTime > 0, 'Invalid parameters');\n if (_startTime > 0) {\n require(block.timestamp < startTime, 'Sale already started');\n require(block.timestamp < _startTime, 'Sale time in past');\n uint256 prevValue = startTime;\n startTime = _startTime;\n emit SaleTimeUpdated(bytes32('START'), prevValue, _startTime, block.timestamp);\n }\n\n if (_endTime > 0) {\n require(block.timestamp < endTime, 'Sale already ended');\n require(_endTime > startTime, 'Invalid endTime');\n uint256 prevValue = endTime;\n endTime = _endTime;\n emit SaleTimeUpdated(bytes32('END'), prevValue, _endTime, block.timestamp);\n }\n }\n\n /**\n * @dev To update max tokens to buy\n * @param _maxTokensToBuy New max tokens value\n */\n function changeMaxTokensToBuy(uint256 _maxTokensToBuy) external onlyOwner {\n require(_maxTokensToBuy > 0, 'Zero max tokens to buy value');\n uint256 prevValue = maxTokensToBuy;\n maxTokensToBuy = _maxTokensToBuy;\n emit MaxTokensUpdated(prevValue, _maxTokensToBuy, block.timestamp);\n }\n\n /**\n * @dev To update rounds info\n * @param _rounds New rounds array\n */\n function changeRoundsData(uint256[1][2] memory _rounds) external onlyOwner {\n rounds = _rounds;\n }\n\n /**\n * @dev To get latest ethereum price in 10**18 format\n */\n function getLatestPrice() public view returns (uint256) {\n (, int256 price, , , ) = aggregatorInterface.latestRoundData();\n price = (price * (10**10));\n return uint256(price);\n }\n\n modifier checkSaleState(uint256 amount) {\n require(block.timestamp >= startTime && block.timestamp <= endTime, 'Invalid time for buying');\n require(amount > 0, 'Invalid sale amount');\n _;\n }\n\n /**\n * @dev To check total amount of bonus tokens user will get for particular amount and months locked\n * @param amount amount of tokens to be locked\n * @param lockup_months number of months tokens will be locked\n */\n\n function checkBonus(uint256 amount, uint256 lockup_months) public view returns (uint256, uint256) {\n (uint256 lbonus, ) = checkLockupBonus(amount, lockup_months);\n return (checkTokenQuantityBonus(amount), lbonus);\n }\n\n /**\n * @dev To check amount of bonus tokens user will get for particular amount purchased\n * compared with equivalent amount of tokens in USDT\n * @param amount amount of tokens to be locked\n */\n\n function checkTokenQuantityBonus(uint256 amount) public view returns (uint256) {\n uint256 price = calculatePrice(amount) / baseDecimals;\n if (price < token_quantity_bonus[0][0]) return 0;\n if (price >= token_quantity_bonus[0][token_quantity_bonus[0].length - 1]) return ((amount * baseDecimals) * token_quantity_bonus[1][token_quantity_bonus[1].length - 1]) / 10000;\n\n uint256 bonus;\n\n for (uint256 i = 0; i < (token_quantity_bonus[0].length); i++) {\n if (price < token_quantity_bonus[0][i]) {\n bonus = (token_quantity_bonus[1][i - 1]);\n break;\n } else if (price == token_quantity_bonus[0][i]) {\n bonus = (token_quantity_bonus[1][i]);\n break;\n }\n }\n\n return ((amount * baseDecimals) * bonus) / 10000;\n }\n\n /**\n * @dev To check amount of bonus tokens user will get for particular amount and months locked\n * @param amount amount of tokens to be locked\n * @param lockup_months number of months tokens will be locked\n */\n function checkLockupBonus(uint256 amount, uint256 lockup_months) public view returns (uint256 bonus, uint256 timeLockedFor) {\n if (lockup_bonus[lockup_months] == 0) {\n return (0, 0);\n } else {\n bonus = ((amount * baseDecimals) * lockup_bonus[lockup_months]) / 10000;\n timeLockedFor = lockup_months * MONTH;\n }\n }\n\n /**\n * @dev To buy into a presale using USDT\n * @param amount No of tokens to buy\n */\n function buyWithUSDT(uint256 amount, uint256 lockup_months) external checkSaleState(amount) whenNotPaused returns (bool) {\n uint256 usdPrice = usdtBuyHelper(amount);\n uint256 usdEq = calculatePrice(amount);\n uint256 newBonus = update(amount, lockup_months, usdEq, _msgSender());\n uint256 ourAllowance = USDTInterface.allowance(_msgSender(), address(this));\n require(usdPrice <= ourAllowance, 'Make sure to add enough allowance');\n (bool success, ) = address(USDTInterface).call(abi.encodeWithSignature('transferFrom(address,address,uint256)', _msgSender(), owner(), usdPrice));\n require(success, 'Token payment failed');\n emit TokensBought(_msgSender(), amount, address(USDTInterface), (newBonus), usdPrice, usdEq, block.timestamp);\n return true;\n }\n\n /**\n * @dev To buy into a presale using ETH\n * @param amount No of tokens to buy\n */\n function buyWithEth(uint256 amount, uint256 lockup_months) external payable checkSaleState(amount) whenNotPaused nonReentrant returns (bool) {\n uint256 ethAmount = ethBuyHelper(amount);\n uint256 usdEq = calculatePrice(amount);\n require(msg.value >= ethAmount, 'Less payment');\n uint256 excess = msg.value - ethAmount;\n uint256 newBonus = update(amount, lockup_months, usdEq, _msgSender());\n sendValue(payable(owner()), ethAmount);\n if (excess > 0) sendValue(payable(_msgSender()), excess);\n emit TokensBought(_msgSender(), amount, address(0), (newBonus), ethAmount, usdEq, block.timestamp);\n return true;\n }\n\n /**\n * @dev helper function to calculate LockupBonus & InvestmentBonus\n * @param amount No of tokens user has purchased\n * @param lockup_months number of months tokens will be locked\n */\n\n function update(\n uint256 amount,\n uint256 lockup_months,\n uint256 _linearPriceUsdRaised,\n address _user\n ) internal returns (uint256) {\n uint256 quantityBonus = checkTokenQuantityBonus(amount);\n (uint256 lockupBonus, uint256 time) = checkLockupBonus(amount, lockup_months);\n totalTokensSold += amount;\n if (totalTokensSold > rounds[0][currentStep]) {\n currentStep += 1;\n }\n\n uint256 newBonus = quantityBonus + lockupBonus;\n linearPriceUsdRaised += _linearPriceUsdRaised;\n userDeposits[_user].push(UserDeposits(amount * baseDecimals, newBonus, (((amount * baseDecimals) + newBonus) * initialClaimPercent) / 10000, 0, time));\n newUser[_user][userDeposits[_user].length - 1] = true;\n totalBonus += (newBonus);\n return newBonus;\n }\n\n function updateLinearStartTime(uint256 time) external onlyOwner {\n require(linearStartTime == 0, 'Linear time already set');\n linearStartTime = time;\n }\n\n function updateIncrement(uint256 _increment) external onlyOwner {\n require(increment == 0, 'increment already set');\n increment = _increment;\n }\n\n /**\n * @dev to update userDeposits for purchases made on BSC\n * @param users array of users\n * @param users array of userDeposits associated with users\n */\n function updateFromBSC(address[] calldata users, UserDeposits[] calldata _userDeposits) external onlyOwner {\n require(users.length == _userDeposits.length, 'Length mismatch');\n for (uint256 i = 0; i < users.length; i++) {\n userDeposits[users[i]].push(_userDeposits[i]);\n }\n }\n\n /**\n * @dev Helper funtion to get ETH price for given amount\n * @param amount No of tokens to buy\n */\n function ethBuyHelper(uint256 amount) public view returns (uint256 ethAmount) {\n uint256 usdPrice = calculatePrice(amount);\n ethAmount = (usdPrice * baseDecimals) / getLatestPrice();\n }\n\n /**\n * @dev Helper funtion to get USDT price for given amount\n * @param amount No of tokens to buy\n */\n function usdtBuyHelper(uint256 amount) public view returns (uint256 usdPrice) {\n usdPrice = calculatePrice(amount);\n usdPrice = usdPrice / (10**12);\n }\n\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, 'Low balance');\n (bool success, ) = recipient.call{value: amount}('');\n require(success, 'ETH Payment failed');\n }\n\n /**\n * @dev To check details of transactions done by the user\n * @param user user's address\n */\n\n function deposits(address user) external view returns (UserDeposits[] memory) {\n return userDeposits[user];\n }\n\n /**\n * @dev To set the claim start time and sale token address by the owner\n * @param _claimStart claim start time\n * @param noOfTokens no of tokens to add to the contract\n * @param _saleToken sale toke address\n */\n function startClaim(\n uint256 _claimStart,\n uint256 noOfTokens,\n address _saleToken\n ) external onlyOwner returns (bool) {\n require(_claimStart > endTime && _claimStart > block.timestamp, 'Invalid claim start time');\n require(noOfTokens >= (totalTokensSold * baseDecimals) + totalBonus, 'Tokens less than sold');\n require(_saleToken != address(0), 'Zero token address');\n require(claimStart == 0, 'Claim already set');\n claimStart = _claimStart;\n saleToken = _saleToken;\n bool success = IERC20Upgradeable(_saleToken).transferFrom(_msgSender(), address(this), noOfTokens);\n require(success, 'Token transfer failed');\n emit TokensAdded(saleToken, noOfTokens, block.timestamp);\n return true;\n }\n\n /**\n * @dev To change the claim start time by the owner\n * @param _claimStart new claim start time\n */\n function changeClaimStart(uint256 _claimStart) external onlyOwner returns (bool) {\n require(claimStart > 0, 'Initial claim data not set');\n require(_claimStart > endTime, 'Sale in progress');\n require(_claimStart > block.timestamp, 'Claim start in past');\n uint256 prevValue = claimStart;\n claimStart = _claimStart;\n emit ClaimStartUpdated(prevValue, _claimStart, block.timestamp);\n return true;\n }\n\n /**\n * @dev To claim tokens after claiming starts\n * @param _id Id of the transaction\n */\n function claim(uint256 _id) public whenNotPaused returns (bool) {\n require(saleToken != address(0), 'Sale token not added');\n require(!isBlacklisted[_msgSender()], 'This Address is Blacklisted');\n\n if (whitelistClaimOnly) {\n require(isWhitelisted[_msgSender()], 'User not whitelisted for claim');\n }\n\n uint256 tokens = getClaimableAmount(_msgSender(), _id);\n require(tokens > 0, 'No claimable tokens available');\n\n if (!newUser[_msgSender()][_id]) {\n userDeposits[_msgSender()][_id].claimedAmount += tokens - ((tokens * 10) / 100);\n } else {\n userDeposits[_msgSender()][_id].claimedAmount += tokens;\n }\n\n bool success = IERC20Upgradeable(saleToken).transfer(_msgSender(), tokens);\n require(success, 'Token transfer failed');\n emit TokensClaimed(_msgSender(), _id, tokens, block.timestamp);\n return true;\n }\n\n /**\n * @dev To claim multiple tokens after claiming starts\n * @param _id array of id's of the transaction\n */\n function claimMultiple(uint256[] memory _id) external whenNotPaused {\n require(_id.length > 0, 'Invalid length');\n for (uint256 i; i < _id.length; i++) {\n require(claim(_id[i]), 'Claiming failed');\n }\n }\n\n /**\n * @dev Helper funtion to get claimable tokens for a user after claiming starts\n * @param _user Address of the user\n * @param _id Id of the transaction\n */\n function getClaimableAmount(address _user, uint256 _id) public view returns (uint256 claimableAmount) {\n require(claimStart > 0, 'Claim start time not set');\n require(_id < userDeposits[_user].length, 'Invalid Id');\n UserDeposits memory deposit = userDeposits[_user][_id];\n uint256 amount = deposit.depositAmount;\n uint256 bonus = deposit.bonusAmount;\n amount += bonus;\n uint256 claimedAmount = deposit.claimedAmount;\n require(amount > 0, 'Nothing to claim');\n\n if (amount - claimedAmount == 0) return 0;\n\n if (block.timestamp < claimStart) return 0;\n\n if (block.timestamp < (claimStart + deposit.claimTime)) {\n uint256 timePassedRatio = ((block.timestamp - claimStart) * baseDecimals) / ((deposit.claimTime));\n\n claimableAmount = (((amount - deposit.initialClaim) * timePassedRatio) / baseDecimals) + deposit.initialClaim;\n } else {\n claimableAmount = amount;\n }\n\n claimableAmount = claimableAmount - claimedAmount;\n if (!newUser[_msgSender()][_id]) {\n claimableAmount += (claimableAmount * 10) / 100;\n }\n }\n\n /**\n * @dev To update Investment bonus structure\n * @param _tokenQuantity updated values array\n */\n function updateInvestmentBonus(uint256[][2] memory _tokenQuantity) public onlyOwner {\n require(_tokenQuantity[0].length == _tokenQuantity[1].length, 'Mismatch length for token quantity bonus');\n token_quantity_bonus = _tokenQuantity;\n }\n\n /**\n * @dev To update LockUp bonus structure\n * @param _lockup updated values array\n */\n function updateLockUpBonus(uint256[][] memory _lockup) public onlyOwner {\n require(_lockup[0].length == _lockup[1].length, 'Mismatch length for token lockup bonus');\n for (uint256 i; i < _lockup[0].length; i++) {\n lockup_bonus[_lockup[0][i]] = _lockup[1][i];\n }\n }\n\n /**\n * @dev To buy ETH directly from wert .*wert contract address should be whitelisted if wertBuyRestrictionStatus is set true\n * @param user address of the user\n * @param amount No of ETH to buy\n */\n function buyWithETHWert(\n address user,\n uint256 amount,\n uint256 lockup_months\n ) external payable checkSaleState(amount) whenNotPaused nonReentrant returns (bool) {\n require(wertWhitelisted[_msgSender()], 'User not whitelisted for this tx');\n uint256 ethAmount = ethBuyHelper(amount);\n uint256 usdEq = calculatePrice(amount);\n require(msg.value >= ethAmount, 'Less payment');\n uint256 excess = msg.value - ethAmount;\n uint256 newBonus = update(amount, lockup_months, usdEq, user);\n\n sendValue(payable(owner()), ethAmount);\n if (excess > 0) sendValue(payable(user), excess);\n emit TokensBought(user, amount, address(0), (newBonus), ethAmount, usdEq, block.timestamp);\n return true;\n }\n\n /**\n * @dev To add wert contract addresses to whitelist\n * @param _addressesToWhitelist addresses of the contract\n */\n function whitelistUsersForWERT(address[] calldata _addressesToWhitelist) external onlyOwner {\n for (uint256 i = 0; i < _addressesToWhitelist.length; i++) {\n wertWhitelisted[_addressesToWhitelist[i]] = true;\n }\n }\n\n /**\n * @dev To remove wert contract addresses to whitelist\n * @param _addressesToRemoveFromWhitelist addresses of the contracts\n */\n function removeFromWhitelistForWERT(address[] calldata _addressesToRemoveFromWhitelist) external onlyOwner {\n for (uint256 i = 0; i < _addressesToRemoveFromWhitelist.length; i++) {\n wertWhitelisted[_addressesToRemoveFromWhitelist[i]] = false;\n }\n }\n\n /**\n * @dev To add users to blacklist which restricts blacklisted users from claiming\n * @param _usersToBlacklist addresses of the users\n */\n function blacklistUsers(address[] calldata _usersToBlacklist) external onlyOwner {\n for (uint256 i = 0; i < _usersToBlacklist.length; i++) {\n isBlacklisted[_usersToBlacklist[i]] = true;\n }\n }\n\n /**\n * @dev To remove users from blacklist which restricts blacklisted users from claiming\n * @param _userToRemoveFromBlacklist addresses of the users\n */\n function removeFromBlacklist(address[] calldata _userToRemoveFromBlacklist) external onlyOwner {\n for (uint256 i = 0; i < _userToRemoveFromBlacklist.length; i++) {\n isBlacklisted[_userToRemoveFromBlacklist[i]] = false;\n }\n }\n\n /**\n * @dev To add users to whitelist which restricts users from claiming if claimWhitelistStatus is true\n * @param _usersToWhitelist addresses of the users\n */\n function whitelistUsers(address[] calldata _usersToWhitelist) external onlyOwner {\n for (uint256 i = 0; i < _usersToWhitelist.length; i++) {\n isWhitelisted[_usersToWhitelist[i]] = true;\n }\n }\n\n /**\n * @dev To remove users from whitelist which restricts users from claiming if claimWhitelistStatus is true\n * @param _userToRemoveFromWhitelist addresses of the users\n */\n function removeFromWhitelist(address[] calldata _userToRemoveFromWhitelist) external onlyOwner {\n for (uint256 i = 0; i < _userToRemoveFromWhitelist.length; i++) {\n isWhitelisted[_userToRemoveFromWhitelist[i]] = false;\n }\n }\n\n /**\n * @dev To set status for claim whitelisting\n * @param _status bool value\n */\n function setClaimWhitelistStatus(bool _status) external onlyOwner {\n whitelistClaimOnly = _status;\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}