Create2.sol 2.4 KB

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