contract UniSwap_ETH_CDAIZap is Initializable {
    using SafeMath for uint;
    // state variables

    // - THESE MUST ALWAYS STAY IN THE SAME LAYOUT
    bool private stopped;
    address payable public owner;
    IuniswapFactory public UniSwapFactoryAddress;
    IOneSplitInterface public OneSplitInterfaceAddress;
    IERC20 public NEWDAI_TOKEN_ADDRESS;
    Compound public COMPOUND_TOKEN_ADDRESS;
    address public DAI_TOKEN_ADDRESS;
    address public ETH_TOKEN_ADDRESS;
    address public ONESPLIT_ADDRESS;


    // events
    event ERC20TokenHoldingsOnConversionDaiChai(uint);
    event ERC20TokenHoldingsOnConversionEthDai(uint);
    event LiquidityTokens(uint);

    // circuit breaker modifiers
    modifier stopInEmergency {if (!stopped) _;}
    modifier onlyInEmergency {if (stopped) _;}
    modifier onlyOwner() {
        require(isOwner(), "you are not authorised to call this function");
        _;
    }


    function initialize() initializer public {
        stopped = false;
        owner = msg.sender;
        UniSwapFactoryAddress = IuniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);
        NEWDAI_TOKEN_ADDRESS = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
        COMPOUND_TOKEN_ADDRESS = Compound(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
        OneSplitInterfaceAddress = IOneSplitInterface(0xD010B65120E027419586216D25bF86C2c24FCC4a);
        ONESPLIT_ADDRESS = address(0xD010B65120E027419586216D25bF86C2c24FCC4a);
        DAI_TOKEN_ADDRESS = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
        ETH_TOKEN_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
    }


    function set_new_UniSwapFactoryAddress(address _new_UniSwapFactoryAddress) public onlyOwner {
        UniSwapFactoryAddress = IuniswapFactory(_new_UniSwapFactoryAddress);
    }

    function set_new_DAI_TOKEN_ADDRESS(address _new_DAI_TOKEN_ADDRESS) public onlyOwner {
        NEWDAI_TOKEN_ADDRESS = IERC20(_new_DAI_TOKEN_ADDRESS);
        DAI_TOKEN_ADDRESS = _new_DAI_TOKEN_ADDRESS;
    }

    function set_new_cDAI_TokenContractAddress(address _new_cDAI_TokenContractAddress) public onlyOwner {
        COMPOUND_TOKEN_ADDRESS = Compound(_new_cDAI_TokenContractAddress);
    }

    function set_OneSplitInterfaceAddress(address _new_OneSplitInterfaceAddress) public onlyOwner {
        OneSplitInterfaceAddress = IOneSplitInterface(_new_OneSplitInterfaceAddress);
        ONESPLIT_ADDRESS = _new_OneSplitInterfaceAddress;
    }

    function getExpectedReturn(uint256 eth) public view returns (uint256) {
      uint256 _minReturn = 0;
      (_minReturn, ) = OneSplitInterfaceAddress.getExpectedReturn(ETH_TOKEN_ADDRESS, DAI_TOKEN_ADDRESS, eth, 1, 0);
      return _minReturn;
    }

    function LetsInvest(address _towhomtoissue, uint256 _minReturn) public payable stopInEmergency returns (uint) {
        IERC20 ERC20TokenAddress = IERC20(address(COMPOUND_TOKEN_ADDRESS));
        IuniswapExchange UniSwapExchangeContractAddress = IuniswapExchange(UniSwapFactoryAddress.getExchange(address(COMPOUND_TOKEN_ADDRESS)));

        // determining the portion of the incoming ETH to be converted to the ERC20 Token
        uint conversionPortion = SafeMath.div(SafeMath.mul(msg.value, 505), 1000);
        uint non_conversionPortion = SafeMath.sub(msg.value,conversionPortion);

        if (_minReturn == 0) {
          (_minReturn, ) = OneSplitInterfaceAddress.getExpectedReturn(ETH_TOKEN_ADDRESS, DAI_TOKEN_ADDRESS, conversionPortion, 1, 0);
        }

        OneSplitInterfaceAddress.goodSwap.value(conversionPortion)(ETH_TOKEN_ADDRESS, DAI_TOKEN_ADDRESS, conversionPortion, _minReturn, 1, 0);
        uint tokenBalance = NEWDAI_TOKEN_ADDRESS.balanceOf(address(this));

        require(tokenBalance > 0, "the conversion did not happen as planned");

        // conversion of DAI to cDAI
        uint qty2approve = SafeMath.mul(tokenBalance, 3);
        require(NEWDAI_TOKEN_ADDRESS.approve(address(ERC20TokenAddress), qty2approve));
        COMPOUND_TOKEN_ADDRESS.mint(tokenBalance);
        uint ERC20TokenHoldings = ERC20TokenAddress.balanceOf(address(this));
        require (ERC20TokenHoldings > 0, "the conversion did not happen as planned");
        emit ERC20TokenHoldingsOnConversionDaiChai(ERC20TokenHoldings);
        NEWDAI_TOKEN_ADDRESS.approve(address(ERC20TokenAddress), 0);
        ERC20TokenAddress.approve(address(UniSwapExchangeContractAddress),ERC20TokenHoldings);

        // adding Liquidity
        uint max_tokens_ans = getMaxTokens(address(UniSwapExchangeContractAddress), ERC20TokenAddress, non_conversionPortion);
        UniSwapExchangeContractAddress.addLiquidity.value(non_conversionPortion)(1,max_tokens_ans,SafeMath.add(now,1800));
        ERC20TokenAddress.approve(address(UniSwapExchangeContractAddress),0);

        // transferring Liquidity
        uint LiquityTokenHoldings = UniSwapExchangeContractAddress.balanceOf(address(this));
        emit LiquidityTokens(LiquityTokenHoldings);
        UniSwapExchangeContractAddress.transfer(_towhomtoissue, LiquityTokenHoldings);
        ERC20TokenHoldings = ERC20TokenAddress.balanceOf(address(this));
        ERC20TokenAddress.transfer(_towhomtoissue, ERC20TokenHoldings);
        return LiquityTokenHoldings;
    }

    function Redeem(address _towhomtosend, uint256 _amount) public stopInEmergency returns (uint) {
        // Compound contract address
        IERC20 ERC20TokenAddress = IERC20(address(COMPOUND_TOKEN_ADDRESS));

        // Compound uniswap exchange
        IuniswapExchange UniSwapExchangeContractAddress = IuniswapExchange(UniSwapFactoryAddress.getExchange(address(COMPOUND_TOKEN_ADDRESS)));

        // Send users uni-v1 to contract address (will fail if not approved)
        UniSwapExchangeContractAddress.transferFrom(msg.sender, address(this), _amount);

        // Get min_eth and min_token for removeLiquidity call
        (, uint256 ownerSharesEth, uint256 ownerSharesToken) = getReturn(address(UniSwapExchangeContractAddress), ERC20TokenAddress, _amount);
        // Swap uni-v1 for eth and tokens
        (uint256 eth, uint256 tokens) = UniSwapExchangeContractAddress.removeLiquidity(_amount, ownerSharesEth, ownerSharesToken, SafeMath.add(now,1800));

        // Approve onsplit to take the compound tokens
        ERC20TokenAddress.approve(ONESPLIT_ADDRESS, tokens);
        // Get the expected return in ETH
        (uint256 _minReturn, ) = OneSplitInterfaceAddress.getExpectedReturn(address(COMPOUND_TOKEN_ADDRESS), ETH_TOKEN_ADDRESS, tokens, 1, 0);
        // Swap for the expected ETH
        OneSplitInterfaceAddress.goodSwap.value(0)(address(COMPOUND_TOKEN_ADDRESS), ETH_TOKEN_ADDRESS, tokens, _minReturn, 1, 0);


        ERC20TokenAddress.approve(ONESPLIT_ADDRESS, 0);

        uint256 ethReturn = SafeMath.add(eth, _minReturn);
        (bool result, ) = _towhomtosend.call.value(ethReturn).gas(50000)("");
        require(result, "transfer of ETH failed");
        return ethReturn;
    }

    function getMaxTokens(address _UniSwapExchangeContractAddress, IERC20 _ERC20TokenAddress, uint _value) public view returns (uint) {
        uint contractBalance = _UniSwapExchangeContractAddress.balance;
        uint eth_reserve = SafeMath.sub(contractBalance, _value);
        uint token_reserve = _ERC20TokenAddress.balanceOf(_UniSwapExchangeContractAddress);
        uint token_amount = SafeMath.div(SafeMath.mul(_value,token_reserve),eth_reserve) + 1;
        return token_amount;
    }

    function getEthBalance(address _UniSwapExchangeContractAddress) public view returns (uint) {
      uint ethBalance = _UniSwapExchangeContractAddress.balance;
      return ethBalance;
    }

    function getTokenReserves(address _UniSwapExchangeContractAddress, IERC20 _ERC20TokenAddress) public view returns (uint) {
      uint token_reserve = _ERC20TokenAddress.balanceOf(_UniSwapExchangeContractAddress);
      return token_reserve;
    }


    function getTotalShares(address _UniSwapExchangeContractAddress) public view returns (uint) {
      uint totalShares = IuniswapExchange(_UniSwapExchangeContractAddress).totalSupply();
      return totalShares;
    }

    function getReturn(address _UniSwapExchangeContractAddress, IERC20 _ERC20TokenAddress, uint _value) public view returns (uint, uint, uint) {
        // Token balance in uniswap contract
        uint token_reserve = _ERC20TokenAddress.balanceOf(_UniSwapExchangeContractAddress);
        // ETH balance in uniswap contract
        uint ethBalance = _UniSwapExchangeContractAddress.balance;

        // Get total pool shares
        uint totalShares = IuniswapExchange(_UniSwapExchangeContractAddress).totalSupply();

        // Calculate owner share pool
        uint ownerSharesEth = SafeMath.div(SafeMath.mul(_value, ethBalance), totalShares);
        uint ownerSharesToken = SafeMath.div(SafeMath.mul(_value, token_reserve), totalShares);

        // Calculate eth value
        uint ethBought = IuniswapExchange(_UniSwapExchangeContractAddress).getTokenToEthInputPrice(ownerSharesToken);
        uint ethValue = SafeMath.add(ethBought, ownerSharesEth);

        return (ethValue, ownerSharesEth, ownerSharesToken);
    }

    // incase of half-way error
    function inCaseTokengetsStuck(IERC20 _TokenAddress) onlyOwner public {
        uint qty = _TokenAddress.balanceOf(address(this));
        _TokenAddress.transfer(owner, qty);
    }

    // - fallback function let you / anyone send ETH to this wallet without the need to call any function
    function() external payable {
        if (msg.sender != owner) {
            LetsInvest(msg.sender, 0);
        }
    }

    // - to Pause the contract
    function toggleContractActive() onlyOwner public {
        stopped = !stopped;
    }
    // - to withdraw any ETH balance sitting in the contract
    function withdraw() onlyOwner public{
        owner.transfer(address(this).balance);
    }
    // - to kill the contract
    function destruct() public onlyOwner {
        selfdestruct(owner);
    }
    /**
     * @return true if `msg.sender` is the owner of the contract.
     */
    function isOwner() public view returns (bool) {
        return msg.sender == owner;
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address payable newOwner) public onlyOwner {
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     */
    function _transferOwnership(address payable newOwner) internal {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        owner = newOwner;
    }

}
function destruct() public onlyOwner {
    selfdestruct(owner);
}

// - to kill the contract