contract StablesPoolCash 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.
        uint256 rebaseIndexStart; // Rebase index of start.
        //
        // 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 poolType;         // 0 - Normal/Default, 10 - Rebase token.
        uint256 amount;
        uint256 lastRewardBlock;  // Last block number that SUSHIs distribution occurs.
        uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
    }

    // The SUSHI TOKEN!
    IERC20 public sushi;
    // Governance address.
    address public governance;
    uint256 public constant BLOCKS_PER_WEEK = 46500;
    uint256[] public epochTotalRewards = [40000 ether, 30000 ether, 20000 ether, 10000 ether];
    // Block number when each epoch ends.
    uint[4] public epochEndBlocks;
    // Reward per block for each of 4 epochs (last item is equal to 0 - for sanity).
    uint[5] public epochRewardsPerBlock;
    // 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;
    // The block number when SUSHI mining starts.
    uint256 public startBlock;
    // Rebase token log;
    uint256[] public rabaseLog;

    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(
        address _sushi,
        address _governance,
        uint256 _startBlock,
        address[] memory _lpTokens
    ) public {
        sushi = IERC20(_sushi);
        startBlock = _startBlock;
        governance = _governance;
        epochEndBlocks[0] = startBlock + BLOCKS_PER_WEEK;
        uint256 i;
        for (i = 1; i <= 3; ++i) {
            epochEndBlocks[i] = epochEndBlocks[i - 1] + BLOCKS_PER_WEEK;
        }
        for (i = 0; i <= 3; ++i) {
            epochRewardsPerBlock[i] = epochTotalRewards[i].div(BLOCKS_PER_WEEK);
        }
        epochRewardsPerBlock[4] = 0;

		for (i = 0; i < _lpTokens.length; ++i) {
			add(IERC20(_lpTokens[i]), false, 0);
		}
    }

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


    // 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 getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) {
        for (uint8 epochId = 4; epochId >= 1; --epochId) {
            if (_to >= epochEndBlocks[epochId - 1]) {
                if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardsPerBlock[epochId]);
                uint256 _generatedReward = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardsPerBlock[epochId]);
                if (epochId == 1) return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochRewardsPerBlock[0]));
                for (epochId = epochId - 1; epochId >= 1; --epochId) {
                    if (_from >= epochEndBlocks[epochId - 1]) return _generatedReward.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardsPerBlock[epochId]));
                    _generatedReward = _generatedReward.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardsPerBlock[epochId]));
                }
                return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochRewardsPerBlock[0]));
            }
        }
        return _to.sub(_from).mul(epochRewardsPerBlock[0]);
    }

    // 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 sushiReward = getGeneratedReward(pool.lastRewardBlock, block.number);
            accSushiPerShare = accSushiPerShare.add(sushiReward.div(totalAllocPoint).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 sushiReward = getGeneratedReward(pool.lastRewardBlock, block.number);
        pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.div(totalAllocPoint).mul(1e12).div(lpSupply));
        pool.lastRewardBlock = block.number;
    }

    // Deposit LP tokens to MasterChef for SUSHI allocation.
    function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (pool.poolType == 10) {
            rebasePool(_pid);
            if (user.amount > 0) {
                user.amount = user.amount.mul(rebaseRatio(user.rebaseIndexStart)).div(1e18);
            }
            user.rebaseIndexStart = rabaseLog.length;
        }
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
            if(pending > 0) {
                safeSushiTransfer(msg.sender, pending);
            }
        }
        if(_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            user.amount = user.amount.add(_amount);
            pool.amount = pool.amount.add(_amount);
        }
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }

    // Withdraw LP tokens from MasterChef.
    function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (pool.poolType == 10) {
            rebasePool(_pid);
            if (user.amount > 0) {
                user.amount = user.amount.mul(rebaseRatio(user.rebaseIndexStart)).div(1e18);
            }
            user.rebaseIndexStart = rabaseLog.length;
        }
        require(user.amount >= _amount, "withdraw: not good");

        uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
        if(pending > 0) {
            safeSushiTransfer(msg.sender, pending);
        }
        if(_amount > 0) {
            user.amount = user.amount.sub(_amount);
            pool.amount = pool.amount.sub(_amount);
            pool.lpToken.safeTransfer(address(msg.sender), _amount);
        }
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
        emit Withdraw(msg.sender, _pid, _amount);
    }

    function exit(uint256 _pid) external {
        UserInfo storage user = userInfo[_pid][msg.sender];
        PoolInfo storage pool = poolInfo[_pid];
        if (pool.poolType == 10) {
            rebasePool(_pid);
            if (user.amount > 0) {
                user.amount = user.amount.mul(rebaseRatio(user.rebaseIndexStart)).div(1e18);
            }
            user.rebaseIndexStart = rabaseLog.length;
        }
        withdraw(_pid, user.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];
        pool.lpToken.safeTransfer(address(msg.sender), user.amount);
        emit EmergencyWithdraw(msg.sender, _pid, user.amount);
        user.amount = 0;
        user.rewardDebt = 0;
    }

    // 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 governance address by the previous gov.
    function setGovernance(address _governance) external {
        require(msg.sender == governance, "!governance");
        require(_governance != address(0), "zero");
        governance = _governance;
    }

    function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external {
        require(msg.sender == governance, "!governance");
        if (block.number < epochEndBlocks[3] + BLOCKS_PER_WEEK) {
            // do not allow to drain lpToken if less than 3 months after farming
            require(_token != sushi, "!sushi");
            for (uint256 pid = 0; pid < poolInfo.length; ++pid) {
                PoolInfo storage pool = poolInfo[pid];
                require(_token != pool.lpToken, "!pool.lpToken");
            }
        }
        _token.safeTransfer(to, amount);
    }

    // Rebase pool.
    function rebasePool(uint256 _pid) internal {
        PoolInfo storage pool = poolInfo[_pid];
        IERC20 token = pool.lpToken;
        uint256 amount = pool.amount;
        uint256 bal = token.balanceOf(address(this));
        if (pool.poolType != 10 || amount == 0 || bal == 0 || amount == bal)
            return;
        rabaseLog.push(bal.mul(1e18).div(amount));
        // force sync.
        pool.amount = token.balanceOf(address(this));
    }
    function rebaseRatio(uint256 startIndex) public view returns (uint256) {
        uint256 i;
        uint256 rebase = 1e18;
        for (i = startIndex; i < rabaseLog.length; i++) {
            rebase = rebase.mul(rabaseLog[i]).div(1e18);
        }
        return rebase;
    }
}
// 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 getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) {
    for (uint8 epochId = 4; epochId >= 1; --epochId) {
        if (_to >= epochEndBlocks[epochId - 1]) {
            if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardsPerBlock[epochId]);
            uint256 _generatedReward = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardsPerBlock[epochId]);
            if (epochId == 1) return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochRewardsPerBlock[0]));
            for (epochId = epochId - 1; epochId >= 1; --epochId) {
                if (_from >= epochEndBlocks[epochId - 1]) return _generatedReward.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardsPerBlock[epochId]));
                _generatedReward = _generatedReward.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardsPerBlock[epochId]));
            }
            return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochRewardsPerBlock[0]));
        }
    }
    return _to.sub(_from).mul(epochRewardsPerBlock[0]);
}

// Return reward multiplier over the given _from to _to block.