contract TRYFarming is Ownable {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // Info of each user.
    struct UserInfo {
        uint256 amount;     // How many LP tokens the user has provided.
        uint256 rewardDebt; // Reward debt. See explanation below.
    }

    // Info of each pool.
    struct PoolInfo {
        IERC20 lpToken;           // Address of LP token contract.
        uint256 allocPoint;       // How many allocation points assigned to this pool. FaasToken to distribute per block.
        uint256 lastRewardBlock;  // Last block number that FaasToken distribution occurs.
        uint256 accFAASPerShare; // Accumulated FaasToken per share, times 1e12. See below.
    }


    FEG public FAASToken;    // The FEG TOKEN!
    address public devaddr;    // Dev address.

    mapping(address => bool) public lpTokenExistsInPool;    // Track all added pools to prevent adding the same pool more then once.
    mapping (uint256 => mapping (address => UserInfo)) public userInfo;    // Info of each user that stakes LP tokens.

    uint256 public totalAllocPoint = 0;    // Total allocation points. Must be the sum of all allocation points in all pools.

    uint256 public constant startBlock = 12006620;    // The block number when FaasToken mining starts.
    uint256 public bonusEndBlock = 12006620;

    uint256 public constant DEV_TAX = 5;
    uint256 public constant BONUS_MULTIPLIER = 1;

	uint256 public faasPerBlock = 128e15;

    PoolInfo[] public poolInfo;    // Info of each pool.

    event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
    event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);

    modifier onlyDev() {
        require(devaddr == _msgSender(), "not dev");
        _;
    }

    constructor(
        FEG _FAASToken,
        address _devaddr
    ) public {
        FAASToken = _FAASToken;
        devaddr = _devaddr;
    }

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

    // Add a new lp to the pool. Can only be called by the owner.
    function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
        require(!lpTokenExistsInPool[address(_lpToken)], "MasterChef: LP Token Address already exists in pool");
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: lastRewardBlock,
            accFAASPerShare: 0
        }));

        lpTokenExistsInPool[address(_lpToken)] = true;
    }

    function updateDevAddress(address _devAddress) public onlyDev {
        devaddr = _devAddress;
    }

    // Add a pool manually for pools that already exists, but were not auto added to the map by "add()".
    function updateLpTokenExists(address _lpTokenAddr, bool _isExists) external onlyOwner {
        lpTokenExistsInPool[_lpTokenAddr] = _isExists;
    }

    // Update the given pool's FaasToken allocation point. Can only be called by the owner.
    function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
        poolInfo[_pid].allocPoint = _allocPoint;
    }

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
        if (_to <= bonusEndBlock) {
            return _to.sub(_from).mul(BONUS_MULTIPLIER);
        } else if (_from >= bonusEndBlock) {
            return _to.sub(_from);
        } else {
            return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
                _to.sub(bonusEndBlock)
            );
        }
    }

    // View function to see pending FaasToken on frontend.
    function pendingFAAS(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accFAASPerShare = pool.accFAASPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 blocksToReward = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 faasReward = blocksToReward.mul(faasPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            // Check if rewards are higher than the supply left
            uint256 SupplyLeft = FAASToken.balanceOf(address(this));
            if (faasReward >= SupplyLeft) {
                faasReward = SupplyLeft;
            }
            accFAASPerShare = accFAASPerShare.add(faasReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accFAASPerShare).div(1e12).sub(user.rewardDebt);
    }

    // Update reward variables for all pools. Be careful of gas spending!
    function massUpdatePools() public {
        uint256 length = poolInfo.length;
        for (uint256 pid = 0; pid < length; ++pid) {
            updatePool(pid);
        }
    }

    // Update reward variables 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;
        }
        
        // Stop update if there's no token left to distribute
        uint256 SupplyLeft = FAASToken.balanceOf(address(this));
        if (SupplyLeft == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }

        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        
        // Check how many blocks have to be rewarded since the last pool update
        uint256 blocksToReward = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 faasReward = blocksToReward.mul(faasPerBlock).mul(pool.allocPoint).div(totalAllocPoint);

        pool.accFAASPerShare = pool.accFAASPerShare.add(faasReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to FarmingBad for FaasToken allocation.
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accFAASPerShare).div(1e12).sub(user.rewardDebt);
            if(pending > 0) {
                safeFaasTransfer(msg.sender, pending);
            }
        }
        if(_amount > 0) {
            uint256 _taxAmount = _amount.mul(DEV_TAX).div(100);
            _amount = _amount.sub(_taxAmount);
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            pool.lpToken.safeTransferFrom(address(msg.sender), address(devaddr), _taxAmount);
            user.amount = user.amount.add(_amount);
        }
        user.rewardDebt = user.amount.mul(pool.accFAASPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from FarmingBad.
    function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        uint256 pending = user.amount.mul(pool.accFAASPerShare).div(1e12).sub(user.rewardDebt);
        if(pending > 0) {
            safeFaasTransfer(msg.sender, pending);
        }
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        }
        user.rewardDebt = user.amount.mul(pool.accFAASPerShare).div(1e12);
        emit Withdraw(msg.sender, _pid, _amount);
        
    }

    // Withdraw without caring about rewards. EMERGENCY ONLY.
    function emergencyWithdraw(uint256 _pid) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        uint256 amount = user.amount;
        user.amount = 0;
        user.rewardDebt = 0;
        pool.lpToken.safeTransfer(address(msg.sender), amount);
        emit EmergencyWithdraw(msg.sender, _pid, amount);
    }

    // Safe FAAS Token transfer function, just in case if rounding error causes pool to not have enough BPTs.
    function safeFaasTransfer(address _to, uint256 _amount) internal {
        uint256 FAASBal = FAASToken.balanceOf(address(this));
        if (_amount > FAASBal) {
            FAASToken.transfer(_to, FAASBal);
        } else {
            FAASToken.transfer(_to, _amount);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
}
// FarmingBad is the master of the Faas Token. He can dsitribute FEG.
//
// Note that it's ownable and the owner wields tremendous power.
// The yield farming smart contract is here to distribute all FEG that are sent to his own address
function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
// Update dev address by the previous dev.