In Initializable.sol - modifier initializer(), what's the need to verify "address(this)" is a contract?

In the modifier initializer(), the require statement also checks !AddressUpgradeable.isContract(address(this)) (see code below). I'm wondering why we need to verify that address(this) is not a contract here. Doesn't address(this) always refer to an instance of the smart contract? What is the scenario where (!AddressUpgradeable.isContract(address(this)) && _initialized == 1) returns true? Thank you!

modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

You probably want to provide a link to that code on GitHub.

For one, it doesn't appear in this Initializable.sol.


Anyway, you're right that address(this) is the address of this contract.

However, AddressUpgradeable.isContract(someAddress) returns true if and only if there is actually a contract bytecode deployed at someAddress.

And when it is called from the constructor of a contract, that bytecode has not yet been deployed at that address (but rather, it is kind of in the process of "being deployed" there).

So in short, AddressUpgradeable.isContract(address(this)) is used here in order to determine if this modifier is invoked from the constructor of the contract (i.e., during deployment), or from any other function of the contract (i.e., after deployment).


BTW, here is the link to the related code (posted in your question) on GitHub.

1 Like

Thanks barakman.
I also had the same type of problem.

1 Like

You're welcome.
I basically just looked into the code and figured it out based on common sense.
So my answer probably needs some verification, in case that common sense was wrong.