Create2.sol 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. * _Available since v2.5.0._
  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}. Note that
  17. * a contract cannot be deployed twice using the same salt.
  18. */
  19. function deploy(bytes32 salt, bytes memory bytecode) internal returns (address) {
  20. address addr;
  21. // solhint-disable-next-line no-inline-assembly
  22. assembly {
  23. addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
  24. }
  25. require(addr != address(0), "Create2: Failed on deploy");
  26. return addr;
  27. }
  28. /**
  29. * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the `bytecodeHash`
  30. * or `salt` will result in a new destination address.
  31. */
  32. function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
  33. return computeAddress(salt, bytecodeHash, address(this));
  34. }
  35. /**
  36. * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
  37. * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
  38. */
  39. function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) {
  40. bytes32 _data = keccak256(
  41. abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
  42. );
  43. return address(bytes20(_data << 96));
  44. }
  45. }