/
Create2.sol
47 lines (33 loc) · 1.21 KB
/
Create2.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Create2 {
error Create2InsufficientBalance(uint256 received, uint256 minimumNeeded);
error Create2EmptyBytecode();
error Create2FailedDeployment();
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) external payable returns (address addr) {
if (msg.value < amount) {
revert Create2InsufficientBalance(msg.value, amount);
}
if (bytecode.length == 0) {
revert Create2EmptyBytecode();
}
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
if (addr == address(0)) {
revert Create2FailedDeployment();
}
}
function computeAddress(bytes32 salt, bytes32 bytecodeHash) external view returns (address addr) {
address contractAddress = address(this);
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, contractAddress)
let start := add(ptr, 0x0b)
mstore8(start, 0xff)
addr := keccak256(start, 85)
}
}
}