creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/StakingContract.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.24;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract StakingContract is ReentrancyGuard, Ownable {\n    IERC20 public basicToken;\n\n    uint256 public totalStaked;\n    uint256 public totalStakedAccruingRewards;  \n    uint256 public rewardRate;\n    uint256 public lastUpdateTime;\n    uint256 public rewardPerTokenStored;\n    uint256 public unstakeTimeLock = 7 days; // Default time lock for unstaking\n    uint256 public unstakeFeePercent = 0; // Fee for unstaking, in basis points\n    uint256 public emissionStart;\n    uint256 public emissionEnd;\n    uint256 public feesAccrued;\n    uint256 public pendingRewardsStored;\n    \n    uint256 private constant MAX_FEE = 200;\n    uint256 private constant BASIS_POINTS = 10000;\n    uint256 private constant MAX_TIMELOCK = 15 days;\n\n    struct Staker {\n        uint256 amountStaked;\n        uint256 rewardDebt;\n        uint256 rewards;\n        uint256 unstakeInitTime; \n    }\n\n    mapping(address => Staker) public stakers;\n\n    event UnstakeInitiated(address indexed user);\n    event Staked(address indexed user, uint256 amount);\n    event Unstaked(address indexed user, uint256 amount);\n    event RewardPaid(address indexed user, uint256 reward);\n    event UnstakeFeePercentUpdated(uint256 newFeePercent);\n    event UnstakeTimeLockUpdated(uint256 newTimeLock);\n\n    modifier updateReward(address account) {\n        rewardPerTokenStored = rewardPerToken();\n        pendingRewardsStored = pendingRewards();\n        lastUpdateTime = lastApplicableTime();\n        Staker storage staker = stakers[account];\n        if (staker.unstakeInitTime == 0 ) {\n            staker.rewards = earned(account);\n            staker.rewardDebt = rewardPerTokenStored;\n        }\n        \n        // else if (staker.unstakeInitTIme !=0)\n        //staker.rewards = staker.rewards;\n        _;\n    }\n\n    constructor(IERC20 _basicToken, uint256 _rewardRate, uint256 _emissionStart, uint256 _emissionDuration) Ownable(msg.sender) {\n        basicToken = _basicToken;\n        rewardRate = _rewardRate;\n        emissionStart = _emissionStart;\n        emissionEnd = emissionStart + _emissionDuration;\n    }\n\n    function lastApplicableTime() public view returns (uint256) {\n        return block.timestamp < emissionEnd ? block.timestamp : emissionEnd;\n    }\n\n    function pendingRewards() public view returns (uint256) {\n            uint256 totalStakedAccruingRewardsCached = totalStakedAccruingRewards;\n            if (totalStakedAccruingRewardsCached == 0) return pendingRewardsStored;\n            uint256 fullPendingRewards = (lastApplicableTime() - lastUpdateTime) * rewardRate * 1e18;\n            uint256 roundingError = fullPendingRewards % totalStakedAccruingRewardsCached;\n            return pendingRewardsStored + fullPendingRewards - roundingError;\n        }\n\n    function rewardPerToken() public view returns (uint256) {\n        if (totalStakedAccruingRewards == 0) {\n            return rewardPerTokenStored;\n        }\n        return rewardPerTokenStored + (\n            (lastApplicableTime() - lastUpdateTime) * rewardRate * 1e18 / totalStakedAccruingRewards\n        );\n    }\n\n    function earned(address account) public view returns (uint256) {\n        Staker storage staker = stakers[account];\n        if (staker.unstakeInitTime != 0) {\n                return staker.rewards;\n        }\n        return (\n            staker.amountStaked *\n            (rewardPerToken() - staker.rewardDebt) / 1e18\n        ) + staker.rewards;\n    }\n\n\n    function stake(uint256 _amount) external nonReentrant updateReward(msg.sender) {\n        require(_amount > 0, \"Cannot stake 0\");\n        require(block.timestamp >= emissionStart, \"Staking not yet started\");\n        require(block.timestamp <= emissionEnd, \"Staking period has ended\");\n        Staker storage staker = stakers[msg.sender];\n        require(staker.unstakeInitTime == 0, \"Cannot stake after initiating unstake.\");\n        totalStaked += _amount;\n        totalStakedAccruingRewards += _amount;\n        staker.amountStaked += _amount;\n        require(basicToken.transferFrom(msg.sender, address(this), _amount), \"Token deposit failed\");\n        emit Staked(msg.sender, _amount);\n    }\n\n    function initiateUnstake() external updateReward(msg.sender) {\n        Staker storage staker = stakers[msg.sender];\n        require(staker.amountStaked > 0, \"No tokens staked\");\n        require(staker.unstakeInitTime == 0, \"Unstake already initiated\");\n        staker.unstakeInitTime = block.timestamp;\n        totalStakedAccruingRewards -= staker.amountStaked;\n        emit UnstakeInitiated(msg.sender);\n    }\n\n    function completeUnstake() external nonReentrant updateReward(msg.sender) {\n        Staker storage staker = stakers[msg.sender];\n        require(staker.amountStaked > 0, \"No tokens staked\");\n        require(staker.unstakeInitTime > 0, \"Unstake not initiated\");\n        require(block.timestamp >= staker.unstakeInitTime + unstakeTimeLock, \"Timelock not yet passed\");\n\n        uint256 amount = staker.amountStaked;\n        uint256 reward = staker.rewards;\n        uint256 fee = amount * unstakeFeePercent / BASIS_POINTS;\n        uint256 amountAfterFee = amount - fee;\n\n        uint256 availableForRewards = _getFreeContractBalance();\n\n        feesAccrued += fee;\n        totalStaked -= amount;\n        staker.amountStaked = 0;\n        staker.rewardDebt = 0;\n        staker.unstakeInitTime = 0;\n\n        uint256 totalAmount = amountAfterFee;\n        // If there are rewards, combine them with the staked amount after fees for a single transfer\n        if (reward > 0 && availableForRewards >= reward) {\n            if (pendingRewardsStored >= reward * 1e18) pendingRewardsStored -= reward * 1e18;\n            totalAmount += reward;\n            staker.rewards = 0;\n            emit RewardPaid(msg.sender, reward);\n        }\n        require(basicToken.transfer(msg.sender, totalAmount), \"Unstake transfer failed\");\n        emit Unstaked(msg.sender, amount);\n    }\n\n    function claimReward() external nonReentrant updateReward(msg.sender) {\n        Staker storage staker = stakers[msg.sender];\n        uint256 reward = staker.rewards;\n        require(reward > 0, \"No rewards to claim\");\n\n        // Calculate the available balance for rewards\n        uint256 availableForRewards = _getFreeContractBalance();\n        require(availableForRewards >= reward, \"Insufficient funds for reward\");\n        if (pendingRewardsStored >= reward * 1e18) pendingRewardsStored -= reward * 1e18;\n        staker.rewards = 0;\n        require(basicToken.transfer(msg.sender, reward), \"Reward transfer failed\");\n        emit RewardPaid(msg.sender, reward);\n    }\n\n    function setUnstakeFeePercent(uint256 _newFee) external onlyOwner {\n        require(_newFee <= MAX_FEE, \"Unstake fee exceeds 2%, maximum allowed\"); \n        unstakeFeePercent = _newFee;\n        emit UnstakeFeePercentUpdated(_newFee); \n    }\n\n    function setUnstakeTimeLock(uint256 _newTimeLock) external onlyOwner {\n        require(_newTimeLock <= MAX_TIMELOCK, \"Time lock must be between 0 to 15 days\");\n        unstakeTimeLock = _newTimeLock;\n        emit UnstakeTimeLockUpdated(_newTimeLock);\n    }\n\n    function getRemainingUnstakeTime(address _staker) external view returns (uint256) {\n        Staker storage staker = stakers[_staker];\n        if (block.timestamp < staker.unstakeInitTime + unstakeTimeLock) {\n            return (staker.unstakeInitTime + unstakeTimeLock) - block.timestamp;\n        } else {\n            return 0;\n        }\n    }\n\n    function withdrawFees(uint256 amount) external onlyOwner {\n        require(amount <= feesAccrued, \"Amount exceeds accrued fees\");\n        feesAccrued -= amount;\n        require(basicToken.transfer(msg.sender, amount), \"Fee withdrawal failed\");\n    }\n\n    function withdrawRemainingTokens() external updateReward(address(0)) onlyOwner {\n        require(block.timestamp > emissionEnd, \"Cannot withdraw before emission end\");\n        uint256 freeContractBalanceCached = _getFreeContractBalance();\n        uint256 pendingRewardsCached = pendingRewards() / 1e18;\n\n        require(freeContractBalanceCached > pendingRewardsCached, \"No remaining tokens to withdraw\");\n        uint256 remainingBalance = freeContractBalanceCached - pendingRewardsCached;\n        require(basicToken.transfer(msg.sender, remainingBalance), \"Token withdrawal failed\");\n    }\n\n    function _getFreeContractBalance() internal view returns (uint256) {\n        return basicToken.balanceOf(address(this)) - totalStaked - feesAccrued;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\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 ReentrancyGuard {\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    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\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        // 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        // 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        return _status == ENTERED;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/access/Ownable.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 {Context} from \"../utils/Context.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 Ownable is Context {\n    address private _owner;\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    constructor(address initialOwner) {\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        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        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\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    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
        "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
        "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
        "forge-std/=lib/forge-std/src/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": false,
      "libraries": {}
    }
  }}