About: An IoT and blockChain developer;
interested in Cloud Computing;
love coding...
Location:
Saskatoon, Saskatchewan
Joined:
Oct 9, 2021
Tutorial - Using create2 to predict the contract address before deploying
Publish Date: Jun 13 '22
15 0
This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of Solidity.
The purpose of building this blog is to write down the detailed operation history and my memo for learning the dApps and solidity programming.
If you are also interested and want to get hands dirty, just follow these steps below and have fun!~
The create2 opcode gives us the ability to predict the contract address where a contract will be deployed. This opens up lots of possibilities to improve user onboarding and scalability.
contract overview
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
//Use Create2 to know contract address before it is deployed.
contract DeployWithCreate2 {
address public owner;
constructor(address _owner) {
owner = _owner;
}
}
contract Create2Factory {
event Deploy(address addr);
// to deploy another contract using owner address and salt specified
function deploy(uint _salt) external {
DeployWithCreate2 _contract = new DeployWithCreate2{
salt: bytes32(_salt) // the number of salt determines the address of the contract that will be deployed
}(msg.sender);
emit Deploy(address(_contract));
}
// get the computed address before the contract DeployWithCreate2 deployed using Bytecode of contract DeployWithCreate2 and salt specified by the sender
function getAddress(bytes memory bytecode, uint _salt) public view returns (address) {
bytes32 hash = keccak256(
abi.encodePacked(
bytes1(0xff), address(this), _salt, keccak256(bytecode)
)
);
return address (uint160(uint(hash)));
}
// get the ByteCode of the contract DeployWithCreate2
function getBytecode(address _owner) public pure returns (bytes memory) {
bytes memory bytecode = type(DeployWithCreate2).creationCode;
return abi.encodePacked(bytecode, abi.encode(_owner));
}
}
We use Create2Factory to deploy the contract DeployWithCreate2. First we get the byteCode of the contract DeployWithCreate2 using the function getBytecode, and then we use byteCode and owner-specified salt to compute the address of contract DeployWithCreate2. Finally we use function deploy to deploy the contract DeployWithCreate2 to see the actuall contract address.
Welcome to visit the Git repo for source code (Create2.sol or Example-44), and feel free to reach me by leaving a message below or via email found in my profile.