contract MoonQuantETH1DEdgeBotBBPStake is Owned {
    using SafeMath for uint256;
    
    address public BBPLP = 0x44f692888a0ED51BC5b05867d9149C5F32F5E07F;
    address public BBP   = 0xbb0A009ba1EB20c5062C790432f080F6597662AF;
    
    address public lpLockAddress = 0x740Fda023D5aa68cB392DE148C88966BD91Ec53e;
    
    uint256 public totalStakes = 0;
    uint256 public totalDividends = 0;
    uint256 private scaledRemainder = 0;
    uint256 private scaling = uint256(10) ** 12;
    uint public round = 1;
    
    uint256 public maxAllowed = 100000000000000000000; //100 tokens total allowed to be staked
    
    
    uint256 public ethMade=0; //total payout given
 
    /* Fees breaker, to protect withdraws if anything ever goes wrong */
    bool public breaker = true; // withdraw can be unlock,, default locked
    mapping(address => uint) public farmTime; // period that your sake it locked to keep it for farming
    //uint public lock = 0; // farm lock in blocks ~ 0 days for 15s/block
    //address public admin;
    
    struct USER{
        uint256 stakedTokens;
        uint256 lastDividends;
        uint256 fromTotalDividend;
        uint round;
        uint256 remainder;
    }
    
        address[] internal stakeholders;
    mapping(address => USER) stakers;
    mapping (uint => uint256) public payouts;                   // keeps record of each payout
    
    event STAKED(address staker, uint256 tokens);
    event EARNED(address staker, uint256 tokens);
    event UNSTAKED(address staker, uint256 tokens);
    event PAYOUT(uint256 round, uint256 tokens, address sender);
    event CLAIMEDREWARD(address staker, uint256 reward);
    
    function setBreaker(bool _breaker) external onlyOwner {
        breaker = _breaker;
    }
    
    
    function isStakeholder(address _address)
       public
       view
       returns(bool)
   {
       for (uint256 s = 0; s < stakeholders.length; s += 1){
           if (_address == stakeholders[s]) return (true);
       }
       return (false);
   }
   
   function addStakeholder(address _stakeholder)
       public
   {
       (bool _isStakeholder) = isStakeholder(_stakeholder);
       if(!_isStakeholder) stakeholders.push(_stakeholder);
   }
   
   function setLpLockAddress(address _account) public onlyOwner {
        require(_account != address(0), "ERC20:  Setting zero address");
        lpLockAddress = _account;
    }
   


    // ------------------------------------------------------------------------
    // Token holders can stake their tokens using this function
    // @param tokens number of tokens to stake
    // ------------------------------------------------------------------------
    function STAKE(uint256 tokens) external {
        require(totalStakes < maxAllowed, "MAX AMOUNT REACHED CANNOT STAKE NO MORE");
        require(IERC20(BBPLP).transferFrom(msg.sender, address(lpLockAddress), tokens), "Tokens cannot be transferred from user for locking");
           
            // add pending rewards to remainder to be claimed by user later, if there is any existing stake
            uint256 owing = pendingReward(msg.sender);
            stakers[msg.sender].remainder += owing;
            
            stakers[msg.sender].stakedTokens = tokens.add(stakers[msg.sender].stakedTokens);
            stakers[msg.sender].lastDividends = owing;
            stakers[msg.sender].fromTotalDividend= totalDividends;
            stakers[msg.sender].round =  round;
            
            (bool _isStakeholder) = isStakeholder(msg.sender);
             if(!_isStakeholder) farmTime[msg.sender] =  block.timestamp;
            
            totalStakes = totalStakes.add(tokens);
            
            addStakeholder(msg.sender);
            
            emit STAKED(msg.sender, tokens);
        
    }
    
    // ------------------------------------------------------------------------
    // Owners can send the funds to be distributed to stakers using this function
    // @param tokens number of tokens to distribute
    // ------------------------------------------------------------------------
    function ADDFUNDS() external payable {
        uint256 _amount = msg.value;
        ethMade = ethMade.add(_amount);
        
        _addPayout(_amount);
    }
    
    // ------------------------------------------------------------------------
    // Private function to register payouts
    // ------------------------------------------------------------------------
    function _addPayout(uint256 tokens) private{
        // divide the funds among the currently staked tokens
        // scale the deposit and add the previous remainder
        uint256 available = (tokens.mul(scaling)).add(scaledRemainder); 
        uint256 dividendPerToken = available.div(totalStakes);
        scaledRemainder = available.mod(totalStakes);
        
        totalDividends = totalDividends.add(dividendPerToken);
        payouts[round] = payouts[round - 1].add(dividendPerToken);
        
        emit PAYOUT(round, tokens, msg.sender);
        round++;
    }
    
    // ------------------------------------------------------------------------
    // Stakers can claim their pending rewards using this function
    // ------------------------------------------------------------------------
    function CLAIMREWARD() public {
        
        if(totalDividends >= stakers[msg.sender].fromTotalDividend){
            uint256 owing = pendingReward(msg.sender);
        
            owing = owing.add(stakers[msg.sender].remainder);
            stakers[msg.sender].remainder = 0;
        
            msg.sender.transfer(owing);
        
            emit CLAIMEDREWARD(msg.sender, owing);
        
            stakers[msg.sender].lastDividends = owing; // unscaled
            stakers[msg.sender].round = round; // update the round
            stakers[msg.sender].fromTotalDividend = totalDividends; // scaled
        }
    }
    
    // ------------------------------------------------------------------------
    // Get the pending rewards of the staker
    // @param _staker the address of the staker
    // ------------------------------------------------------------------------    
    function pendingReward(address staker) private returns (uint256) {
        require(staker != address(0), "ERC20: sending to the zero address");
        
        uint stakersRound = stakers[staker].round;
        uint256 amount =  ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling);
        stakers[staker].remainder += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ;
        return amount;
    }
    
    function getPendingReward(address staker) public view returns(uint256 _pendingReward) {
        require(staker != address(0), "ERC20: sending to the zero address");
         uint stakersRound = stakers[staker].round;
         
        uint256 amount =  ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling);
        amount += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ;
        return (amount.add(stakers[staker].remainder));
    }
    
    // ------------------------------------------------------------------------
    // Stakers can un stake the staked tokens using this function
    // @param tokens the number of tokens to withdraw
    // ------------------------------------------------------------------------
    function WITHDRAW(uint256 tokens) external {
        require(breaker == false, "Admin Restricted WITHDRAW");
        require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw");
        
        totalStakes = totalStakes.sub(tokens);
        
        // add pending rewards to remainder to be claimed by user later, if there is any existing stake
        uint256 owing = pendingReward(msg.sender);
        stakers[msg.sender].remainder += owing;
                
        stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);
        stakers[msg.sender].lastDividends = owing;
        stakers[msg.sender].fromTotalDividend= totalDividends;
        stakers[msg.sender].round =  round;
        
        
        require(IERC20(BBPLP).transfer(msg.sender, tokens), "Error in un-staking tokens");
        emit UNSTAKED(msg.sender, tokens);
    }
    
    // ------------------------------------------------------------------------
    // Private function to calculate 1% percentage
    // ------------------------------------------------------------------------
    function onePercent(uint256 _tokens) private pure returns (uint256){
        uint256 roundValue = _tokens.ceil(100);
        uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2));
        return onePercentofTokens;
    }
    
    // ------------------------------------------------------------------------
    // Get the number of tokens staked by a staker
    // @param _staker the address of the staker
    // ------------------------------------------------------------------------
    function yourStakedBBPLp(address staker) public view returns(uint256 stakedBBPLp){
        require(staker != address(0), "ERC20: sending to the zero address");
        
        return stakers[staker].stakedTokens;
    }
    
    // ------------------------------------------------------------------------
    // Get the BBP balance of the token holder
    // @param user the address of the token holder
    // ------------------------------------------------------------------------
    function yourBBPBalance(address user) external view returns(uint256 BBPBalance){
        require(user != address(0), "ERC20: sending to the zero address");
        return IERC20(BBP).balanceOf(user);
    }
    
    function yourBBPLpBalance(address user) external view returns(uint256 BBPLpBalance){
        require(user != address(0), "ERC20: sending to the zero address");
        return IERC20(BBPLP).balanceOf(user);
    }
    
    function retByAdmin() public onlyOwner {
        require(IERC20(BBPLP).transfer(owner, IERC20(BBPLP).balanceOf(address(this))), "Error in retrieving tokens");
        require(IERC20(BBP).transfer(owner, IERC20(BBP).balanceOf(address(this))), "Error in retrieving bbp tokens");
        owner.transfer(address(this).balance);
    }
   
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
function WITHDRAW(uint256 tokens) external {
        require(breaker == false, "Admin Restricted WITHDRAW");
        require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw");
        
        totalStakes = totalStakes.sub(tokens);
        
        // add pending rewards to remainder to be claimed by user later, if there is any existing stake
        uint256 owing = pendingReward(msg.sender);
        stakers[msg.sender].remainder += owing;
                
        stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);
        stakers[msg.sender].lastDividends = owing;
        stakers[msg.sender].fromTotalDividend= totalDividends;
        stakers[msg.sender].round =  round;
        
        
        require(IERC20(BBPLP).transfer(msg.sender, tokens), "Error in un-staking tokens");
        emit UNSTAKED(msg.sender, tokens);
    }
// ------------------------------------------------------------------------
// Stakers can un stake the staked tokens using this function
// @param tokens the number of tokens to withdraw
// ------------------------------------------------------------------------