Skip to content

Instantly share code, notes, and snippets.

@coffiasd
Created July 23, 2023 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coffiasd/c2ff1a2d718d286b9064873be2fe079a to your computer and use it in GitHub Desktop.
Save coffiasd/c2ff1a2d718d286b9064873be2fe079a to your computer and use it in GitHub Desktop.
CREATE2 and CREATE
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
import {TokenTemplate} from "../src/TokenTemplate.sol";
contract Create2Test is Test {
function setUp() public {}
function testDeploy() public {
uint256 _salt = 1;
bytes32 hash = keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
_salt,
keccak256(type(TokenTemplate).creationCode)
)
);
address preAddr = address(uint160(uint(hash)));
address actuallyAddr = deploy(type(TokenTemplate).creationCode, _salt);
assert(preAddr == actuallyAddr);
}
function deploy(
bytes memory bytecode,
uint _salt
) public payable returns (address) {
address addr;
assembly {
addr := create2(
callvalue(), // wei sent with current call
// Actual code starts after skipping the first 32 bytes
add(bytecode, 0x20),
mload(bytecode), // Load the size of code contained in the first 32 bytes
_salt // Salt from function arguments
)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return addr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment