Initializable.sol 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.0-rc.1 (proxy/utils/Initializable.sol)
  3. pragma solidity ^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 {ERC1967Proxy-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. * [CAUTION]
  17. * ====
  18. * Avoid leaving a contract uninitialized.
  19. *
  20. * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
  21. * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
  22. * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
  23. *
  24. * [.hljs-theme-light.nopadding]
  25. * ```
  26. * /// @custom:oz-upgrades-unsafe-allow constructor
  27. * constructor() initializer {}
  28. * ```
  29. * ====
  30. */
  31. abstract contract Initializable {
  32. /**
  33. * @dev Indicates that the contract has been initialized.
  34. */
  35. bool private _initialized;
  36. /**
  37. * @dev Indicates that the contract is in the process of being initialized.
  38. */
  39. bool private _initializing;
  40. /**
  41. * @dev Modifier to protect an initializer function from being invoked twice.
  42. */
  43. modifier initializer() {
  44. require(_initializing || !_initialized, "Initializable: contract is already initialized");
  45. bool isTopLevelCall = !_initializing;
  46. if (isTopLevelCall) {
  47. _initializing = true;
  48. _initialized = true;
  49. }
  50. _;
  51. if (isTopLevelCall) {
  52. _initializing = false;
  53. }
  54. }
  55. }