Skip to content
Verified contractExactUNLICENSED

ExtoPlanV7

Address0xe2cff64b1da0e08e009ca30545cffac445a3aecb
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 50 runs
EVM version
paris
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,628,120
Creation transaction
0x9f55d8b042…ac8668c2b9

contracts/exto_plan/exto_planV7.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol';

interface Aggregator {
    function latestAnswer(address) external view returns (int256 prevAnswer, int256 latestAnswer, int256 sumAnswer);
}

interface IExtoTokenMiles {
    function releaseMilesToHolder(address _holder, address _creator, uint256 _reward, uint32 _feerate) external;
    function releaseMilesToPlan(address _creator, uint256 _reward, uint32 _feerate) external;    
    function enrollRewardToReferrer(address _contractor, address _referrer, uint256 _amount, uint256 _period) external;
}
/*
  enrollPeriod = 0 : enroll any time 
*/
contract ExtoPlanV7 is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable {
    
    IERC20 public extoInterface;
    Aggregator public aggregatorInterface; // yield Rate Data Aggregator
    IExtoTokenMiles public extoTokenMiles;
    uint256 extoBase;

    bool public isSingleContract;
    bool public isClosePlan;
    bool public canRefund;
    bool public isIndivReward;

    uint256 public rewardTerm; // days, week = 7, months = 28, quarter 90, half 180, year 365
    uint256 public rewardCount; // max 255

    int256 public baseRate;
    uint32 public feeRate;

    uint256 public enrollStartAt; //collecting exto start date
    uint256 public enrollPeriod; 

    uint256 public planStartAt;  
    uint256 public planPeriod;
    uint256 public planLockupPeriod;
    uint256 public rewardSentAt; //latest rewarding time

    uint256 public tempDeposits; //to creator 

    uint256 public totalRewards; 
    uint256 public totalEnrollments; 
    uint256 public totalDeposit; //releaseable deposits
    uint256 public totalRefund;
    uint256 public cntEnrollment;
    uint256 public cntRefund; 

    uint256 public minDeposit;
    uint256 public maxDeposit;
    uint256 public extoValue;
    uint256 public targetDeposit;

    address public creator;
    address public operator;

    struct Staking {
        uint256 amount;
        uint256 refund;
        uint256 reward;
        uint256 rewardAt;
        int256 latestRoi;
        address referrer;
        uint8 flag;
    }

    uint8 constant CAN_REFUND = 1 << 0;
    uint8 constant IS_REFUNDED = 1 << 1;
    uint8 constant IS_START = 1 << 2;
    uint8 constant IS_CLOSED = 1 << 3;
    uint8 constant IS_PAUSED = 1 << 4;
    uint8 constant IS_LOCKED = 1 << 5;

    mapping(address => uint256) public mapDeposits;
    mapping(address => uint256) public mapClaimable; // claimable balance
    mapping(address => uint256) public mapRewards; // rewarded 
    mapping(address => uint256) public mapRefunds;
    mapping(address => Staking[]) public mapStaking;

    event ReleaseReward(address indexed user, uint256 amount, uint256 timestamp);
    event ReleaseRewardToPlan(address indexed user, uint256 amount, int256 yieldRate, uint256 timestamp);
    event ReleaseRewardToHolder(address indexed user, uint256 amount, int256 yieldRate, uint256 timestamp);    
    event RewardsEachByNet(address indexed user, uint256 amount, int256 yieldRate, uint256 timestamp);

    event ListUpReward(address indexed user, uint256 length, uint256 total, uint256 timestamp);
    event Enrollment(address indexed user, uint256 amount, uint256 stakingLength, address indexed referrer, uint256 timestamp);
    event AllowRefund(address indexed user, uint256 amount, uint256 timestamp);
    event Refund(address indexed user, uint256 amount, uint256 timestamp);
    event Refunds(address indexed user, uint256 amount, uint256 length, uint256 timestamp);
    event StatusPlan(bytes32 indexed key, uint256 timestamp);    
    event SetEnrollment(uint256 enrollStartAt, uint256 enrollPeriod, uint256 timestamp);
    event SetPlanPeriod(uint256 planStartAt, uint256 planPeriod, uint256 timestamp);
    event ChangeAddress(address indexed from, address to, uint256 timestamp);

    //V7
    event ClaimRefundToHolder(address indexed user, uint256 amount, int256 yieldRate, uint256 refund, uint256 timestamp);

    function initialize(address _exto, address _oracle, address _creator, address _tokenMiles, int256 _baseRate) external initializer {
        require(_oracle != address(0), 'check aggregator address');
        require(_exto != address(0), 'check exto address');    
        require(_tokenMiles != address(0), 'check tokenmiles address');    
        require(_creator != address(0), 'check creator address');    

        extoInterface = IERC20(_exto);
        aggregatorInterface = Aggregator(_oracle);
        extoTokenMiles = IExtoTokenMiles(_tokenMiles);

        __Pausable_init_unchained();
        __Ownable_init_unchained(_msgSender());
        __ReentrancyGuard_init_unchained();   

        baseRate = _baseRate;        

        extoBase = 1e18;
        creator = _creator;
    }      

    function initEnroll(uint256 _minDeposit, uint256 _maxDeposit, uint256 _ev,  uint256 _targetDeposit, uint256 _enrollStartAt, uint256 _enrollPeriod, bool _isIndivReward, uint256 _planPeriod, bool _isSingleContract) external onlyOwner {    
        require(_enrollStartAt >= block.timestamp, 'Invalid enroll time');

        minDeposit = _minDeposit * extoBase;
        maxDeposit = _maxDeposit * extoBase;
        extoValue = _ev * extoBase;
        targetDeposit = _targetDeposit * extoBase;

        enrollStartAt = _enrollStartAt;
        enrollPeriod = _enrollPeriod;
        isIndivReward = _isIndivReward;
        isSingleContract = _isSingleContract;

        setPeriod(_planPeriod);

        emit StatusPlan(bytes32('INIT'), block.timestamp);
    }

    function startPlan(uint256 _planStartAt, uint256 _planPeriod, uint256 _rewardTerm) external hasPermit nonReentrant {
        require(!canRefund, "under refund");
        require(!isClosePlan, "closed plan");
        require(planStartAt == 0, "already start");

        if ((targetDeposit > 0 && targetDeposit > totalEnrollments) && (enrollPeriod > 0 && enrollEndAt() > block.timestamp)) {
          revert("can not start");
        }

        setPeriod(_planPeriod);

        planStartAt = _planStartAt;    
        rewardSentAt = _planStartAt;
        rewardTerm = _rewardTerm;

        emit StatusPlan(bytes32('START'), block.timestamp);
    }    

    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();    
    }    

    function setFlag(Staking storage _staking, uint8 _mask, bool _value) internal {
        if (_value)
            _staking.flag |= _mask;
        else 
            _staking.flag &= ~_mask;
    }

    function setFlagStatus(address _holder, uint256 _stakingIdx, uint8 _flag, bool _value) public onlyOwner {
        require(_stakingIdx < mapStaking[_holder].length, "Index out of bounds");
        Staking storage staking = mapStaking[_msgSender()][_stakingIdx];
        setFlag(staking, _flag, _value);        
    }

    function getYieldRate() public view returns (int256, int256, int256) {
        (int256 prevSumLatest, int256 latestRate, int256 sumLatestRate) = aggregatorInterface.latestAnswer(address(this)); // decimals 8
        return (prevSumLatest, latestRate, sumLatestRate);
    }

    function setEnrollment(uint256 _enrollStartAt, uint256 _enrollPeriod) external nonReentrant onlyOwner {      
        require(enrollStartAt > 0, "not init enrollment");
        require(planStartAt <= block.timestamp, "already start");
        require(_enrollStartAt > 0 || _enrollPeriod >= 0, "empty vars");
    
        if (_enrollStartAt > 0) enrollStartAt = _enrollStartAt;
        
        enrollPeriod = _enrollPeriod;
        emit SetEnrollment(_enrollStartAt, _enrollPeriod, block.timestamp);
    }   

    function enrollEndAt() public view returns (uint256) {
        return enrollStartAt + enrollPeriod;
    }

    function setPlanPeriod(uint256 _planStartAt, uint256 _planPeriod) external nonReentrant onlyOwner {
        require(enrollStartAt > 0, "not init enrollment");              

        planStartAt = _planStartAt;        
        setPeriod(_planPeriod);
        
        emit SetPlanPeriod(_planStartAt, _planPeriod, block.timestamp);
    } 

    function planEndAt() external view returns (uint256) {
        return planStartAt + planPeriod;
    }

    function ReleaseLockupAt() public view returns (uint256) {
        return planStartAt + planLockupPeriod;
    }

    function getEnrollStartAt() external view returns (uint256) {
        return enrollStartAt;
    }

    // by onChain (private)
    function enrollPlan(address _address, uint256 _amount, address _referrer) external whenNotPaused nonReentrant {
        require(_address != address(0), "zero address");
        require(_amount > 0, "deposit more than 0");    
        require(!isClosePlan, 'already closed plan');
        require(minDeposit <= _amount && maxDeposit >= _amount, "check amount");        
        require(mapStaking[_msgSender()].length < 999, "exceeded max contract");

        require(block.timestamp >= enrollStartAt && enrollStartAt > 0, "not started enrollment");

        uint256 newTotal = totalEnrollments + _amount;

        if (targetDeposit > 0 && targetDeposit < newTotal) {
            revert("Plan Pool exceeded");
        }

        if (enrollPeriod > 0 && enrollEndAt() < block.timestamp) {
            revert("finished enrollment");
        }

        uint256 extoAllowance = extoInterface.allowance(_msgSender(), address(this));
        require(_amount <= extoAllowance, "check exto allowance");        
        require(extoInterface.transferFrom(_msgSender(), address(this), _amount), "Transfer failed");

        tempDeposits += (_amount - extoValue);
        totalDeposit += extoValue;
        
        totalEnrollments = newTotal;
        cntEnrollment++;

        if (isSingleContract && mapStaking[_msgSender()].length > 0) {
            Staking storage staking = mapStaking[_msgSender()][0];
            require(maxDeposit >= staking.amount + _amount, "check max deposit amount");
            staking.amount += _amount;
        } else {
            (, , int256 sumLatestRate) = getYieldRate();      
            mapStaking[_msgSender()].push(Staking({
                amount: _amount, 
                refund: 0,
                reward: 0,
                rewardAt: block.timestamp,
                referrer: _referrer,     
                latestRoi: sumLatestRate,
                flag: 0
            }));
        }

        mapDeposits[_msgSender()] += _amount;

        uint256 stakingLength = mapStaking[_msgSender()].length;

        emit Enrollment(_msgSender(), _amount, stakingLength, _referrer, block.timestamp);
    }

    function getUserStakings(address _user) external view returns (Staking[] memory) {
        return mapStaking[_user];
    }  

    function getUserStaking(address _user, uint256 _stakingIdx) external view returns(Staking memory) {
        require(_stakingIdx < mapStaking[_user].length, "Index out of bounds");
        return mapStaking[_user][_stakingIdx];
    }

    function forceRefundPlan(bool _canRefund) external onlyOwner {
        require(planStartAt == 0, "already plan started");        
        canRefund = _canRefund;
    }

    function allowRefundHolder(address _holder, uint256[] calldata _stakingIdx, uint256[] calldata _refund) external hasPermit {        
        uint256 len = _stakingIdx.length;
        uint256 sumRefund = 0;
        require(len > 0, "empty statking idxs ");

        for(uint256 i = 0; i < len; i++) {
            Staking storage staking = mapStaking[_holder][_stakingIdx[i]];
            require(staking.amount > 0, "Staking not found");                        
            require((staking.flag & IS_REFUNDED) == 0, "Already Refunded");            

            staking.flag |= CAN_REFUND;
            staking.refund = _refund[i];
            sumRefund += _refund[i];            
        }

        require(extoInterface.allowance(_msgSender(), address(this)) >= sumRefund, 'check exto allowance');
        require(extoInterface.transferFrom(_msgSender(), address(this), sumRefund), 'transferFrom failed');

        emit AllowRefund(_msgSender(), sumRefund, block.timestamp);
    }

    function refundStakings(uint256[] calldata _stakingIdx, uint256 _refund) external whenNotPaused nonReentrant {
      uint256 len = _stakingIdx.length;
      uint256 refund = 0;
      for(uint256 i = 0; i < len; i++) {
        require(_stakingIdx[i] < mapStaking[_msgSender()].length, "Index out of bounds");
        Staking storage staking = mapStaking[_msgSender()][_stakingIdx[i]];

        require(staking.amount > 0, "Staking not found");
        require(staking.refund > 0, "Not Approve Refund");        
        require(staking.flag & IS_PAUSED == 0, "PAUSED");
        require(canRefund || (staking.flag & CAN_REFUND != 0) || (staking.flag & IS_REFUNDED == 0), "Unable Refund");
        require(staking.flag & IS_LOCKED == 0, "Locked Staking");        

        refund += staking.refund;
        staking.flag |= IS_REFUNDED;
      }

      require(_refund == refund, "Not Match Amount");
      require(extoInterface.balanceOf(address(this)) >= refund, "insufficient EXTO");
      require(extoInterface.transfer(_msgSender(), refund), "EXTO refund failed");

      mapRefunds[_msgSender()] += refund;
      totalRefund += refund;

      emit Refunds(_msgSender(), refund, len, block.timestamp);
    }

    function refundStaking(uint256 _stakingIdx, uint256 _refund) external whenNotPaused nonReentrant {    
        require(_stakingIdx < mapStaking[_msgSender()].length, "Index out of bounds");
        Staking storage staking = mapStaking[_msgSender()][_stakingIdx];
        require(staking.amount > 0, "Staking not found");
        require(staking.refund > 0, "Not Approve Refund");            
        require(staking.refund == _refund, "Not Match Amount");
        require(staking.flag & IS_PAUSED == 0, "PAUSED");
        require(canRefund || (staking.flag & CAN_REFUND != 0) || (staking.flag & IS_REFUNDED == 0), "Unable Refund");
        require(staking.flag & IS_LOCKED == 0, "Locked Staking");
        require(extoInterface.balanceOf(address(this)) >= staking.refund, "Insufficient Balance");

        staking.flag |= IS_REFUNDED;
        mapRefunds[_msgSender()] += staking.refund;
        totalRefund += staking.refund;

        require(extoInterface.transfer(_msgSender(), staking.refund), "EXTO refund failed");

        emit Refund(_msgSender(), staking.refund, block.timestamp);
    }

    function setCreator(address _creator) external onlyOwner {
        creator = _creator;
    }

    function setOperator(address _operator) external onlyOwner {
        operator = _operator;
    }

    function setFeeRate(uint32 _feeRate) external onlyOwner {
      require(_feeRate <= 10000000, 'exceed 10%');
      feeRate = _feeRate;
    }

    function setPeriod(uint256 _planPeriod) public hasPermit {
        require(_planPeriod >= (28 days) || _planPeriod == 0, "plan at least 28 day");
        planPeriod = _planPeriod;
    }

    function setRewardTerm(uint256 __rewardTerm) public onlyOwner {
        require(__rewardTerm >= 28 days || __rewardTerm == 0, "plan at least 28 day");
        rewardTerm = __rewardTerm;      
    }

    function setPlanLockupPeriod(uint256 _planLockupPeriod) public hasPermit {
        planLockupPeriod = _planLockupPeriod;
    }

    function setIndivReward(bool _isIndivReward) external onlyOwner {
      isIndivReward = _isIndivReward;
    }    

    modifier hasPermit() {      
        require(msg.sender == operator || msg.sender == creator || msg.sender == owner(), "not permitted");
        _;
    }

    function transferDeposits(uint256 _tempDeposits, address _creator) external hasPermit nonReentrant whenNotPaused {
        require(tempDeposits >= _tempDeposits, "check amount");
        require(creator == _creator, "check creator");        
        tempDeposits -= _tempDeposits;
        require(extoInterface.transfer(creator, _tempDeposits), "Transfer failed");
    }

    function getRewardable(uint256 _stakingIdx) external view  returns (uint256) {
        require(_stakingIdx < mapStaking[_msgSender()].length, "Index out of bounds");
        Staking storage staking = mapStaking[_msgSender()][_stakingIdx];      
        (, , int256 sumLatestRate) = getYieldRate();
        int256 _defRate = sumLatestRate - staking.latestRoi;
        if (_defRate < 0) _defRate = 0;
        uint256 reward = (staking.amount * uint256(_defRate)) / 1e8; 
        return reward;
    } 

    function forceClosePlan() external onlyOwner whenNotPaused nonReentrant {
        require(!isClosePlan, 'already closed plan');

        isClosePlan = true;

        emit StatusPlan(bytes32('FINISH'), block.timestamp);
    }

    function enrollPlanByBSC(address[] calldata _address, uint256[] calldata _amount, address[] calldata _referrer) external hasPermit nonReentrant {        
        require(!isClosePlan, 'already closed plan');

        uint256 len = _address.length;
        uint256 sumAmount = 0;

        require((len < 256) && (len == _amount.length) && (len == _referrer.length), "lengths do not length");        

        for(uint i = 0; i < len; i++) {
          require(_address[i] != address(0), "zero address");
          require(_amount[i] > 0, "deposit more than 0");
          require(mapStaking[_address[i]].length < 999, "exceeded max contract");
          sumAmount += _amount[i];
        }

        require(block.timestamp >= enrollStartAt && enrollStartAt > 0, "not started enrollment");

        if (targetDeposit > 0 && targetDeposit < totalEnrollments + sumAmount) {
            revert("Plan Pool exceeded");
        }

        uint256 extoAllowance = extoInterface.allowance(_msgSender(), address(this));
        require(sumAmount <= extoAllowance, "check exto allowance");        
        require(extoInterface.transferFrom(_msgSender(), address(this), sumAmount), "Transfer failed");        

        tempDeposits += (sumAmount - extoValue);
        totalDeposit += extoValue;

        totalEnrollments += sumAmount;       
        cntEnrollment += len;  
        
        (, , int256 sumLatestRate) = getYieldRate();      

        for(uint i = 0; i < len; i++) {        

            uint mapLen = mapStaking[_address[i]].length;

            if (isSingleContract && mapLen > 0) {
                Staking storage staking = mapStaking[_address[i]][0];
                require(maxDeposit >= staking.amount + _amount[i], "check max deposit amount");
                staking.amount += _amount[i];
            } else {
                mapStaking[_address[i]].push(Staking({
                    amount: _amount[i], 
                    refund: 0,
                    reward: 0,
                    rewardAt: block.timestamp,
                    referrer: _referrer[i],     
                    latestRoi: sumLatestRate,
                    flag: 0
                }));
                mapLen++;
            }

          mapDeposits[_address[i]] += _amount[i];

          emit Enrollment(_address[i], _amount[i], mapLen, _referrer[i], block.timestamp);
        }        
    }

    function setDepositAmount(uint256 _minDeposit, uint256 _maxDeposit) external hasPermit nonReentrant {        
        if (_minDeposit > 0) minDeposit = _minDeposit;
        if (_maxDeposit > 0) maxDeposit = _maxDeposit;

        require(minDeposit <= maxDeposit, "check min, max value");
    }

    function setTargetDeposit(uint256 _targetDeposit) external onlyOwner {
      targetDeposit = _targetDeposit;
    }

    function resetDeposit(address _old, address _new) external onlyOwner {
      require(mapStaking[_old].length > 0, "No stakings for old address");
      require(mapStaking[_new].length == 0, "has stakings for new address");

      for (uint i = 0; i < mapStaking[_old].length; i++) {
          mapStaking[_new].push(mapStaking[_old][i]);
      }

      mapDeposits[_new] += mapDeposits[_old];
      mapRewards[_new] += mapRewards[_old];
      mapClaimable[_new] += mapClaimable[_old];
      mapRefunds[_new] += mapRefunds[_old];

      delete mapStaking[_old];
      mapDeposits[_old] = 0;
      mapRewards[_old] = 0;
      mapClaimable[_old] = 0;
      mapRefunds[_old] = 0;

      emit ChangeAddress(_old, _new, block.timestamp);
    }

    function enrollPlanWithReferrer(address _address, uint256 _amount, address _referrer) external whenNotPaused nonReentrant {
        require(_address != address(0), "zero address");
        require(_amount > 0, "deposit more than 0");    
        require(!isClosePlan, 'already closed plan');
        require(minDeposit <= _amount && maxDeposit >= _amount, "check amount");        
        require(mapStaking[_msgSender()].length < 999, "exceeded max contract");

        require(block.timestamp >= enrollStartAt && enrollStartAt > 0, "not started enrollment");

        uint256 newTotal = totalEnrollments + _amount;

        if (targetDeposit > 0 && targetDeposit < newTotal) {
            revert("Plan Pool exceeded");
        }

        if (enrollPeriod > 0 && enrollEndAt() < block.timestamp) {
            revert("finished enrollment");
        }

        uint256 extoAllowance = extoInterface.allowance(_msgSender(), address(this));
        require(_amount <= extoAllowance, "check exto allowance");        
        require(extoInterface.transferFrom(_msgSender(), address(this), _amount), "Transfer failed");

        tempDeposits += (_amount - extoValue);
        totalDeposit += extoValue;
        
        totalEnrollments = newTotal;
        cntEnrollment++;

        if (isSingleContract && mapStaking[_msgSender()].length > 0) {
            Staking storage staking = mapStaking[_msgSender()][0];
            require(maxDeposit >= staking.amount + _amount, "check max deposit amount");
            staking.amount += _amount;
        } else {
            (, , int256 sumLatestRate) = getYieldRate();      
            mapStaking[_msgSender()].push(Staking({
                amount: _amount, 
                refund: 0,
                reward: 0,
                rewardAt: block.timestamp,
                referrer: _referrer,     
                latestRoi: sumLatestRate,
                flag: 0
            }));
        }

        if (_referrer != address(0) && planPeriod > 0) 
          extoTokenMiles.enrollRewardToReferrer(_msgSender(), _referrer, _amount, planPeriod);

        mapDeposits[_msgSender()] += _amount;

        uint256 stakingLength = mapStaking[_msgSender()].length;

        emit Enrollment(_msgSender(), _amount, stakingLength, _referrer, block.timestamp);
    }


    function claimRefundToHolder(uint256 _stakingIdx, uint256 _reward, uint256 _refund) external whenNotPaused nonReentrant {    
        require(_stakingIdx < mapStaking[_msgSender()].length, "Index out of bounds");
        Staking storage staking = mapStaking[_msgSender()][_stakingIdx];
        require(staking.amount > 0, "staking not found");
        require(staking.flag & IS_CLOSED == 0, "closed staking");
        require(staking.rewardAt + rewardTerm <= block.timestamp, "not a time to reward");
        require(planStartAt + planPeriod <= block.timestamp, "not a time to release");
        require(planStartAt > 0 && planStartAt <= block.timestamp, "not started plan");
        require(staking.amount == _refund, "check refund amount");

        require(isIndivReward, "use individual rewards");    

        (, , int256 sumLatestRate) = getYieldRate();

        require(staking.latestRoi != sumLatestRate, 'Nothing to reward');
        int256 _defRate = sumLatestRate - staking.latestRoi;        
        require(_defRate > 0, 'zero ROI');

        uint256 reward = (staking.amount * uint256(_defRate)) / 1e8;            

        require(reward == _reward, "Check ROI");

        uint32 opFee = (feeRate == 0)?10_00_0000:feeRate;
        extoTokenMiles.releaseMilesToHolder(_msgSender(), creator, reward, opFee);

        staking.refund += _refund;
        require(extoInterface.balanceOf(address(this)) >= staking.refund, "Insufficient Balance");
        
        staking.flag |= IS_REFUNDED;
        staking.flag |= IS_CLOSED;
        mapRefunds[_msgSender()] += staking.refund;
        totalRefund += staking.refund;

        require(extoInterface.transfer(_msgSender(), staking.refund), "EXTO refund failed");

        mapRewards[_msgSender()] += reward;
        totalRewards += reward;
        staking.reward += reward;
        staking.rewardAt = block.timestamp;
        staking.latestRoi = sumLatestRate;

        emit ClaimRefundToHolder(_msgSender(), _reward, _defRate, _refund, block.timestamp);
    }

}

@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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.
 *
 * The initial owner is set to the address provided by the deployer. 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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        OwnableStorage storage $ = _getOwnableStorage();
        return $._owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(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) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @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);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

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

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

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

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

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

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

@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 50,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.