Initializable.sol 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // SPDX-License-Identifier: MIT
  2. // solhint-disable-next-line compiler-version
  3. pragma solidity >=0.4.24 <0.8.0;
  4. /**
  5. * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
  6. * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
  7. * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
  8. * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
  9. *
  10. * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
  11. * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
  12. *
  13. * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
  14. * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
  15. */
  16. abstract contract Initializable {
  17. /**
  18. * @dev Indicates that the contract has been initialized.
  19. */
  20. bool private _initialized;
  21. /**
  22. * @dev Indicates that the contract is in the process of being initialized.
  23. */
  24. bool private _initializing;
  25. /**
  26. * @dev Modifier to protect an initializer function from being invoked twice.
  27. */
  28. modifier initializer() {
  29. require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
  30. bool isTopLevelCall = !_initializing;
  31. if (isTopLevelCall) {
  32. _initializing = true;
  33. _initialized = true;
  34. }
  35. _;
  36. if (isTopLevelCall) {
  37. _initializing = false;
  38. }
  39. }
  40. /// @dev Returns true if and only if the function is running in the constructor
  41. function _isConstructor() private view returns (bool) {
  42. // extcodesize checks the size of the code stored in an address, and
  43. // address returns the current address. Since the code is still not
  44. // deployed when running a constructor, any checks on its code size will
  45. // yield zero, making it an effective way to detect if a contract is
  46. // under construction or not.
  47. address self = address(this);
  48. uint256 cs;
  49. // solhint-disable-next-line no-inline-assembly
  50. assembly { cs := extcodesize(self) }
  51. return cs == 0;
  52. }
  53. }