Create2.sol 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.7.0) (utils/Create2.sol)
  3. pragma solidity ^0.8.0;
  4. /**
  5. * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
  6. * `CREATE2` can be used to compute in advance the address where a smart
  7. * contract will be deployed, which allows for interesting new mechanisms known
  8. * as 'counterfactual interactions'.
  9. *
  10. * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
  11. * information.
  12. */
  13. library Create2 {
  14. /**
  15. * @dev Deploys a contract using `CREATE2`. The address where the contract
  16. * will be deployed can be known in advance via {computeAddress}.
  17. *
  18. * The bytecode for a contract can be obtained from Solidity with
  19. * `type(contractName).creationCode`.
  20. *
  21. * Requirements:
  22. *
  23. * - `bytecode` must not be empty.
  24. * - `salt` must have not been used for `bytecode` already.
  25. * - the factory must have a balance of at least `amount`.
  26. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
  27. */
  28. function deploy(
  29. uint256 amount,
  30. bytes32 salt,
  31. bytes memory bytecode
  32. ) internal returns (address) {
  33. address addr;
  34. require(address(this).balance >= amount, "Create2: insufficient balance");
  35. require(bytecode.length != 0, "Create2: bytecode length is zero");
  36. /// @solidity memory-safe-assembly
  37. assembly {
  38. addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
  39. }
  40. require(addr != address(0), "Create2: Failed on deploy");
  41. return addr;
  42. }
  43. /**
  44. * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
  45. * `bytecodeHash` or `salt` will result in a new destination address.
  46. */
  47. function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
  48. return computeAddress(salt, bytecodeHash, address(this));
  49. }
  50. /**
  51. * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
  52. * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
  53. */
  54. function computeAddress(
  55. bytes32 salt,
  56. bytes32 bytecodeHash,
  57. address deployer
  58. ) internal pure returns (address) {
  59. bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash));
  60. return address(uint160(uint256(_data)));
  61. }
  62. }