Initializable.sol 2.2 KB

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