14

Why would someone use create2() inline assembly code to create a child contract in factory pattern as opposed to using newContract() to create an instance of "newContract"?

What are the upsides and downsides of using one over the other?

2 Answers 2

25

CREATE opcode is used by default when deploying smart contracts. The deployed contract address is calculated like this.

keccak256(senderAddress, nonce)

CREATE2 opcode is introduced later and allows you to predetermine the contract address. Contract address is computed like this.

keccak256(0xFF, senderAddress, salt, bytecode)

0xFF parameter is a constant to prevent collision with CREATE opcode.

salt parameter is a value sender sends when deploying contract.

bytecode parameter is, you probably guessed it, the bytecode of the smart contract you want to deploy.

If you want to predetermine the contract address before deploying, you can simply loop through different salt values and select the one you like (or want).

A great example of using CREATE2 can be seen here. Application of CREATE2 opcode

Edit: Creating a contract with new keyword requires you to know the contract's source code. After creating a contract with new keyword, it will return the created contract's address.

This also uses CREATE opcode behind to create the contract.

2
  • What about just calling the smart contract() ? Also what are the applications of knowing a contract address before you create it?
    – YulePale
    Jun 4, 2021 at 19:15
  • 1
    Sorry for the late response. I've edited the answer. Jun 5, 2021 at 15:38
1

If you are looking for an example you can refer this link, using CREATE2 one project can deploy with same contract address on multiple chains.

https://github.com/Elefria-Labs/playground-contracts/blob/main/test/Create2.test.ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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