Initializable.sol 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // SPDX-License-Identifier: MIT
  2. // solhint-disable-next-line compiler-version
  3. pragma solidity ^0.8.0;
  4. import "./Address.sol";
  5. /**
  6. * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
  7. * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
  8. * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
  9. * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
  10. *
  11. * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
  12. * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
  13. *
  14. * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
  15. * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
  16. */
  17. abstract contract Initializable {
  18. /**
  19. * @dev Indicates that the contract has been initialized.
  20. */
  21. bool private _initialized;
  22. /**
  23. * @dev Indicates that the contract is in the process of being initialized.
  24. */
  25. bool private _initializing;
  26. /**
  27. * @dev Modifier to protect an initializer function from being invoked twice.
  28. */
  29. modifier initializer() {
  30. require(_initializing || !_initialized, "Initializable: contract is already initialized");
  31. bool isTopLevelCall = !_initializing;
  32. if (isTopLevelCall) {
  33. _initializing = true;
  34. _initialized = true;
  35. }
  36. _;
  37. if (isTopLevelCall) {
  38. _initializing = false;
  39. }
  40. }
  41. }