contract Geyser is Ownable {
    using SafeMath for uint256;
    using TransferHelper for IERC20;

    // Info of each user.
    struct UserInfo {
        uint256 amount;     // How many LP tokens the user has provided.
        uint256 lpAmount;   // Single token, swap to LP token.
        uint256 rewardDebt; // Reward debt. See explanation below.
        //
        // We do some fancy math here. Basically, any point in time, the amount of SUSHIs
        // entitled to a user but is pending to be distributed is:
        //
        //   pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
        //
        // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
        //   1. The pool's `accSushiPerShare` (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. SUSHIs to distribute per block.
        uint256 buybackRatio;     // Buyback ratio, 0 means no ratio. 5 means 0.5%
        uint256 poolType;         // Pool type, 0 - LP(default), 1 - Token need to convert to LP(include ETH)
        uint256 amount;           // User deposit amount(Token or LP Token)
        uint256 lpAmount;         // ETH/Token convert to uniswap liq amount
        uint256 lastRewardBlock;  // Last block number that SUSHIs distribution occurs.
        uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
    }

    // mainnet
    address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address public constant UNIV2ROUTER2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

    // The SUSHI TOKEN!
    IERC20 public sushi;
    address public pairaddr;
    uint256 public mintReward;
    uint public constant SUSPEND_MINING_BALANCE = 10000*1e8;
    // Dev address.
    address public devaddr;
    // Treasury address;
    address public treasury;
    // SUSHI tokens created per block.
    uint256 public sushiPerBlock;
    // Halving blocks;
    uint256 public blocksHalving;
    // The migrator contract. It has a lot of power. Can only be set through governance (owner).
    IMigratorChef public migrator;

    // Info of each pool.
    PoolInfo[] public poolInfo;
    // Info of each user that stakes 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 SUSHI mining starts.
    uint256 public startBlock;

    event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 buybackAmount, uint256 liquidity);
    event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, uint256 buybackAmount, uint256 liquidity);
    event Mint(address indexed to, uint256 amount);

    constructor(
        IERC20 _sushi,
        address _devaddr,
        address _treasury,
        uint256 _sushiPerBlock,
        uint256 _startBlock,
        uint256 _blocksHalving
    ) public {
        sushi = _sushi;
        devaddr = _devaddr;
        treasury = _treasury;
        sushiPerBlock = _sushiPerBlock;
        startBlock = _startBlock;
        blocksHalving = _blocksHalving;
    }

    receive() external payable {
        assert(msg.sender == WETH);
    }

    function setPair(address _pairaddr) public onlyOwner {
        pairaddr = _pairaddr;

        IERC20(pairaddr).safeApprove(UNIV2ROUTER2, uint(-1));
        IERC20(WETH).safeApprove(UNIV2ROUTER2, uint(-1));
        sushi.safeApprove(UNIV2ROUTER2, uint(-1));
    }

    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, uint256 _buybackRatio, uint256 _type) public onlyOwner {
        if (_withUpdate) {
            massUpdatePools();
        }
        uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
        totalAllocPoint = totalAllocPoint.add(_allocPoint);
        poolInfo.push(PoolInfo({
            lpToken: _lpToken,
            allocPoint: _allocPoint,
            buybackRatio: _buybackRatio,
            poolType: _type,
            amount: 0,
            lpAmount: 0,
            lastRewardBlock: lastRewardBlock,
            accSushiPerShare: 0
        }));

        _lpToken.safeApprove(UNIV2ROUTER2, uint(-1));
    }

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

    // Set the migrator contract. Can only be called by the owner.
    function setMigrator(IMigratorChef _migrator) public onlyOwner {
        migrator = _migrator;
    }

    // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
    function migrate(uint256 _pid) public {
        require(address(migrator) != address(0), "migrate: no migrator");
        PoolInfo storage pool = poolInfo[_pid];
        IERC20 lpToken = pool.lpToken;
        uint256 bal = lpToken.balanceOf(address(this));
        lpToken.safeApprove(address(migrator), bal);
        IERC20 newLpToken = migrator.migrate(lpToken);
        require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
        pool.lpToken = newLpToken;
    }

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _to) public view returns (uint256) {
        uint256 blockCount = _to.sub(startBlock);
        uint256 epochCount = blockCount.div(blocksHalving);
        uint256 multiplierPart1 = 0;
        uint256 multiplierPart2 = 0;
        uint256 divisor = 1;

        for (uint256 i = 0; i < epochCount; ++i) {
            multiplierPart1 = multiplierPart1.add(blocksHalving.div(divisor));
            divisor = divisor.mul(2);
        }

        multiplierPart2 = blockCount.mod(blocksHalving).div(divisor);

        return multiplierPart1.add(multiplierPart2);
    }

    // Return reward multiplier over the given _from to _to block.
    function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
        if (sushi.balanceOf(address(this)) < SUSPEND_MINING_BALANCE) {
            return 0;
        }

        if (_to <= _from) {
            return 0;
        }
        return getMultiplier(_to).sub(getMultiplier(_from));
    }

    // View function to see pending SUSHIs on frontend.
    function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][_user];
        uint256 accSushiPerShare = pool.accSushiPerShare;
        uint256 lpSupply = pool.amount;
        if (block.number > pool.lastRewardBlock && lpSupply != 0) {
            uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
            uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
            accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
        }
        return user.amount.mul(accSushiPerShare).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;
        }
        uint256 lpSupply = pool.amount;
        if (lpSupply == 0) {
            pool.lastRewardBlock = block.number;
            return;
        }
        uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
        uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
        mint(devaddr, sushiReward.div(20));
		mintReward.add(sushiReward);
        pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to MasterChef for SUSHI allocation.
    function deposit(uint256 _pid, uint256 _amount) public payable {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        uint256 buybackAmount;
        uint256 liquidity;
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
            if(pending > 0) {
                safeSushiTransfer(msg.sender, pending);
            }
        }
        if (msg.value > 0) {
		    IWETH(WETH).deposit{value: msg.value}();
		    _amount = msg.value;
        } else if(_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        }

        if(_amount > 0) {
            buybackAmount = _amount.mul(pool.buybackRatio).div(1000);
            if (pool.buybackRatio > 0 && buybackAmount == 0) {
                // too little, directy to treasury
                buybackAmount = _amount;
            }
            // transfer to treasury contract and buyback token.
            pool.lpToken.safeTransfer(treasury, buybackAmount);
            _amount = _amount.sub(buybackAmount);

            if (pool.poolType == 1) {
                liquidity = assetTokenToLp(pool.lpToken, _amount);
                user.lpAmount = user.lpAmount.add(liquidity);
                pool.lpAmount = pool.lpAmount.add(liquidity);
            }
            pool.amount = pool.amount.add(_amount);
            user.amount = user.amount.add(_amount);
        }
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount, buybackAmount, liquidity);
    }

    // Withdraw LP tokens from MasterChef.
    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.accSushiPerShare).div(1e12).sub(user.rewardDebt);
        if(pending > 0) {
            safeSushiTransfer(msg.sender, pending);
        }
        uint256 buybackAmount;
        uint256 liquidity;
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.amount = pool.amount.sub(_amount);

            if (pool.poolType == 1) {
                liquidity = user.lpAmount.mul(_amount).div(user.amount.add(_amount));
                _amount = lpToAssetToken(pool.lpToken, liquidity);
                user.lpAmount = user.lpAmount.sub(liquidity);
                pool.lpAmount = pool.lpAmount.sub(liquidity);
            }

            buybackAmount = _amount.mul(pool.buybackRatio).div(1000);
            if (pool.buybackRatio > 0 && buybackAmount == 0) {
                // too little, directy to treasury
                buybackAmount = _amount;
            }
            // transfer to treasury contract and buyback token.
            pool.lpToken.safeTransfer(treasury, buybackAmount);
            _amount = _amount.sub(buybackAmount);

            if (address(pool.lpToken) == WETH) {
                IWETH(WETH).withdraw(_amount);
                TransferHelper.safeTransferETH(address(msg.sender), _amount);
            } else {
                pool.lpToken.safeTransfer(address(msg.sender), _amount);
            }
        }
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
        emit Withdraw(msg.sender, _pid, _amount, buybackAmount, liquidity);
    }

    // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
    function safeSushiTransfer(address _to, uint256 _amount) internal {
        uint256 sushiBal = sushi.balanceOf(address(this));
        if (_amount > sushiBal) {
            sushi.transfer(_to, sushiBal);
        } else {
            sushi.transfer(_to, _amount);
        }
    }

    // Update dev address by the previous dev.
    function dev(address _devaddr) public {
        require(msg.sender == devaddr, "dev: wut?");
        devaddr = _devaddr;
    }
    // Update Treasury contract address;
    function setTreasury(address _treasury) public onlyOwner {
        treasury = _treasury;
    }
    
    function mint(address to, uint256 rewardAmount) private {
        if (rewardAmount == 0) {
            emit Mint(to, 0);
            return;
        }
        
        sushi.safeTransfer(to, rewardAmount);
        emit Mint(to, rewardAmount);
    }

    function swapExactTokensForTokens(address _fromToken, address _toToken, uint256 _amount) internal returns (uint256) {
        if (_fromToken == _toToken || _amount == 0) return _amount;
        address[] memory path = new address[](2);
        path[0] = _fromToken;
        path[1] = _toToken;
        uint[] memory amount = IUniswapV2Router02(UNIV2ROUTER2).swapExactTokensForTokens(
                      _amount, 0, path, address(this), now.add(60));
        return amount[amount.length - 1];
    }

    function assetTokenToLp(IERC20 _token, uint256 _amount) internal returns (uint256 liq) {
        if (_amount == 0) return 0;

        if (address(_token) != WETH) {
            _amount = swapExactTokensForTokens(address(_token), WETH, _amount);
        }

        // slippage 0.5% , ETH: 0.5*(1+0.005) = 0.5025
        uint256 amountBuy = _amount.mul(5025).div(10000);
        uint256 amountEth = _amount.sub(amountBuy);

        address[] memory path = new address[](2);
        path[0] = WETH;
        path[1] = address(sushi);
        uint256[] memory amounts = IUniswapV2Router02(UNIV2ROUTER2).swapExactTokensForTokens(
                  amountBuy, 0, path, address(this), now.add(60));
        uint256 amountToken = amounts[1];

        uint256 amountEthReturn;
        (amountEthReturn,, liq) = IUniswapV2Router02(UNIV2ROUTER2).addLiquidity(
                WETH, address(sushi), amountEth, amountToken, 0, 0, address(this), now.add(60));

        if (amountEth > amountEthReturn) {
            swapExactTokensForTokens(WETH, address(sushi), amountEth.sub(amountEthReturn));
        }
    }

    function lpToAssetToken(IERC20 _token, uint256 _liquidity) internal returns (uint256 amountAsset){
        if (_liquidity == 0) return 0;
        (uint256 amountToken, uint256 amountEth) = IUniswapV2Router02(UNIV2ROUTER2).removeLiquidity(
            address(sushi), WETH, _liquidity, 0, 0, address(this), now.add(60));

        amountEth = amountEth.add(swapExactTokensForTokens(address(sushi), WETH, amountToken));

        if (address(_token) == WETH) {
            amountAsset = amountEth;
        } else {
            address[] memory path = new address[](2);
            path[0] = WETH;
            path[1] = address(_token);
            uint256[] memory amounts = IUniswapV2Router02(UNIV2ROUTER2).swapExactTokensForTokens(
                  amountEth, 0, path, address(this), now.add(60));
            amountAsset = amounts[1];
        }
    }
}
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
function safeSushiTransfer(address _to, uint256 _amount) internal {
        uint256 sushiBal = sushi.balanceOf(address(this));
        if (_amount > sushiBal) {
            sushi.transfer(_to, sushiBal);
        } else {
            sushi.transfer(_to, _amount);
        }
    }
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.