Create2.sol 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (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. assembly {
  37. addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
  38. }
  39. require(addr != address(0), "Create2: Failed on deploy");
  40. return addr;
  41. }
  42. /**
  43. * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
  44. * `bytecodeHash` or `salt` will result in a new destination address.
  45. */
  46. function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
  47. return computeAddress(salt, bytecodeHash, address(this));
  48. }
  49. /**
  50. * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
  51. * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
  52. */
  53. function computeAddress(
  54. bytes32 salt,
  55. bytes32 bytecodeHash,
  56. address deployer
  57. ) internal pure returns (address) {
  58. bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash));
  59. return address(uint160(uint256(_data)));
  60. }
  61. }