Initializable.sol 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity >=0.4.24 <0.7.0;
  3. /**
  4. * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
  5. * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
  6. * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
  7. * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
  8. *
  9. * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
  10. * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
  11. *
  12. * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
  13. * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
  14. */
  15. abstract 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 protect an initializer function from being invoked twice.
  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. }