// Contract: RYZRSwapFactory
// Target function: function mint(address to) external override lock returns (uint liquidity)
https://ethereum.github.io/yellowpaper/paper.pdf), defines	
        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most	
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.	
        //	
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value	
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or	
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept	
        // these malleable signatures as well.	
        require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");	
        require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");	
        // If the signature is valid (and not malleable), return the signer address	
        address signer = ecrecover(hash, v, r, s);	
        require(signer != address(0), "ECDSA: invalid signature");	
        return signer;	
    }	
    /**	
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This	
     * replicates the behavior of the	
     * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]	
     * JSON-RPC method.	
     *	
     * See {recover}.	
     */	
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {	
        // 32 is the length in bytes of hash,	
        // enforced by the type signature above	
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));	
    }	
}

// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath { // provides additional gas efficiency
    function add(uint x, uint y) internal pure returns (uint z) {
        require((z = x + y) >= x, "ds-math-add-overflow");
    }

    function sub(uint x, uint y) internal pure returns (uint z) {
        require((z = x - y) <= x, "ds-math-sub-underflow");
    }

    function mul(uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
    }

    function div(uint x, uint y) internal pure returns (uint z) {
        require(y > 0, "ds-math-div-underflow");
        z = x / y;
    }
}

interface IRYZRSwapERC20 {
    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}

contract RYZRSwapERC20 is IRYZRSwapERC20 {
    using SafeMath for uint;

    string public constant override name = 'RYZRSwap-LP';
    string public constant override symbol = 'NEW-LP';
    uint8 public constant override decimals = 18;
    uint  public override totalSupply;
    mapping(address => uint) public override balanceOf;
    mapping(address => mapping(address => uint)) public override allowance;

    bytes32 public immutable override DOMAIN_SEPARATOR;
    bytes32 public constant override PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    mapping(address => uint) public override nonces;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor() {
        uint chainId;
        assembly {
            chainId := chainid()
        }
        DOMAIN_SEPARATOR = keccak256(
            abi.encode(
                keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                keccak256(bytes(name)),
                keccak256(bytes('1')),
                chainId,
                address(this)
            )
        );
    }

    function _mint(address to, uint value) internal {
        totalSupply = totalSupply.add(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(address(0), to, value);
    }

    function _burn(address from, uint value) internal {
        balanceOf[from] = balanceOf[from].sub(value);
        totalSupply = totalSupply.sub(value);
        emit Transfer(from, address(0), value);
    }

    function _approve(address owner, address spender, uint value) private {
        allowance[owner][spender] = value;
        emit Approval(owner, spender, value);
    }

    function _transfer(address from, address to, uint value) private {
        balanceOf[from] = balanceOf[from].sub(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(from, to, value);
    }

    function approve(address spender, uint value) external virtual override returns (bool) {
        _approve(msg.sender, spender, value);
        return true;
    }

    function transfer(address to, uint value) external override returns (bool) {
        _transfer(msg.sender, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint value) external override returns (bool) {
        if (allowance[from][msg.sender] != type(uint).max - 1) {
            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
        }
        _transfer(from, to, value);
        return true;
    }

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
        require(deadline >= block.timestamp, 'RYZRSwap: TIMESTAMP_DEADLINE_EXPIRED');
        bytes32 digest = keccak256(
            abi.encodePacked(
                '\x19\x01',
                DOMAIN_SEPARATOR,
                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
            )
        );
        address recoveredAddress = ECDSA.recover(digest, v, r, s);
        require(recoveredAddress != address(0) && recoveredAddress == owner, 'RYZRSwap: SIGNATURE_IS_INVVALID');
        _approve(owner, spender, value);
    }
}

interface IRYZRSwapRouter {
    function pairFeeAddress(address pair) external view returns (address);
    function adminFee() external view returns (uint256);
    function feeAddressGet() external view returns (address);
}

	/**	
 * @dev Contract module that helps prevent reentrant calls to a function.	
 *	
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier	
 * available, which can be applied to functions to make sure there are no nested	
 * (reentrant) calls to them.	
 *	
 * Note that because there is a single `nonReentrant` guard, functions marked as	
 * `nonReentrant` may not call one another. This can be worked around by making	
 * those functions `private`, and then adding `external` `nonReentrant` entry	
 * points to them.	
 *	
 * TIP: If you would like to learn more about reentrancy and alternative ways	
 * to protect against it, check out our blog post	
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].	
 *	
 * _Since v2.5.0:_ this module is now much more gas efficient, given net gas	
 * metering changes introduced in the Istanbul hardfork.	
 */	
contract ReentrancyGuard {	
    bool private _notEntered;	
    constructor () {	
        // Storing an initial non-zero value makes deployment a bit more	
        // expensive, but in exchange the refund on every call to nonReentrant	
        // will be lower in amount. Since refunds are capped to a percetange of	
        // the total transaction's gas, it is best to keep them low in cases	
        // like this one, to increase the likelihood of the full refund coming	
        // into effect.	
        _notEntered = true;	
    }	
    /**	
     * @dev Prevents a contract from calling itself, directly or indirectly.	
     * Calling a `nonReentrant` function from another `nonReentrant`	
     * function is not supported. It is possible to prevent this from happening	
     * by making the `nonReentrant` function external, and make it call a	
     * `private` function that does the actual work.	
     */	
    modifier nonReentrant() {	
        // On the first call to nonReentrant, _notEntered will be true	
        require(_notEntered, "ReentrancyGuard: reentrant call");	
        // Any calls to nonReentrant after this point will fail	
        _notEntered = false;	
        _;	
        // By storing the original value once again, a refund is triggered (see	
        // https://eips.ethereum.org/EIPS/eip-2200)	
        _notEntered = true;	
    }	
}

interface IRYZRSwapPair {
    function baseToken() external view returns (address);
    function getTotalFee() external view returns (uint);
    function updateTotalFee(uint totalFee) external returns (bool);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast, address _baseToken);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, uint amount0Fee, uint amount1Fee, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
    function setBaseToken(address _baseToken) external;
}

interface IRYZRSwapFactory {
    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);
    function pairExist(address pair) external view returns (bool);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function routerInitialize(address) external;
    function routerAddress() external view returns (address);
}

contract RYZRSwapPair is IRYZRSwapPair, RYZRSwapERC20, ReentrancyGuard {
    using SafeMath  for uint;
    using UQ112x112 for uint224;

    uint public constant override MINIMUM_LIQUIDITY = 10**3;
    bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));

    IRYZRSwapRouter public routerAddress;

    address public immutable override factory;
    address public override token0;
    address public override token1;
    address public override baseToken;
    uint public totalFee = 1000;

    uint112 private reserve0;           
    uint112 private reserve1;           
    uint32  private blockTimestampLast; 

    uint public override price0CumulativeLast;
    uint public override price1CumulativeLast;
    uint public override kLast; 

    uint private unlocked = 1;
    modifier lock() { // IMPORTANT TO PREVENT RE-ENTRANCY
        require(msg.sender == address(routerAddress), "RYZRSwap: ONLY_ROUTER_CAN_ACCESS");
        require(unlocked == 1, "RYZRSwap: LOCKED");
        unlocked = 0;
        _;
        unlocked = 1;
    }

    function getReserves() public view override returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast, address _baseToken) {
        _reserve0 = reserve0;
        _reserve1 = reserve1;
        _blockTimestampLast = blockTimestampLast;
        _baseToken = baseToken;
    }

    function _safeTransfer(address token, address to, uint value, bool isSwapping) private nonReentrant {
        if(value == 0){
            return;
        }
        if (routerAddress.pairFeeAddress(address(this)) == token && isSwapping){
            uint256 adminFee = routerAddress.adminFee();
            if(adminFee != 0){
                uint256 getOutFee = value.mul(adminFee) / (10000);
                (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, routerAddress.feeAddressGet(), getOutFee));
                require(success && (data.length == 0 || abi.decode(data, (bool))), "RYZRSwap: TRANSFER_FAILED");
                value = value.sub(getOutFee);
            }
            (bool success1, bytes memory data1) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
            require(success1 && (data1.length == 0 || abi.decode(data1, (bool))), "RYZRSwap: TRANSFER_FAILED");
        }else {
            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
            require(success && (data.length == 0 || abi.decode(data, (bool))), "RYZRSwap: TRANSFER_FAILED");
        }
    }

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);
    event Initialize(address token0, address token1, IRYZRSwapRouter router, address caller);	
    event BaseTokenSet(address baseToken, address caller);	
    event TotalFeeUpdate(uint totalFee);

    constructor() {
        factory = msg.sender;
    }

    // called once by the factory at time of deployment
    function initialize(address _token0, address _token1) external override {
        require(msg.sender == factory, "RYZRSwap: ONLY_FACTORY_CAN_CALL"); 
        require(_token0 != address(0) && _token1 != address(0), "RYZRSwap: INVALID_ADDRESS");
        token0 = _token0;
        token1 = _token1;
        routerAddress = IRYZRSwapRouter(IRYZRSwapFactory(factory).routerAddress());
        emit Initialize(token0, token1, routerAddress, msg.sender);
    }

    // update reserves and, on the first call per block, price accumulators
    function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
        require(balance0 <= type(uint112).max && balance1 <= type(uint112).max, "RYZRSwap: OVERFLOW_ERROR");
        uint32 blockTimestamp = uint32(block.timestamp % 2**32);
        uint32 timeElapsed = blockTimestamp - blockTimestampLast; 
        if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
            price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
            price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
        }
        reserve0 = uint112(balance0);
        reserve1 = uint112(balance1);
        blockTimestampLast = blockTimestamp;
        emit Sync(reserve0, reserve1);
    }

    // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
    function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
        address feeTo = IRYZRSwapFactory(factory).feeTo();
        feeOn = feeTo != address(0);
        uint _kLast = kLast; 
        if (feeOn) {
            if (_kLast != 0) {
                uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                uint rootKLast = Math.sqrt(_kLast);
                if (rootK > rootKLast) {
                    uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                    uint denominator = rootK.mul(5).add(rootKLast);
                    uint liquidity = numerator / denominator;
                    if (liquidity > 0) _mint(feeTo, liquidity);
                }
            }
        } else if (_kLast != 0) {
            kLast = 0;
        }
    }