Initializable.sol 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity >=0.4.24 <0.7.0;
  3. /**
  4. * @title Initializable
  5. *
  6. * @dev Helper contract to support initializer functions. To use it, replace
  7. * the constructor with a function that has the `initializer` modifier.
  8. * WARNING: Unlike constructors, initializer functions must be manually
  9. * invoked. This applies both to deploying an Initializable contract, as well
  10. * as extending an Initializable contract via inheritance.
  11. * WARNING: When used with inheritance, manual care must be taken to not invoke
  12. * a parent initializer twice, or ensure that all initializers are idempotent,
  13. * because this is not dealt with automatically as with constructors.
  14. */
  15. contract Initializable {
  16. /**
  17. * @dev Indicates that the contract has been initialized.
  18. */
  19. bool private _initialized;
  20. /**
  21. * @dev Indicates that the contract is in the process of being initialized.
  22. */
  23. bool private _initializing;
  24. /**
  25. * @dev Modifier to use in the initializer function of a contract.
  26. */
  27. modifier initializer() {
  28. require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
  29. bool isTopLevelCall = !_initializing;
  30. if (isTopLevelCall) {
  31. _initializing = true;
  32. _initialized = true;
  33. }
  34. _;
  35. if (isTopLevelCall) {
  36. _initializing = false;
  37. }
  38. }
  39. /// @dev Returns true if and only if the function is running in the constructor
  40. function _isConstructor() private view returns (bool) {
  41. // extcodesize checks the size of the code stored in an address, and
  42. // address returns the current address. Since the code is still not
  43. // deployed when running a constructor, any checks on its code size will
  44. // yield zero, making it an effective way to detect if a contract is
  45. // under construction or not.
  46. address self = address(this);
  47. uint256 cs;
  48. // solhint-disable-next-line no-inline-assembly
  49. assembly { cs := extcodesize(self) }
  50. return cs == 0;
  51. }
  52. }