Initializable.sol 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.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 {ERC1967Proxy-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. * [CAUTION]
  16. * ====
  17. * Avoid leaving a contract uninitialized.
  18. *
  19. * An uninitialized contract can be used in certain kinds of exploits since it may allow an attacker to take control of
  20. * the contract. This includes the implementation contract behind a proxy. You can either invoke the initializer
  21. * manually, independently of initialization of the proxy, or you can include a constructor to automatically mark it as
  22. * 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. }