3

I am new to solidity, can you please explain the create2 function?

assembly {
    pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}

2 Answers 2

1
  • 0 is the amount of Ether to be sent to the contract being deployed.

  • add(bytecode, 0x20) This is the location in memory where the contract bytecode starts. The add opcode adds the two values together to get the starting memory location of the bytecode. The 0x20 offset is used to skip over the first 32 bytes of the bytecode, which contain the length of the bytecode.

  • mload(bytecode) is to loads the bytecode at the memory location specified previously.

  • salt is a random 32-byte value used to generate a deterministic address for the deployed contract. The salt value is usually derived from a combination of the deploying contract's address, the contract creation code, and any relevant parameters.

The Factory can have a view function such as this one to get a deployed address:

function computeDestinationAddress(bytes32 salt, bytes memory bytecode) external view returns (address) {
    bytes32 bytecodeHash = keccak256(bytecode);
    bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, bytecodeHash));
    return address(bytes20(_data << 96));
}
1
  • Thanks for your answer. Commented Aug 3, 2023 at 10:01
1

The create2 is an opcode that takes 4 stack arguments: endowment, memory_start, memory_length, salt. Behaves identically to CREATE (0xf0), except using keccak256( 0xff ++ address ++ salt ++ keccak256(init_code))[12:] instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.

In other words: The CREATE2 opcode gives us the ability predict the address where a contract will be deployed, without ever having to do so.

Your Answer

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

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