contract StakeRewarder is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;
    
    // Info of each user.
    struct UserInfo {
        uint256 amount;     // Quantity of tokens the user has staked.
        uint256 rewardDebt; // Reward debt. See explanation below.
        // We do some fancy math here. Basically, any point in time, the
        // amount of rewards entitled to a user but is pending to be distributed is:
        //
        //   pendingReward = (stakedAmount * pool.accPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws tokens in a pool:
        //   1. The pool's `accPerShare` (and `lastRewardBlock`) gets updated.
        //   2. User receives the pending reward sent to their address.
        //   3. User's `amount` gets updated.
        //   4. User's `rewardDebt` gets updated.
    }
    
    /**
     * @dev Info of each staking token
     */
    struct PoolInfo {
        IERC20 token;             // Address of the token contract.
        uint256 allocPoint;       // Allocation points assigned to this pool.
        uint256 lastRewardBlock;  // Last block number rewarded.
        uint256 accPerShare;      // Accumulated rewards per share (times 1e12).
    }
    
    // The rewards token
    IERC20 rewardToken;
    
    // Reward tokens issued per block.
    uint256 public rewardPerBlock;
    
    // Info of each pool.
    PoolInfo[] public poolInfo;
    
    // Info of each user that stakes tokens.
    mapping(uint256 => mapping(address => UserInfo)) public userInfo;
    
    // Underpaid rewards owed to a user.
    mapping(address => uint256) public underpayment;
    
    // Total allocation points. Must be the sum of all allocation points across all staking tokens.
    uint256 public totalAllocPoint = 0;
    
    // The block number when staking starts.
    uint256 public startBlock;
    
    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event EmergencyReclaimRewards(address indexed user, uint256 amount);
    event EmergencyWithdraw(
        address indexed user,
        uint256 indexed pid,
        uint256 amount
    );

    constructor(
        IERC20 _rewardToken,
        uint256 _rewardPerBlock,
        uint256 _startBlock
    ) {
        rewardToken = _rewardToken;
        rewardPerBlock = _rewardPerBlock;
        startBlock = _startBlock;
    }

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    /**
     * @dev Adds a new token to the stack. Can only be called by the owner.
     * WARNING: DO NOT ADD TOKENS MORE THAN ONCE! Rewards will be messed up.
     */
    function add(
        uint256 _allocPoint,
        IERC20 _token,
        bool _withUpdate
    ) public onlyOwner {
        if (_withUpdate) {
            refreshPools();
        }

        uint256 lastRewardBlock =
            block.number > startBlock ? block.number : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(
            PoolInfo({
                token: _token,
                allocPoint: _allocPoint,
                lastRewardBlock: lastRewardBlock,
                accPerShare: 0
            })
        );
    }

    /**
     * @dev Update the given staking pool's allocation points. Can only be called by the owner.
     */ 
    function set(
        uint256 _pid,
        uint256 _allocPoint,
        bool _shouldUpdate
    ) public onlyOwner {
        if (_shouldUpdate) {
            refreshPools();
        }
        
        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
            _allocPoint
        );

        poolInfo[_pid].allocPoint = _allocPoint;
    }
    
    /**
     * @dev Update the reward per block. Can only be called by the owner.
     */
    function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner {
        rewardPerBlock = _rewardPerBlock;
    }

    /**
     * @dev Return reward multiplier over the given _from to _to block.
     */
    function getMultiplier(uint256 _from, uint256 _to)
        public
        pure
        returns (uint256)
    {
        return _to.sub(_from);
    }

    /**
     * @dev View function to see pending rewards for an address (not for contract use).
     */
    function pendingRewards(uint256 _pid, address _user)
        external
        view
        returns (uint256)
    {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accPerShare = pool.accPerShare;
        uint256 tokenSupply = pool.token.balanceOf(address(this));
        
        if (block.number > pool.lastRewardBlock && tokenSupply != 0) {
            uint256 multiplier =
                getMultiplier(pool.lastRewardBlock, block.number);
            uint256 reward =
                multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(
                    totalAllocPoint
                );
            accPerShare = accPerShare.add(
                reward.mul(1e12).div(tokenSupply)
            );
        }

        return user.amount.mul(accPerShare).div(1e12).sub(user.rewardDebt);
    }

    /**
     * @dev Update all pools. Callable by anyone. Could be gas intensive.
     */
    function refreshPools() public {
        uint256 length = poolInfo.length;
        for (uint256 pid = 0; pid < length; ++pid) {
            updatePool(pid);
        }
    }

    /**
     * @dev Update rewards of the given pool to be up-to-date.
     */
    function updatePool(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];

        if (block.number <= pool.lastRewardBlock) {
            return;
        }

        uint256 tokenSupply = pool.token.balanceOf(address(this));

        if (tokenSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }

        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 reward =
            multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(
                totalAllocPoint
            );

        pool.accPerShare = pool.accPerShare.add(
            reward.mul(1e12).div(tokenSupply)
        );

        pool.lastRewardBlock = block.number;
    }

    /**
     * @dev Stake tokens to earn a share of rewards.
     */
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        
        require(_amount > 0, "deposit: only non-zero amounts allowed");
        
        // make sure the pool is up-to-date
        updatePool(_pid);
        
        // deliver any pending rewards
        if (user.amount > 0) {
            uint256 pending =
                user.amount.mul(pool.accPerShare).div(1e12).sub(
                    user.rewardDebt
                ).add(underpayment[msg.sender]);
            
            uint256 payout = safelyDistribute(msg.sender, pending);
            if (payout < pending) {
                underpayment[msg.sender] = pending.sub(payout);
            } else {
                underpayment[msg.sender] = 0;
            }
        }
        
        // pull in user's staked assets
        pool.token.safeTransferFrom(
            address(msg.sender),
            address(this),
            _amount
        );
        
        // update user's deposit and reward info
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12);
        
        emit Deposit(msg.sender, _pid, _amount);
    }

    /**
     * @dev Withdraw staked tokens and any pending rewards.
     */
    function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        
        require(_amount > 0, "withdraw: only non-zero amounts allowed");
        require(user.amount >= _amount, "withdraw: amount too large");
        
        // make sure the pool is up-to-date
        updatePool(_pid);
        
        // calculate the pending reward
        uint256 pending =
            user.amount.mul(pool.accPerShare).div(1e12).sub(
                user.rewardDebt
            ).add(underpayment[msg.sender]);

        // send the rewards out
        uint256 payout = safelyDistribute(msg.sender, pending);
        if (payout < pending) {
            underpayment[msg.sender] = pending.sub(payout);
        } else {
            underpayment[msg.sender] = 0;
        }
        
        // update the user's deposit and reward info
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12);
        
        // send back the staked assets
        pool.token.safeTransfer(address(msg.sender), _amount);
        
        emit Withdraw(msg.sender, _pid, _amount);
    }

    /**
     * @dev Withdraw staked tokens and forego any unclaimed rewards. This is a fail-safe.
     */
    function emergencyWithdraw(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        uint256 amount = user.amount;
        
        // reset everything to zero
        user.amount = 0;
        user.rewardDebt = 0;
        underpayment[msg.sender] = 0;
        
        // send back the staked assets
        pool.token.safeTransfer(address(msg.sender), amount);
        emit EmergencyWithdraw(msg.sender, _pid, amount);
    }

    /**
     * @dev Safely distribute at most the amount of tokens in holding.
     */
    function safelyDistribute(address _to, uint256 _amount) internal returns (uint256 amount) {
        uint256 available = rewardToken.balanceOf(address(this));
        amount = _amount > available ? available : _amount;
        rewardToken.transfer(_to, amount);
        return amount;
    }
    
    /**
     * @dev Withdraw undisbursed rewards tokens. This is a fail-safe.
     */
    function emergencyReclaimRewards(uint256 _amount) public onlyOwner {
        if (_amount == 0) {
            _amount = rewardToken.balanceOf(address(this));
        }
        
        rewardToken.transfer(msg.sender, _amount);
        emit EmergencyReclaimRewards(msg.sender, _amount);
    }
}
/**
 * @title StakeRewarder
 * @dev This contract distributes rewards to depositors of supported tokens.
 * It's based on Sushi's MasterChef v1, but notably only serves what's already
 * available: no new tokens can be created. It's just a restaurant, not a farm.
 */
function emergencyReclaimRewards(uint256 _amount) public onlyOwner {
    if (_amount == 0) {
        _amount = rewardToken.balanceOf(address(this));
    }
        
    rewardToken.transfer(msg.sender, _amount);
    emit EmergencyReclaimRewards(msg.sender, _amount);
}

/**
 * @dev Withdraw undisbursed rewards tokens. This is a fail-safe.
 */