creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../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 * The initial owner is set to the address provided by the deployer. This can\n * 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    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable\n    struct OwnableStorage {\n        address _owner;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Ownable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;\n\n    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {\n        assembly {\n            $.slot := OwnableStorageLocation\n        }\n    }\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    function __Ownable_init(address initialOwner) internal onlyInitializing {\n        __Ownable_init_unchained(initialOwner);\n    }\n\n    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\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        OwnableStorage storage $ = _getOwnableStorage();\n        return $._owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling 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        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\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        OwnableStorage storage $ = _getOwnableStorage();\n        address oldOwner = $._owner;\n        $._owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\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 * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\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 Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 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.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reininitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\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     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\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     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\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        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\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     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        assembly {\n            $.slot := INITIALIZABLE_STORAGE\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../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    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../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    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n    struct ReentrancyGuardStorage {\n        uint256 _status;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n        assembly {\n            $.slot := ReentrancyGuardStorageLocation\n        }\n    }\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\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        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if ($._status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        $._status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\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 Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        return $._status == ENTERED;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\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 value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n     * 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 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` 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(address from, address to, uint256 value) external returns (bool);\n}\n"
      },
      "contracts/StakingContractV1.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./StakingRecord.sol\";\nimport \"./StakingRateInfo.sol\";\nimport \"./StakingPeriod.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\n\ncontract StakingContractV1 is OwnableUpgradeable, ReentrancyGuardUpgradeable {\n    uint public constant DAY = 3600 * 24;\n    // uint public constant DAY = 1;       // For test\n\n    address public upcAddress;\n\n    mapping (uint => StakingRateInfo) public stakingInfos;\n\n    mapping (address => bool) public staked;\n\n    StakingRecord[] public records;\n\n    uint public stakingAmountLimit;\n\n    uint public totalStakingAmount;\n\n    mapping (string=>address) public referralCodes;\n\n    uint public referralFee;       //20%\n\n    event SetUPCAddress(address upcAddress);\n\n    event Stake(uint id, address staker, uint amount, uint stakedAt, uint stakingInfoID, string referralCode, uint reward, uint referralReward);\n\n    event Claim(uint id, address staker, uint claimAmount);\n\n    event ClaimReferralFee(uint id, address referrer, uint claimAmount);\n\n    event Deposit(uint amount);\n\n    event GenerateReferralCode(address staker, string code);\n\n    event SetStakingPeriod(uint id, StakingPeriod[] periods);\n\n    function initialvalue(address owner) initializer external {\n        stakingInfos[1].day = 180; stakingInfos[1].apy = 100;\n        stakingInfos[2].day = 90; stakingInfos[2].apy = 50;\n        stakingInfos[3].day = 30; stakingInfos[3].apy = 20;\n\n        // upcAddress = 0xCADC40cE57164b3193cCAAf0E5C498F8180DEF5f;     //testnet\n        upcAddress = 0x487d62468282Bd04ddf976631C23128A425555EE;     //mainnet\n\n        stakingAmountLimit = 10 ** 6 * 10 ** 5;\n\n        referralFee = 20;\n\n        __Ownable_init(owner);\n        __ReentrancyGuard_init();\n   }\n\n    function stake(uint amount, uint stakingInfoID, string memory referralCode) public nonReentrant {\n        require(amount >= 0, \"It's not able to stake 0 UPC.\");\n        require(isStakablePeriod(stakingInfoID), \"Out of staking period.\");\n        require(totalStakingAmount + amount <= stakingAmountLimit, \"Staking amount limit exceeds.\");\n        if (bytes(referralCode).length != 0) {\n            require(referralCodes[referralCode] != msg.sender, \"Not able to use own referral code.\");\n        }\n        \n        require(IERC20(upcAddress).allowance(msg.sender, address(this)) >= amount, \"UPC token is not allowed.\");\n        require(IERC20(upcAddress).balanceOf(msg.sender) >= amount, \"UPC token balance is not enough.\");\n        require(IERC20(upcAddress).transferFrom(msg.sender, address(this), amount), \"UPC token transfer failed.\");\n\n        records.push(StakingRecord(msg.sender, amount, block.timestamp, false, stakingInfoID, referralCode, false));\n\n        totalStakingAmount += amount;\n\n        staked[msg.sender] = true;\n\n        emit Stake(records.length - 1, msg.sender, amount, block.timestamp, stakingInfoID, referralCode, finalClaimableAmount(records.length - 1), referralAmount(records.length - 1));\n    }\n\n    function isStakablePeriod(uint id) public view returns(bool) {\n        for (uint i = 0; i < stakingInfos[id].periods.length; i++) {\n            if (block.timestamp >= stakingInfos[id].periods[i].from && block.timestamp <= stakingInfos[id].periods[i].to) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    function isClaimable(uint id) public view returns(bool) {\n        if (records[id].claimed) {\n            return false;\n        }\n\n        if (block.timestamp - records[id].stakedAt < DAY * stakingInfos[records[id].stakingRateInfoID].day) {\n            return false;\n        }\n\n        return true;\n    }\n\n    function referralAmount(uint id) public view returns(uint) {\n        if (records[id].claimedReferralFee) {\n            return 0;\n        }\n\n        if (bytes(records[id].referralCode).length == 0) {\n            return 0;\n        }\n\n        if (referralCodes[records[id].referralCode] == address(0)) {\n            return 0;\n        }\n\n        return (records[id].amount * stakingInfos[records[id].stakingRateInfoID].apy * (DAY * stakingInfos[records[id].stakingRateInfoID].day) / 100 / 365 / DAY) * referralFee / 100;\n    }\n\n    function finalClaimableAmount(uint id) public view returns(uint) {\n        if (records[id].claimed) {\n            return 0;\n        }\n\n        return records[id].amount * stakingInfos[records[id].stakingRateInfoID].apy * (DAY * stakingInfos[records[id].stakingRateInfoID].day) / 100 / 365 / DAY;\n    }\n\n    function claim(uint id) public {\n        require(msg.sender == records[id].staker, \"Only owner can claim.\");\n        require(isClaimable(id), \"This staking record is not able to claim.\");\n\n        uint amount = finalClaimableAmount(id);\n\n        require(IERC20(upcAddress).transfer(msg.sender, records[id].amount + amount), \"Claim failed.\");\n\n        records[id].claimed = true;\n\n        emit Claim(id, msg.sender, amount);\n    }\n\n    function claimReferralFee(uint id) public {\n        require(msg.sender == referralCodes[records[id].referralCode], \"Only referer can claim the referral fee.\");\n        require(block.timestamp - records[id].stakedAt >= DAY * stakingInfos[records[id].stakingRateInfoID].day, \"It is not able to claim, yet\");\n        require(!records[id].claimedReferralFee, \"Alreay claimed.\");\n\n        uint amount = referralAmount(id);\n        require(IERC20(upcAddress).transfer(msg.sender, amount), \"Claim failed.\");\n\n        records[id].claimedReferralFee = true;\n\n        emit ClaimReferralFee(id, msg.sender, amount);\n    }\n\n    function generateReferralCode() public {\n        require(staked[msg.sender] == true, \"You should have at least one staking record.\");\n\n        string memory code = randomString(6);\n        referralCodes[code] = msg.sender;\n\n        emit GenerateReferralCode(msg.sender, code);\n    }\n\n    function deposit(uint amount) public onlyOwner {\n        require(IERC20(upcAddress).allowance(msg.sender, address(this)) >= amount, \"UPC token is not allowed.\");\n        \n        require(IERC20(upcAddress).transferFrom(msg.sender, address(this), amount), \"Deposit failed.\");\n\n        emit Deposit(amount);\n    }\n\n    function shouldDeposit() public view returns(uint){\n        uint neccessaryAmount = neccessaryUPC();\n\n        if (neccessaryAmount < IERC20(upcAddress).balanceOf(address(this))) {\n            return 0;\n        }\n\n        return neccessaryAmount - IERC20(upcAddress).balanceOf(address(this));\n    }\n\n    function Withdrawable() public view returns(uint) {\n        uint neccessaryAmount = neccessaryUPC();\n\n        if (neccessaryAmount >= IERC20(upcAddress).balanceOf(address(this))) {\n            return 0;\n        }\n\n        return IERC20(upcAddress).balanceOf(address(this)) - neccessaryAmount;\n    }\n\n    function neccessaryUPC() private view returns(uint) {\n        uint ret = 0;\n        for (uint i = 0; i < records.length; i++) {\n            ret += finalClaimableAmount(i) + referralAmount(i);\n            if (!records[i].claimed) {\n                ret += records[i].amount;\n            }\n        }\n        return ret;\n    }\n\n    function withdraw(uint amount) public onlyOwner {\n        // bool isPeriodOver = true;\n        // for (uint id = 1; id <= 3; id++) {\n        //     for (uint i = 0; i < stakingInfos[id].periods.length; i++) {\n        //         if (block.timestamp < stakingInfos[id].periods[i].to) {\n        //             isPeriodOver = false;\n        //             break;\n        //         }\n        //     }\n        // }\n        // require(isPeriodOver, \"It's able to stake now.\");\n\n        require(IERC20(upcAddress).transfer(msg.sender, amount), \"Withdraw failed.\");\n    }\n\n    function setUPCAddress(address addr) public onlyOwner {\n        upcAddress = addr;\n\n        stakingAmountLimit = 10 ** 6 * 10 ** 5;\n\n        emit SetUPCAddress(addr);\n    }\n\n\n    function setStakingPeriod(uint id, StakingPeriod[] memory periods) public onlyOwner {\n        for (uint i = 0; i < stakingInfos[id].periods.length; i++) {\n            stakingInfos[id].periods.pop();\n        }\n\n        for (uint i = 0; i < periods.length; i++) {\n            stakingInfos[id].periods.push(periods[i]);\n        }\n\n        emit SetStakingPeriod(id, periods);\n    }\n\n    function setStakingLimit(uint limit) public onlyOwner {\n        stakingAmountLimit = limit;\n    }\n\n    function setReferralFee(uint fee) public onlyOwner {\n        require(fee <= 100, \"Referral Fee should be less than 100%.\");\n\n        referralFee = fee;\n    }\n\n    function randomString(uint size) private view returns(string memory){\n        bytes memory randomWord = new bytes(size);\n        // since we have 26 letters\n        bytes memory chars = new bytes(26);\n        chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n        for (uint i = 0; i < size; i++) {\n            uint randomNumber=random(26, i);\n            // Index access for string is not possible\n            randomWord[i] = chars[randomNumber];\n        }\n        return string(randomWord);\n    }\n\n    function random(uint number, uint randomIndex) public view returns(uint){\n        return uint(keccak256(abi.encodePacked(block.timestamp,block.prevrandao,  \n        msg.sender,randomIndex))) % number;\n    }\n\n    function pushRecord(address staker, uint amount, uint stakedAt, uint stakingInfoID, string memory referralCode, bool claimed, bool claimedReferralFee) public onlyOwner {\n        records.push(StakingRecord(staker, amount, stakedAt, claimed, stakingInfoID, referralCode, claimedReferralFee));\n        totalStakingAmount += amount;\n\n        staked[staker] = true;\n    }\n\n    function pushReferralCodes(address staker, string memory code) public onlyOwner {\n        referralCodes[code] = staker;\n    }\n}\n"
      },
      "contracts/StakingPeriod.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.9;\n\nstruct StakingPeriod {\n    uint from;\n    uint to;\n}"
      },
      "contracts/StakingRateInfo.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.9;\n\nimport \"./StakingPeriod.sol\";\n\nstruct StakingRateInfo {\n    uint day;\n    uint apy;\n    StakingPeriod[] periods;\n}"
      },
      "contracts/StakingRecord.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.9;\n\nstruct StakingRecord {\n    address staker;\n    uint amount;\n    uint stakedAt;\n    bool claimed;\n    uint stakingRateInfoID;\n    string referralCode;\n    bool claimedReferralFee;\n}"
      }
    },
    "settings": {
      "evmVersion": "paris",
      "optimizer": {
        "enabled": false,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}