EIP-1014 describes salt as bytes32
.
However, the function create2
written in assembly allows passing byte string of arbitrary size as the salt
parameter.
Example
function deploy(bytes memory bytecode, bytes memory _salt) public payable {
address addr;
/*
NOTE: How to call create2
create2(v, p, n, s)
create new contract with code at memory p to p + n
and send v wei
and return the new address
where new address = first 20 bytes of keccak256(0xff + address(this) + s + keccak256(mem[p…(p+n)))
s = big-endian 256-bit value
*/
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)
}
}
emit Deployed(addr, _salt);
}
How to precompute deployed contract address in that case?
This function works for bytes32
salt, but gives incorrect result here.
function getAddress(
bytes memory bytecode,
bytes memory _salt
) public view returns (address) {
bytes32 hash = keccak256(
abi.encodePacked(bytes1(0xff), address(this), _salt, keccak256(bytecode))
);
// NOTE: cast last 20 bytes of hash to address
return address(uint160(uint(hash)));
}
What should I change?