// File: Better.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

contract Better {

    string public constant name = "Better";
    string public constant symbol = "BTR";
    uint8 public constant decimals = 18;  


    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
    event Transfer(address indexed from, address indexed to, uint tokens);


    mapping(address => uint256) balances;

    mapping(address => mapping (address => uint256)) allowed;
    
    uint256 totalSupply_;

    using SafeMath for uint256;


   constructor(uint256 total) {  
	totalSupply_ = total;
	balances[msg.sender] = totalSupply_;
    }

    function mint(uint256 amount_)public{
        totalSupply_ = totalSupply_.add(amount_);
        balances[msg.sender] = balances[msg.sender].add(amount_);
    }  

    function totalSupply() public view returns (uint256) {
	return totalSupply_;
    }
    
    function balanceOf(address tokenOwner) public view returns (uint) {
        return balances[tokenOwner];
    }

    function transfer(address receiver, uint numTokens) public returns (bool) {
        require(numTokens <= balances[msg.sender]);
        balances[msg.sender] = balances[msg.sender].sub(numTokens);
        balances[receiver] = balances[receiver].add(numTokens);
        emit Transfer(msg.sender, receiver, numTokens);
        return true;
    }

    function approve(address delegate, uint numTokens) public returns (bool) {
        allowed[msg.sender][delegate] = numTokens;
        emit Approval(msg.sender, delegate, numTokens);
        return true;
    }

    function allowance(address owner, address delegate) public view returns (uint) {
        return allowed[owner][delegate];
    }

    function transferFrom(address owner, address buyer, uint numTokens) public returns (bool) {
        require(numTokens <= balances[owner]);    
        require(numTokens <= allowed[owner][msg.sender]);
    
        balances[owner] = balances[owner].sub(numTokens);
        allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
        balances[buyer] = balances[buyer].add(numTokens);
        emit Transfer(owner, buyer, numTokens);
        return true;
    }
}

library SafeMath { 
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
      assert(b <= a);
      return a - b;
    }
    
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
      uint256 c = a + b;
      assert(c >= a);
      return c;
    }
}
// File: Context.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

interface IERC20 {
    function totalSupply() external view returns (uint);

    function balanceOf(address account) external view returns (uint);

    function transfer(address recipient, uint amount) external returns (bool);

    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint amount) external returns (bool);

    function transferFrom(
        address sender,
        address recipient,
        uint amount
    ) external returns (bool);

    event Transfer(address indexed from, address indexed to, uint value);
    event Approval(address indexed owner, address indexed spender, uint value);
}
// File: Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;
    address private _serviceAdmin;
    bool private initialized;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event NewServiceAdmin(address indexed previousServiceAdmin, address indexed newServiceAdmin);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */

    function init(address serviceAdmin_) internal {
        require(!initialized, "Ownable: init done");
        _setOwner(_msgSender());
        _setServiceAdmin(serviceAdmin_);
        initialized = true;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Returns the address of the current service admin.
     */
    function serviceAdmin() public view virtual returns (address) {
        return _serviceAdmin;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Throws if called by any account other than the service Admin.
     */
    modifier onlyServiceAdmin() {
        require(serviceAdmin() == _msgSender(), "Ownable: caller is not the serviceAdmin");
        _;
    }

    modifier anyAdmin(){
        require(serviceAdmin() == _msgSender() || owner() == _msgSender(), "Ownable: Caller is not authorized");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() external virtual onlyOwner {
        _setOwner(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) external virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }

    function _setServiceAdmin(address newServiceAdmin) private {
        address oldServiceAdmin = _serviceAdmin;
        _serviceAdmin = newServiceAdmin;
        emit NewServiceAdmin(oldServiceAdmin, newServiceAdmin);
    }
}

// File: Pauseable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "./Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {

    bool private pauseInit;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */

    function _pausable_init() internal{
         require(!pauseInit, "init done");
        _paused = false;
        pauseInit = true;
    }


    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        require(paused(), "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
// File: SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

// File: StakingV1.1.sol



// SPDX-License-Identifier: MIT

/*
                 .'cdO0000OO00KKNNNXKOkdc'.                 
              'cooolc;;lc',l:'':lloxO000KKOdc'              
           'ldoll;.'c..;; .:'  ':..::;cxKKxccddl'           
         ;ddlc'.:;                 ,..;c,cdxddk0Ox:.        
       ;ddc..:,                       ...,::xOo;;lkk;       
     .dx;.;;                             ''.,lk0xlodkd'     
    ;kl;c.                                 .c'.okc,,cO0:    
   ckc'..        .cxd,       'ldOd'          .c:c00ollokl   
  cO;'c.        .dWMMX:     ,0MMMM0'          .'.cko;;;xKl  
 ;Ol;,          ;KMMMMO.    oWMMMMWl           .c'cKkcccdO: 
.ko.,'          :NMMMMK,   .dMMMMMMd            .,;dx.   lk'
lk;:,           ,KMMMMO.    lWMMMMWo             ;,,OklllxKl
ko.'.           .oWMMNl     .OWMMM0'             .:;dO;...dO
0:;:             .ckk:.      .:okd'               ,.cO:...c0
0;'.     .;.                            ':c.      ;::0kllldK
O;c;     cXNOo'                      .cONNx.      ..;Oc   'O
0;..      lW0d,                      .;o0K,       ;::Ol...;0
0c;;      cNl                          .xK,       '.:0xlllkK
ko.,.     ;Xx.                         '0O.      .c;dk.   lO
lk::.     .xX:                         oNl       '.,0Oc::lOo
.ko.:'     'O0,                       cXx.      .::dkc::cOO'
 :Ol,'      'OKc.                   .oKx.      ':.:KkcccdO: 
  cO;,c.     .oKO;.               .cOKc.       ',cko;;:xKl  
   ckc.',      'd0Oo;..      ...:d0Ol.       .c,:00olldOl.  
    ;kl:;.       .;okOkkxddxkOOOko;.       .;.'oOl;;:k0:    
     .dx,'c'         .',::::;'..         ..':cxkdlok0x'     
       ;xd:.'c.                       ...c;;xXkc:cdx:       
        .;ddl:..c. .              .'..c,.:ddlcdKXk:.        
           'ldooc..:, .c. ';..':, 'c,,cokK0xdddl,           
              'cooolc;:l,.:c,,:cccldO0Okxkkdc'.             
                 .,lxO000OOO00KKNNNNX0Oxl,.                 
*/

// BETTER Staking Contract v1.1 (advisor vault with token lock period)
// based on Synthetix StakingRewards

pragma solidity ^0.8.9;
import "./IERC20.sol";
import "./Ownable.sol";
import "./Pauseable.sol";

contract StakingRewards is Ownable,Pausable{
    IERC20 public rewardsToken;
    IERC20 public stakingToken;
    uint256 public periodFinish;
    uint256 public withdrawLockPeriod;
    uint public rewardRate;
    uint public lastUpdateTime;
    uint public rewardPerTokenStored;
    mapping(address => uint) public userRewardPerTokenPaid;
    mapping(address => uint) public rewards;
    uint private _totalSupply;
    mapping(address => uint) private _balances;
    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardPaid(address indexed user, uint256 reward);
    event RewardsDurationUpdated(uint256 newDuration);
    event WithdrawDurationUpdated(uint256 newDuration);
    constructor(address _stakingToken, address _rewardsToken, uint256 _endTime, uint256 _rewardRate, address serviceAdmin) {
        stakingToken = IERC20(_stakingToken);
        rewardsToken = IERC20(_rewardsToken);
        withdrawLockPeriod = _endTime;
        periodFinish = _endTime;
        rewardRate = _rewardRate;
        Ownable.init(serviceAdmin);
    }
    function rewardPerToken() public view returns (uint) {
        if (_totalSupply == 0) {
            return 0;
        }
        return
            rewardPerTokenStored +
            (((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18) / _totalSupply);
    }
    function earned(address account) public view returns (uint) {
        return
            ((_balances[account] *
                (rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18) +
            rewards[account];
    }
    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdateTime = lastTimeRewardApplicable();
        if (account != address(0)) {
            rewards[account] = earned(account);
            userRewardPerTokenPaid[account] = rewardPerTokenStored;
        }
        _;
    }
    function stake(uint _amount) external whenNotPaused updateReward(msg.sender) {
        require(_amount > 0, "Cannot withdraw 0");
        _totalSupply += _amount;
        _balances[msg.sender] += _amount;
        stakingToken.transferFrom(msg.sender, address(this), _amount);
        emit Staked(msg.sender, _amount);
    }
    function withdraw(uint _amount) public whenNotPaused updateReward(msg.sender) {
        require(_amount > 0, "Cannot withdraw 0");
        require(withdrawLockPeriod < block.timestamp, "Can not withdraw during lock period");
        require(_balances[msg.sender] >= _amount,"Can not withdraw more than the current balance");
        _totalSupply -= _amount;
        _balances[msg.sender] -= _amount;
        stakingToken.transfer(msg.sender, _amount);
        emit Withdrawn(msg.sender, _amount);
    }
    function getReward() public whenNotPaused updateReward(msg.sender) {
        uint reward = rewards[msg.sender];
        if (reward > 0){
            rewards[msg.sender] = 0;
            rewardsToken.transfer(msg.sender, reward);
            emit RewardPaid(msg.sender, reward);
        }
    }
    
    function exit() whenNotPaused external {
        withdraw(_balances[msg.sender]);
        getReward();
    }
    
    function updatewithdrawLockPeriod(uint256 _newperiod)public anyAdmin {
        
        withdrawLockPeriod = _newperiod;
        emit WithdrawDurationUpdated(_newperiod);
    }
    function updatePeriod(uint256 _newperiod)public anyAdmin {
        require(_newperiod > periodFinish, "New time should be greater than old one");
        
        periodFinish = _newperiod;
        emit RewardsDurationUpdated(_newperiod);
    }
    function totalSupply() external view returns (uint256) {
        return _totalSupply;
    }
    function balanceOf(address account) external view returns (uint256) {
        return _balances[account];
    }
    function lastTimeRewardApplicable() public view returns (uint256) {
        return block.timestamp < periodFinish ? block.timestamp : periodFinish;
    }

    // ================== Functions to pause and unpause contract ==================
    
    function PauseContract()public anyAdmin{
        _pause();
    }
    function UnPauseContract()public anyAdmin{
        _unpause();
    }
}

// File: StakingV2.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

import "./IERC20.sol";
import "./Ownable.sol";

contract StakingRewards is Ownable{
    IERC20 public rewardsToken;
    IERC20 public stakingToken;

    uint256 public periodFinish;
    uint public rewardRate ;
    uint public lastUpdateTime;
    uint public rewardPerTokenStored;
    uint256 public lockPeriod;
    uint256 public stakeId;

    mapping(uint256 => address) public stakeOwner;
    mapping(uint256 => uint256) public stakeAmount;
    mapping(uint256 => uint256) public stakeTimestamp;
    mapping(uint256 => bool) public stakeStatus;

    mapping(uint256 => uint256) public userRewardPerTokenPaid;
    mapping(uint256 => uint256) public rewards;
    mapping(address => uint256) internal _balances;

    mapping(address => mapping(uint256 => uint256)) private _ownerIdIndex;
    mapping(address => uint256[]) private _ownerIds;

    uint public _totalSupply;


    event Staked(address indexed user, uint256 amount, uint256 stakeId);
    event Withdrawn(address indexed user, uint256 amount, uint256 stakeId);
    event RewardPaid(address indexed user, uint256 reward, uint256 stakeId);
    event RewardsDurationUpdated(uint256 newDuration);
    event LockPeriodUpdated(uint256 newPeriod);

    constructor(address _stakingToken, address _rewardsToken, uint256 _endTime, uint256 _lockPeriod, uint256 _rewardRate, address serviceAdmin) {
        stakingToken = IERC20(_stakingToken);
        rewardsToken = IERC20(_rewardsToken);
        periodFinish = _endTime;
        lockPeriod = _lockPeriod;
        rewardRate = _rewardRate;
        Ownable.init(serviceAdmin);
        stakeId = 1;
    }

    function rewardPerToken() public view returns (uint) {
        if (_totalSupply == 0) {
            return 0;
        }
        return
            rewardPerTokenStored +
            (((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18) / _totalSupply);
    }

    function earned(uint256 _stakeId) public view returns (uint) {
        return
            ((stakeAmount[_stakeId] *
                (rewardPerToken() - userRewardPerTokenPaid[_stakeId])) / 1e18) +
            rewards[_stakeId];
    }

    modifier updateReward(uint256 _stakeId) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdateTime = lastTimeRewardApplicable();

        rewards[_stakeId] = earned(_stakeId);
        userRewardPerTokenPaid[_stakeId] = rewardPerTokenStored;

        _;
    }

    function stake(uint _amount) external updateReward(stakeId) {
        _totalSupply += _amount;

        stakeAmount[stakeId] = _amount;
        stakeOwner[stakeId] = msg.sender;
        stakeStatus[stakeId] = true;
        stakeTimestamp[stakeId] = block.timestamp;

        _balances[msg.sender] += _amount;

        if (!_ownerIdExists(msg.sender, stakeId)) {
            _addOwnerId(msg.sender, stakeId);
        }

        stakingToken.transferFrom(msg.sender, address(this), _amount);
        emit Staked(msg.sender, _amount, stakeId);
        _incrementStakeId();
    }

    function withdraw(uint _stakeId) public updateReward(_stakeId) {
        require(stakeOwner[_stakeId] == msg.sender, "Only Owner can withdraw");
        require(stakeStatus[_stakeId], "Already withdrawn" );
        require(stakeTimestamp[_stakeId]+lockPeriod < block.timestamp, "Can not withdraw during lock period");

        _totalSupply -= stakeAmount[_stakeId];
        _balances[msg.sender] -= stakeAmount[_stakeId];

        if ( _ownerIdExists(msg.sender, _stakeId)) {
            _deleteOwnerId(msg.sender, _stakeId);
        }

        stakingToken.transfer(msg.sender, stakeAmount[_stakeId]);
        stakeStatus[_stakeId] = false;
        emit Withdrawn(msg.sender, stakeAmount[_stakeId], stakeId);
    }

    function getReward(uint256 _stakeId) public updateReward(_stakeId) {
        require(stakeOwner[_stakeId] == msg.sender, "Only Owner can claim reward");

        uint reward = rewards[_stakeId];
        if (reward > 0){
            rewards[_stakeId] = 0;
            rewardsToken.transfer(msg.sender, reward);
            emit RewardPaid(msg.sender, reward, stakeId);
        }
    }
    
    function updateRewardPeriod(uint256 _newperiod)public anyAdmin {
        require(_newperiod > periodFinish, "New time should be greater than old one");
        periodFinish = _newperiod;
        emit RewardsDurationUpdated(_newperiod);
    }

    function updateLockPeriod(uint256 _newLockPeriod)external anyAdmin{
        lockPeriod = _newLockPeriod;
        emit LockPeriodUpdated(_newLockPeriod);
    }

    function totalSupply() external view returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) external view returns (uint256) {
        return _balances[account];
    }

    function lastTimeRewardApplicable() public view returns (uint256) {
        return block.timestamp < periodFinish ? block.timestamp : periodFinish;
    }

    function _incrementStakeId()internal {
        stakeId +=1;
    }

    function _deleteOwnerId(address owner, uint256 id) internal {
        uint256 lastIndex = _ownerIds[owner].length - 1;
        uint256 lastId = _ownerIds[owner][lastIndex];
        if (id == lastId) {
            _ownerIdIndex[owner][id] = 0;
            _ownerIds[owner].pop();
        } else {
            uint256 indexOfId = _ownerIdIndex[owner][id];
            _ownerIdIndex[owner][id] = 0;

            _ownerIds[owner][indexOfId] = lastId;
            _ownerIdIndex[owner][lastId] = indexOfId;
            _ownerIds[owner].pop();
        }
    }

    function _addOwnerId(address owner, uint256 id) internal {
        uint256 len = _ownerIds[owner].length;
        _ownerIdIndex[owner][id] = len;
        _ownerIds[owner].push(id);
    }

    function _ownerIdExists(address owner, uint256 id) internal view returns (bool) {
        if (_ownerIds[owner].length == 0) return false;
        uint256 index = _ownerIdIndex[owner][id];
        return id == _ownerIds[owner][index];
    }

    function getOwnerIds(address owner) public view returns (uint256[] memory) {
        return _ownerIds[owner];
    }
   
    function getOwnerIdIndex(address owner, uint256 id) public view returns (uint256) {
        return _ownerIdIndex[owner][id];   
    }

}