contract blackholeswap is ERC20Mintable {
    using SafeMath for *;
    using SafeERC20 for IERC20;

    /***********************************|
    |        Variables && Events        |
    |__________________________________*/
    IERC20 constant token0 = ERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); //sUSD
    IERC20 constant token1 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); //DAI

    event Purchases(address indexed buyer, address indexed sell_token, uint256 inputs, address indexed buy_token, uint256 outputs);
    event AddLiquidity(address indexed provider, uint256 share, uint256 token0Amount, uint256 token1Amount);
    event RemoveLiquidity(address indexed provider, uint256 share, uint256 token0Amount, uint256 token1Amount);

    /***********************************|
    |            Constsructor           |
    |__________________________________*/

    constructor() public {
        symbol = "BHS sUSD/DAI";
        name = "BlackHoleSwap sUSD/DAI";
        decimals = 18;
        admin = msg.sender;
        vault = msg.sender;
    }

    /***********************************|
    |        Governmence & Params       |
    |__________________________________*/

    uint256 public fee = 0.99985e18; // 1 - swap fee (numerator, in 1e18 format)
    uint256 public protocolFee = 5;
    uint256 public constant A = 0.75e18;
    uint256 constant BASE = 1e18;

    address private admin;
    address private vault;

    uint256 public kLast;

    function setAdmin(address _admin) external {
        require(msg.sender == admin);
        admin = _admin;
    }

    function setParams(uint256 _fee, uint256 _protocolFee) external {
        require(msg.sender == admin);
        require(_fee < 1e18 && _fee >= 0.99e18); //0 < fee <= 1%
        require(_protocolFee > 0); //protocolFee <= 50% fee
        uint256 token0Reserve = getToken0Balance();
        uint256 token1Reserve = getToken1Balance();
        if(_totalSupply > 0) _mintFee(k(token0Reserve, token1Reserve));
        fee = _fee;
        protocolFee = _protocolFee;
        kLast = k(token0Reserve, token1Reserve);
    }

    function setVault(address _vault) external {
        require(msg.sender == admin);
        vault = _vault;
    }

    /***********************************|
    |         Getter Functions          |
    |__________________________________*/

    function getToken0Balance() public view returns (uint256) {
        return token0.balanceOf(address(this));
    }

    function getToken1Balance() public view returns (uint256) {
        return token1.balanceOf(address(this));
    }

    function k(uint256 x, uint256 y) internal pure returns (uint256 _k) {
        uint256 u = x.add(y.mul(A).div(BASE));
        uint256 v = y.add(x.mul(A).div(BASE));
        _k = u.mul(v);
    }

    function f(uint256 _x, uint256 x, uint256 y) internal pure returns (uint256 _y) {
        uint256 c = k(x, y).mul(BASE).div(A).sub(_x.mul(_x), "INSUFFICIENT_LIQUIDITY");

        uint256 cst = A.add(uint256(1e36).div(A));
        uint256 _b = _x.mul(cst).div(BASE);

        uint256 D = _b.mul(_b).add(c.mul(4)); // b^2 - 4c

        _y = D.sqrt().sub(_b).div(2);
    }

    // Calculate output given exact input
    function getOutExactIn(uint256 input, uint256 x, uint256 y) public view returns (uint256 output) {
        uint256 _x = x.add(input.mul(fee).div(BASE));
        uint256 _y = f(_x, x, y);
        output = y.sub(_y);
    }

    // Calculate input given exact output
    function getInExactOut(uint256 output, uint256 x, uint256 y) public view returns (uint256 input) {
        uint256 _y = y.sub(output);
        uint256 _x = f(_y, y, x);
        input = _x.sub(x).mul(BASE).div(fee);
    }

    /***********************************|
    |        Exchange Functions         |
    |__________________________________*/
    
    function _mintFee(uint256 _k) private {
        uint _kLast = kLast; // gas savings

        if (_kLast != 0) {
            uint rootK = _k.sqrt();
            uint rootKLast = _kLast.sqrt();
            if (rootK > rootKLast) {
                uint numerator = _totalSupply.mul(rootK.sub(rootKLast));
                uint denominator = rootK.mul(protocolFee).add(rootKLast);
                uint liquidity = numerator / denominator;
                if (liquidity > 0) _mint(vault, liquidity);
            }
        }

    }

    function token0In(uint256 input, uint256 min_output, uint256 deadline) external returns (uint256 output) {
        require(block.timestamp <= deadline, "EXPIRED");
        uint256 fromReserve = getToken0Balance();
        uint256 toReserve = getToken1Balance();

        output = getOutExactIn(input, fromReserve, toReserve);
        require(output >= min_output, "SLIPPAGE_DETECTED");
        doTransferIn(token0, msg.sender, input);
        doTransferOut(token1, msg.sender, output);

        emit Purchases(msg.sender, address(token0), input, address(token1), output);
    }
    
    function token1In(uint256 input, uint256 min_output, uint256 deadline) external returns (uint256 output) {
        require(block.timestamp <= deadline, "EXPIRED");
        uint256 fromReserve = getToken1Balance();
        uint256 toReserve = getToken0Balance();

        output = getOutExactIn(input, fromReserve, toReserve);
        require(output >= min_output, "SLIPPAGE_DETECTED");
        doTransferIn(token1, msg.sender, input);
        doTransferOut(token0, msg.sender, output);

        emit Purchases(msg.sender, address(token1), input, address(token0), output);
    }

    function token0Out(uint256 max_input, uint256 output, uint256 deadline) external returns (uint256 input) {
        require(block.timestamp <= deadline, "EXPIRED");
        uint256 fromReserve = getToken0Balance();
        uint256 toReserve = getToken1Balance();

        input = getInExactOut(output, fromReserve, toReserve);
        require(input <= max_input, "SLIPPAGE_DETECTED");
        doTransferIn(token1, msg.sender, input);
        doTransferOut(token0, msg.sender, output);

        emit Purchases(msg.sender, address(token1), input, address(token0), output);
    }
    
    function token1Out(uint256 max_input, uint256 output, uint256 deadline) external returns (uint256 input) {
        require(block.timestamp <= deadline, "EXPIRED");
        uint256 fromReserve = getToken1Balance();
        uint256 toReserve = getToken0Balance();

        input = getInExactOut(output, fromReserve, toReserve);
        require(input <= max_input, "SLIPPAGE_DETECTED");
        doTransferIn(token0, msg.sender, input);
        doTransferOut(token1, msg.sender, output);

        emit Purchases(msg.sender, address(token1), input, address(token0), output);
    }
    
    function doTransferIn(IERC20 token, address from, uint256 amount) internal {
        token.safeTransferFrom(from, address(this), amount);
    }

    function doTransferOut(IERC20 token, address to, uint256 amount) internal {
        token.safeTransfer(to, amount);
    }


    /***********************************|
    |        Liquidity Functions        |
    |__________________________________*/

    function addLiquidity(uint256 share, uint256 token0_max, uint256 token1_max) external returns (uint256 token0_in, uint256 token1_in) {
        require(share >= 1e15, 'INVALID_ARGUMENT'); // 0.001

        if (_totalSupply > 0) {
            uint256 token0Reserve = getToken0Balance();
            uint256 token1Reserve = getToken1Balance();
            _mintFee(k(token0Reserve, token1Reserve));
            token0_in = share.mul(token0Reserve).div(_totalSupply);
            token1_in = share.mul(token1Reserve).div(_totalSupply);
            require(token0_in <= token0_max && token1_in <= token1_max, "SLIPPAGE_DETECTED");
            _mint(msg.sender, share);
            kLast = k(token0Reserve.add(token0_in), token1Reserve.add(token1_in));
        }
        else {
            token0_in = share.div(2);
            token1_in = share.div(2);
            _mint(msg.sender, share);
            kLast = k(token0_in, token1_in);
        }

        doTransferIn(token0, msg.sender, token0_in);
        doTransferIn(token1, msg.sender, token1_in);
        emit AddLiquidity(msg.sender, share, token0_in, token1_in);
    }

    function addLiquidityImbalanced(uint256 token0_in, uint256 token1_in, uint256 share_min) external returns (uint256 share) {
        require(_totalSupply > 0, "INSUFFICIENT_LIQUIDITY");
        uint256 token0Reserve = getToken0Balance();
        uint256 token1Reserve = getToken1Balance();
        uint256 kBefore = k(token0Reserve, token1Reserve);
        // charge fee for imbalanced deposit
        uint256 kAfter = k(token0Reserve.add(token0_in.mul(fee).div(BASE)), token1Reserve.add(token1_in.mul(fee).div(BASE)));
        _mintFee(kBefore);
        // ( sqrt(_k) * totalSupply / sqrt(k) - totalSupply )
        share = kAfter.sqrt().mul(_totalSupply).div(kBefore.sqrt()).sub(_totalSupply);
        require(share >= share_min, "SLIPPAGE_DETECTED");
        _mint(msg.sender, share);

        kLast = kAfter;
        doTransferIn(token0, msg.sender, token0_in);
        doTransferIn(token1, msg.sender, token1_in);
        emit AddLiquidity(msg.sender, share, token0_in, token1_in);
    }

    function removeLiquidity(uint256 share, uint256 token0_min, uint256 token1_min) external returns (uint256 token0_out, uint256 token1_out) {
        require(share > 0, 'INVALID_ARGUMENT');

        uint256 token0Reserve = getToken0Balance();
        uint256 token1Reserve = getToken1Balance();
        _mintFee(k(token0Reserve, token1Reserve));

        token0_out = share.mul(token0Reserve).div(_totalSupply);
        token1_out = share.mul(token1Reserve).div(_totalSupply);
        require(token0_out >= token0_min && token1_out >= token1_min, "SLIPPAGE_DETECTED");

        _burn(msg.sender, share);

        kLast = k(token0Reserve.sub(token0_out), token1Reserve.sub(token1_out));
        doTransferOut(token0, msg.sender, token0_out);
        doTransferOut(token1, msg.sender, token1_out);
        emit RemoveLiquidity(msg.sender, share, token0_out, token1_out);
    }

}
function getOutExactIn(uint256 input, uint256 x, uint256 y) public view returns (uint256 output) {
    uint256 _x = x.add(input.mul(fee).div(BASE));
    uint256 _y = f(_x, x, y);
    output = y.sub(_y);
}

// Calculate output given exact input