Create2.sol 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. pragma solidity ^0.5.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 `bytecode`
  30. * or `salt` will result in a new destination address.
  31. */
  32. function computeAddress(bytes32 salt, bytes memory bytecode) internal view returns (address) {
  33. return computeAddress(salt, bytecode, 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, bytes memory bytecodeHash, address deployer) internal pure returns (address) {
  40. bytes32 bytecodeHashHash = keccak256(bytecodeHash);
  41. bytes32 _data = keccak256(
  42. abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHashHash)
  43. );
  44. return address(bytes20(_data << 96));
  45. }
  46. }