Create2.sol 2.4 KB

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