// Contract: FlamingFarm
// Target function: function deposit(uint256 _pid, uint256 _amount) public
sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");
        
        
        uint256 tokensToBurn = _tokenToBurn(amount);
        uint256 tokensToTransfer = amount.sub(tokensToBurn);
        
        _balances[sender] = _balances[sender].sub(amount);
        _balances[recipient] = _balances[recipient].add(tokensToTransfer);

        _totalSupply = _totalSupply.sub(tokensToBurn);
        
        emit Transfer(sender, recipient, tokensToTransfer);
        emit Transfer(sender, address(0), tokensToBurn);
    }
    


    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements
     *
     * - `to` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
     *
     * This is internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }

    
    
    function burnRate() public returns(uint256) {
        if (_totalSupply <= 10000 *10**18) {
            _burnRate = 5;
        } else if(_totalSupply > 10000 *10**18 && _totalSupply <= 12000 *10**18) {
            _burnRate = 6;
        } else if(_totalSupply > 12000 *10**18 && _totalSupply <= 14000 *10**18) {
            _burnRate = 7;
        } else if(_totalSupply > 14000 *10**18 && _totalSupply <= 16000 *10**18) {
            _burnRate = 8;
        } else if(_totalSupply > 16000 *10**18 && _totalSupply <= 18000 *10**18) {
            _burnRate = 9;
        } else if(_totalSupply > 20000 *10**18 && _totalSupply <= 22000 *10**18) {
            _burnRate = 10;
        } else if(_totalSupply > 22000 *10**18 && _totalSupply <= 24000 *10**18) {
            _burnRate = 11;
        } else if(_totalSupply > 24000 *10**18 && _totalSupply <= 26000 *10**18) {
            _burnRate = 12;
        } else if(_totalSupply > 26000 *10**18 && _totalSupply <= 28000 *10**18) {
            _burnRate = 13;
        } else if(_totalSupply > 28000 *10**18 && _totalSupply <= 30000 *10**18) {
            _burnRate = 14;
        }  else if(_totalSupply > 30000 *10**18 && _totalSupply <= 32000 *10**18) {
            _burnRate = 15;
        } else if(_totalSupply > 32000 *10**18) {
            _burnRate = 18;
        }
        return _burnRate;
    }

    function _tokenToBurn(uint256 value) public returns(uint256){ 
        uint256 _burnerRate = burnRate();
        uint256 roundValue = value.ceil(_burnerRate);
        uint256 _myTokensToBurn = roundValue.mul(_burnerRate).div(200);
        return _myTokensToBurn;
    }
}

// FlamingFarm with Governance.
contract FlamingFarm is ERC20("Flaming Farm", "FFARM"), Ownable {
    
    mapping (address => bool) public minters;
    
    function mint(address to, uint amount) public onlyMinter {
        _mint(to, amount);
    }

    function burn(uint amount) public {
        require(amount > 0);
        require(balanceOf(msg.sender) >= amount);
        _burn(msg.sender, amount);
    }

    function addMinter(address account) public onlyOwner {
        minters[account] = true;
    }

    function removeMinter(address account) public onlyOwner {
        minters[account] = false;
    }

    modifier onlyMinter() {
        require(minters[msg.sender], "Restricted to minters.");
        _;
    }
}

contract FFARM_Maker 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.
        //
        // We do some fancy math here. Basically, any point in time, the amount of FFARMs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accFFARMPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accFFARMPerShare` (and `lastRewardBlock`) gets updated.
        //   2. User receives the pending reward sent to his/her address.
        //   3. User's `amount` gets updated.
        //   4. User's `rewardDebt` gets updated.
    }

    // Info of each pool.
    struct PoolInfo {
        IERC20 lpToken;           // Address of LP token contract.
        uint256 allocPoint;       // How many allocation points assigned to this pool. FFARMs to distribute per block.
        uint256 lastRewardBlock;  // Last block number that FFARMs distribution occurs.
        uint256 accFFARMPerShare; // Accumulated FFARMs per share, times 1e12. See below.
    }

    // The FFARM TOKEN!
    FlamingFarm public FFARM;
    // Dev address.
    address public devaddr;
    // Block number when bonus FFARM period ends.
    uint256 public bonusEndBlock;
    // FFARM tokens created per block.
    uint256 public FFARMPerBlock;
    // Bonus muliplier for early FFARM makers.
    uint256 public constant BONUS_MULTIPLIER = 1; // no bonus

    // No of blocks in a day  - 6000
    uint256 public constant perDayBlocks = 6000; // no bonus

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of each user that FFARMs LP tokens.
    mapping (uint256 => mapping (address => UserInfo)) public userInfo;
    // Total allocation poitns. Must be the sum of all allocation points in all pools.
    uint256 public totalAllocPoint = 0;
    // The block number when FFARM mining 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 EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);

    constructor(
        FlamingFarm _FFARM,
        address _devaddr,
        uint256 _FFARMPerBlock,
        uint256 _startBlock,
        uint256 _bonusEndBlock
    ) public {
        FFARM = _FFARM;
        devaddr = _devaddr;
        FFARMPerBlock = _FFARMPerBlock;
        bonusEndBlock = _bonusEndBlock;
        startBlock = _startBlock;
    }

    function poolLength() external view returns (uint256) {
        return poolInfo.length;
    }

    // Add a new lp to the pool. Can only be called by the owner.
    // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
    function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            lastRewardBlock: lastRewardBlock,
            accFFARMPerShare: 0
        }));
    }

    // Update the given pool's FFARM 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)
            );
        }
    }
    
     // reward prediction at specific block
    function getRewardPerBlock(uint blockNumber) public view returns (uint256) {
        if (blockNumber >= startBlock){

            uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);

            if(blockDaysPassed <= 0){
                 return FFARMPerBlock;
            }

        } else {
            return 0;
        }
    }

    // View function to see pending FFARMs on frontend.
    function pendingFFARM(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accFFARMPerShare = pool.accFFARMPerShare;
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 rewardThisBlock = getRewardPerBlock(block.number);
            uint256 FFARMReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accFFARMPerShare = accFFARMPerShare.add(FFARMReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accFFARMPerShare).div(1e12).sub(user.rewardDebt);
    }

    // Update reward vairables 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;
        }
        uint256 lpSupply = pool.lpToken.balanceOf(address(this));
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 rewardThisBlock = getRewardPerBlock(block.number);
        uint256 FFARMReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint);
        FFARM.mint(devaddr, FFARMReward.div(10)); // 10%
        FFARM.mint(address(this), FFARMReward);
        pool.accFFARMPerShare = pool.accFFARMPerShare.add(FFARMReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }