contract xVault {
    using SafeERC20 for IERC20;
    
    address owner;
    
    IComptroller constant COMPTROLLER = IComptroller(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
    address constant FACTORY = address(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac);
    address constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
    
    // calculates the CREATE2 address for a pair without making any external calls
    function pairFor(address tokenA, address tokenB) internal pure returns (address pair) {
        (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        pair = address(uint160(uint(keccak256(abi.encodePacked(
                hex'ff',
                FACTORY,
                keccak256(abi.encodePacked(token0, token1)),
                hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
            )))));
    }
    
    function enterMarkets() public {
        COMPTROLLER.enterMarkets(COMPTROLLER.getAllMarkets());
    }
    
    function approveMarkets() public {
        address[] memory _markets = COMPTROLLER.getAllMarkets();
        for (uint i = 0; i < _markets.length; i++) {
            address _underlying = cyToken(_markets[i]).underlying();
            IERC20(_underlying).safeApprove(_markets[i], uint(-1));
        }
    }
    
    constructor() {
        owner = msg.sender;
        enterMarkets();
        //approveMarkets();
    }
    
    function withdraw(address token, uint amount) external {
        require(owner == msg.sender);
        IERC20(token).safeTransfer(msg.sender, amount);
    }
    
    function open(address cylong, address long, uint lamt, address cyshort, address short, uint samt, address cymargin, uint mamt) external {
        require(owner == msg.sender);
        IERC20(cymargin).safeTransferFrom(msg.sender, address(this), mamt);
        _borrow(cylong, long, lamt, cyshort, short, samt);
    }
    
    function close(address cyrepay, address repay, uint ramt, address cywithdraw, address uwithdraw, uint wamt) external {
        require(owner == msg.sender);
        address tokenB = repay == WETH ? uwithdraw : WETH;
        ISushiswapV2Pair _pairFrom = ISushiswapV2Pair(pairFor(repay, tokenB));
        (uint amount0, uint amount1) = repay < tokenB ? (ramt, uint(0)) : (uint(0), ramt);
        _pairFrom.swap(amount0, amount1, address(this), abi.encode(cyrepay, repay, ramt, address(_pairFrom), cywithdraw, uwithdraw, wamt, false));
    }
    
    function _borrow(address cylong, address long, uint lamt, address cyshort, address short, uint samt) internal {
        (uint amount0, uint amount1) = long < WETH ? (lamt, uint(0)) : (uint(0), lamt);
        address tokenB = long == WETH ? short : WETH;
        ISushiswapV2Pair _pairFrom = ISushiswapV2Pair(pairFor(long, tokenB));
        _pairFrom.swap(amount0, amount1, address(this), abi.encode(cylong, long, lamt, address(_pairFrom), cyshort, short, samt, true));
    }
    
    function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external {
        require(sender == address(this));
        (address _cylong, address _long, uint _lamt, address _pairFrom, address _cyshort, address _short, uint _samt, bool _pos) = abi.decode(data, (address, address, uint, address, address, address, uint, bool));
        if (_pos) {
            _open(_cylong, _lamt, _pairFrom, amount0, _short, _long, _samt, _cyshort);
        } else {
            _close(_cylong, _lamt, _pairFrom, amount0, _short, _long, _samt, _cyshort);
        }
    }
    
    function _close(address _cyrepay, uint _ramt, address _pairFrom, uint _amount0, address _withdraw, address _repay, uint _wamt, address _cywithdraw) internal {
        IERC20(_repay).safeApprove(_cyrepay, 0);
        IERC20(_repay).safeApprove(_cyrepay, uint(-1));
        cyToken(_cyrepay).repayBorrow(_ramt);
        
        (uint reserve0, uint reserve1,) = ISushiswapV2Pair(_pairFrom).getReserves();
        (uint reserveIn, uint reserveOut) = _amount0 > 0 ? (reserve1, reserve0) : (reserve0, reserve1);
        
        uint _minRepay = _getAmountIn(_ramt, reserveIn, reserveOut);
        
        if (_withdraw == WETH || _repay == WETH) {
            require(_minRepay <= _wamt);
            cyToken(_cywithdraw).redeemUnderlying(_minRepay);
            IERC20(_withdraw).safeTransfer(address(_pairFrom), _minRepay);
        } else {
            _crossClose(_withdraw, _minRepay, _wamt, _cywithdraw, address(_pairFrom));
        }
    }
    
    function _open(address _cylong, uint _lamt, address _pairFrom, uint _amount0, address _short, address _long, uint _samt, address _cyshort) internal {
        IERC20(_long).safeApprove(_cylong, 0);
        IERC20(_long).safeApprove(_cylong, uint(-1));
        cyToken(_cylong).mint(_lamt);
        
        (uint reserve0, uint reserve1,) = ISushiswapV2Pair(_pairFrom).getReserves();
        (uint reserveIn, uint reserveOut) = _amount0 > 0 ? (reserve1, reserve0) : (reserve0, reserve1);
        
        uint _minRepay = _getAmountIn(_lamt, reserveIn, reserveOut);
        
        if (_short == WETH || _long == WETH) {
            require(_minRepay <= _samt);
            cyToken(_cyshort).borrow(_minRepay);
            IERC20(_short).safeTransfer(address(_pairFrom), _minRepay);
        } else {
            _cross(_short, _minRepay, _samt, _cyshort, address(_pairFrom));
        }
    }
    
    function _getShortFall(address _short, ISushiswapV2Pair _pairTo, uint _minWETHRepay) internal view returns (address, uint) {
        (address token0,) = _short < WETH ? (_short, WETH) : (WETH, _short);
        (uint reserve0, uint reserve1,) = _pairTo.getReserves();
        (uint reserveIn, uint reserveOut) = token0 == _short ? (reserve0, reserve1) : (reserve1, reserve0);
        return (token0, _getAmountIn(_minWETHRepay, reserveIn, reserveOut));
    }
    
    function _cross(address _short, uint _minWETHRepay, uint _samt, address _cyshort, address _pairFrom) internal {
        ISushiswapV2Pair _pairTo = ISushiswapV2Pair(pairFor(_short, WETH));
        (address token0, uint _shortPay) = _getShortFall(_short, _pairTo, _minWETHRepay);
        require(_shortPay <= _samt);
        cyToken(_cyshort).borrow(_shortPay);
        (uint amount0, uint amount1) = token0 == _short ? (uint(0), _minWETHRepay) : (_minWETHRepay, uint(0));
        IERC20(_short).safeTransfer(address(_pairTo), _shortPay);
        _pairTo.swap(amount0, amount1, _pairFrom, new bytes(0));
    }
    
    function _crossClose(address _withdraw, uint _minWETHRepay, uint _wamt, address _cywithdraw, address _pairFrom) internal {
        ISushiswapV2Pair _pairTo = ISushiswapV2Pair(pairFor(_withdraw, WETH));
        (address token0, uint _shortPay) = _getShortFall(_withdraw, _pairTo, _minWETHRepay);
        require(_shortPay <= _wamt);
        cyToken(_cywithdraw).redeemUnderlying(_shortPay);
        (uint amount0, uint amount1) = token0 == _withdraw ? (uint(0), _minWETHRepay) : (_minWETHRepay, uint(0));
        IERC20(_withdraw).safeTransfer(address(_pairTo), _shortPay);
        _pairTo.swap(amount0, amount1, _pairFrom, new bytes(0));
    }
    
    function execute(address to, uint value, bytes calldata data) external returns (bool, bytes memory) {
        require(owner == msg.sender);
        (bool success, bytes memory result) = to.call{value:value}(data);
        
        return (success, result);
    }

    function _getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
        uint numerator = reserveIn * amountOut * 1000;
        uint denominator = (reserveOut - amountOut) * 997;
        amountIn = (numerator / denominator) + 1;
    }
    
    
}
function pairFor(address tokenA, address tokenB) internal pure returns (address pair) {
        (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        pair = address(uint160(uint(keccak256(abi.encodePacked(
                hex'ff',
                FACTORY,
                keccak256(abi.encodePacked(token0, token1)),
                hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
            )))));
    }
// calculates the CREATE2 address for a pair without making any external calls