1

I am studying Uniswap source code and there is something I do not understand in this file:

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

This factory can create new pairs (createPair function):

    bytes memory bytecode = type(UniswapV2Pair).creationCode;
    bytes32 salt = keccak256(abi.encodePacked(token0, token1));
    assembly {
        pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
    }

for me, these 4 lines do the same thing than:

pair = new UniswapV2Pair()

I do not understand what they want to do with the 4 lines of codes. Do you have any idea ?

Thanks a lot

1
  • Here is another source code for flattener + EtherScan verification API: Jan 19 at 9:02
2

The lines you showed are using the new CREATE2 opcode, instead of the regular CREATE opcode (which would be invoked by using pair = new UniswapV2Pair()).

The benefit of using CREATE2 is that the contract address doesn't depend on the transaction nonce, but on other values which do not automatically change. This way the address can be predetermined.

One of the main advantages of predetermined addresses is that the contract only needs to be created if needed - this is the case especially for Layer 2 disputes where the contract is actually created only if a dispute arises and it needs to be resolved with the contract. This way we save in gas costs.

In the case of Uniswap, I've understood they use CREATE2 also due to gas savings; the creation is cheaper. I don't fully understand the system so I Can't much comment on that, but that's what I have been told.

In newer Solidity versions assembly is not needed but CREATE2 can be invoked directly from pure Solidity. Here's some more information: https://docs.openzeppelin.com/cli/2.8/deploying-with-create2

2
  • Thanks a lot but what is the value-add to predict the contract address ?
    – Bob5421
    Jan 19 at 8:01
  • edited answer to answer your question Jan 19 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.