β—† Purpose

to create the pair address of tokenA and tokenB

β—† Input & Return value

(address tokenA, address tokenB) β‡’ (address pair)

β—† Example

tokenA(USDC) = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48

tokenB(WETH) = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2

β‡’

pair(USDC/WETH) = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc

β—† Code and Explain

create2 is one of opcode to create new contract address.

There are two opcodes to create contract address. β€œCREATE” and β€œCREATE2”.

If you want to dive deep to this, check this page πŸ‘‰Β Create2

function createPair(address tokenA, address tokenB) external returns (address pair) {
        require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
        (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
        require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
        bytes memory bytecode = type(UniswapV2Pair).creationCode;
        bytes32 salt = keccak256(abi.encodePacked(token0, token1));
        assembly {
            pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        IUniswapV2Pair(pair).initialize(token0, token1);
        getPair[token0][token1] = pair;
        getPair[token1][token0] = pair; // populate mapping in the reverse direction
        allPairs.push(pair);
        emit PairCreated(token0, token1, pair, allPairs.length);
    }

β—† Resources

https://github.com/Uniswap/v2-core/blob/master/contracts/UniswapV2Factory.sol#L23

Create2