// Contract: TierSystem
// Target function: function stake(uint _amount, address _invite) external
/**
 *Submitted for verification at BscScan.com on 2021-11-09
*/

/**
 *Submitted for verification at BscScan.com on 2021-10-06
*/

/**
 *Submitted for verification at polygonscan.com on 2021-07-19
*/

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


library SafeMath {
    /**
     * @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) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @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 sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     * - Subtraction cannot overflow.
     *
     * _Available since v2.4.0._
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

    /**
     * @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) {
        // 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 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts 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.
     *
     * _Available since v2.4.0._
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        // Solidity only automatically asserts when dividing by 0
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts 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 mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message 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.
     *
     * _Available since v2.4.0._
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

contract Ownable {
    address public owner;
    address public proposedOwner;
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);


    /**
    * @dev The Ownable constructor sets the original `owner` of the contract to the sender
    * account.
    */
    constructor() {
        owner = msg.sender;
    }

    /**
    * @dev Throws if called by any account other than the owner.
    */
    modifier onlyOwner() {
        require(msg.sender == owner, "Has to be owner");
        _;
    }

    function transferOwnership(address _proposedOwner) public onlyOwner {
        require(msg.sender != _proposedOwner, "Has to be diff than current owner");
        proposedOwner = _proposedOwner;
    }

    function claimOwnership() public {
        require(msg.sender == proposedOwner, "Has to be the proposed owner");
        emit OwnershipTransferred(owner, proposedOwner);
        owner = proposedOwner;
        proposedOwner = address(0);
    }
}

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);
}
abstract contract Context {
  // Empty internal constructor, to prevent people from mistakenly deploying
  // an instance of this contract, which should be used via inheritance.
 

  function _msgSender() internal view returns (address payable) {
    return payable(msg.sender);
  }

  function _msgData() internal view returns (bytes memory) {
    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
    return msg.data;
  }
}

// user can stake HDAO to obtain memberships and upgrade to topper tiers.
// stake can generate interest with a certain APY, as well as referal dynamic rewards

contract TierSystem is Ownable, Context{
    using SafeMath for uint;
    bool public isAudit=false;
    address public HDAO;
    uint public rate;   // yield 
    uint[10] public dynamicRate;
    uint public period; // calm down period
    bool public isReferMode;
    uint public referMode; // two types of refer modes
    uint[4] public threshold;  
    
    enum Tier{None,Bronze,Silver,Gold,Platinum}
    
    // statistics
    uint public totalStake;  // total amount at stake
    uint public totalFrozen; // total amount at frozen status
    uint public withdrawn; // total amount of stake withdrawn
    
    uint public staticAccrued;
    uint public dynamicAccrued;
    
    uint public staticWithdrawn;
    uint public dynamicWithdrawn;
    
    mapping(Tier=>uint) public tierInfo; // members of each tier

    
    struct UserInfo{
        uint deposit_times;
        address invite;
        uint stake_amount;  // real time on stake 
        uint frozen_amount; // unstake amount at frozen status
        uint lastTime; // stake timestamp used for interest calculation, will update at each operation
        uint countdown; // timestamp at unstake, used for calculate frozen period
        
        uint intAccrued; // static interest rewards
        uint dynamicRewards; 
        Tier tier;
        uint num_invitor; // number of people this address invited
        
    }
    
    mapping(address=>UserInfo) public userInfo; 
    
    
    event ReferMode(bool status, uint mode);
    event Stake(address indexed user, uint amount, uint timestamp);
    event Unstake(address indexed user, uint amount, uint timestamp);
    event Withdraw(address indexed user, uint amount, uint timestamp);
    
    constructor(){
        // initialize tier thresholds

        owner = _msgSender();
        userInfo[address(this)].deposit_times = 1;
        period = 3 days;
        rate = 18;
        
        threshold[0] = 10000 * 1e18;
        threshold[1] = 100000 * 1e18;
        threshold[2] = 500000 * 1e18;
        threshold[3] = 1000000 * 1e18;
        
        
        dynamicRate[0] = 30;
        dynamicRate[1] = 20;
        dynamicRate[2] = 10;
        dynamicRate[3] = 5;
        dynamicRate[4] = 5;
        dynamicRate[5] = 3;
        dynamicRate[6] = 3;
        dynamicRate[7] = 2;
        dynamicRate[8] = 2;
        dynamicRate[9] = 2;
        
    }
    
    function setAudit()external onlyOwner{
        isAudit = true;
    }
    function getUserTier(address _user) external view returns(uint8){
        return uint8(userInfo[_user].tier);
    }
    
    function getUserStake(address _user)external view returns(uint){
        return userInfo[_user].stake_amount;
    }
    
    function setHDAO(address addr) external onlyOwner{
        HDAO = addr;
    }
    /*
    * set thresholds for each tier level
    */
    function setThreshold(uint[4] memory ts) external onlyOwner{
        for(uint i=0;i<4; i++){
            threshold[i] = ts[i];
        }
    }
    
    /*
     * set calm down period determining unstake forzen time
    */
    function setPeriod(uint p) external onlyOwner{
        period = p;
    }
    
    /*
    * set static yield rate, as percentage
    */
    function setRate(uint r) external onlyOwner{
        rate = r;
    }
    
    /*
    * switch on or off for referal mode
    */
    function setReferMode(bool s, uint mode) external onlyOwner{
        require(mode==1 || mode==2,"only two mode options");
        isReferMode = s;
        referMode = mode;
        emit ReferMode(s, mode);
    }