|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | +pragma solidity ^0.8.13; |
| 3 | + |
| 4 | +import {Vm} from "forge-std/Vm.sol"; |
| 5 | + |
| 6 | +library Utils { |
| 7 | + // Cheatcodes address, 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D. |
| 8 | + address internal constant VM_ADDRESS = |
| 9 | + address(uint160(uint256(keccak256("hevm cheat code")))); |
| 10 | + Vm internal constant vm = Vm(VM_ADDRESS); |
| 11 | + |
| 12 | + /// @notice Address of the deterministic create2 factory. |
| 13 | + /// @dev This address corresponds to a contracts that is set in the storage |
| 14 | + /// in the genesis file. The same contract with the same address is deployed |
| 15 | + /// in every testnet, so if this script is run in a testnet instead of in a |
| 16 | + /// local environment, it should work. |
| 17 | + address constant DETERMINISTIC_CREATE2_ADDRESS = |
| 18 | + 0x4e59b44847b379578588920cA78FbF26c0B4956C; |
| 19 | + |
| 20 | + function deployWithCreate2( |
| 21 | + bytes memory bytecode, |
| 22 | + bytes32 salt, |
| 23 | + address create2Factory, |
| 24 | + uint256 signerPrivateKey |
| 25 | + ) internal returns (address) { |
| 26 | + if (bytecode.length == 0) { |
| 27 | + revert("Bytecode is not set"); |
| 28 | + } |
| 29 | + address contractAddress = vm.computeCreate2Address( |
| 30 | + salt, |
| 31 | + keccak256(bytecode), |
| 32 | + create2Factory |
| 33 | + ); |
| 34 | + if (contractAddress.code.length != 0) { |
| 35 | + revert("Contract already deployed"); |
| 36 | + } |
| 37 | + |
| 38 | + vm.broadcast(signerPrivateKey); |
| 39 | + (bool success, bytes memory data) = create2Factory.call( |
| 40 | + abi.encodePacked(salt, bytecode) |
| 41 | + ); |
| 42 | + contractAddress = bytesToAddress(data); |
| 43 | + |
| 44 | + if (!success) { |
| 45 | + revert( |
| 46 | + "Failed to deploy contract via create2: create2Factory call failed" |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + if (contractAddress == address(0)) { |
| 51 | + revert( |
| 52 | + "Failed to deploy contract via create2: contract address is zero" |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + if (contractAddress.code.length == 0) { |
| 57 | + revert( |
| 58 | + "Failed to deploy contract via create2: contract code is empty" |
| 59 | + ); |
| 60 | + } |
| 61 | + |
| 62 | + return contractAddress; |
| 63 | + } |
| 64 | + |
| 65 | + function bytesToAddress( |
| 66 | + bytes memory addressOffset |
| 67 | + ) internal pure returns (address addr) { |
| 68 | + assembly { |
| 69 | + addr := mload(add(addressOffset, 20)) |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments