0

I'm trying to understand function overrides so far I'm understanding the concept. However, I'm wondering What happens with attached modifiers if a function is overridden? do they have to be re-attached?

1 Answer 1

0

Consider the following contracts:

// SPDX-License-Identifier: Unlicense

pragma solidity 0.8.14;

contract A {
    modifier modified() {
        revert("Modified");
        // Before
        _;
        // After
    }

    function test1() public virtual modified {
        // A.test1 body
    }
    function test2() public virtual modified {
        // A.test2 body
    }
}

contract B is A {
    function test1() public override {
        // B.test1 body
    }
    function test2() public override {
        super.test2();
        // B.test2 body
    }
}

First of all, when B.test1() overrides A.test1(), B.test1() does not automatically call the super implementation. This means that when you call B.test1(), A.test1() will never be invoked, so the modified modifier will not kick in.

In the case of B.test2(), it explicitly calls A.test2(). As A.test2() has been modified with modifier modified, the code inside modified becomes “part of” A.test2(). So yes, when B.test2() is called, it will call A.test2() including modified.

So no, modified doesn’t need to be reattached. But keep in mind that when B.test2() overrides the modified function A.test2(), the modifier is not “unattached” and “reattached” to B.test2(). Once A.test2() has been modified, the code of A.test2() is modified to “include” the code inside modified, so to speak. So the equivalent code for B.test2() is:

revert("Modified");
// Before
// A.test2 body
// After
// B.test2 body

and not:

revert("Modified");
// Before
// A.test2 body
// B.test2 body
// After

Deploy B in Remix IDE (to JavaScript VM is enough, no need to deploy to a public blockchain) and try it out. Call B.test1() and B.test2() and see what happens, and poke it around to see how it behaves. Whenever you have this type of doubt, Remix IDE is your friend.

P.S. If on the other hand you want the modifier behaviour to wrap the overridden function, then this could be achieved as follows:

// SPDX-License-Identifier: Unlicense

pragma solidity 0.8.14;

contract A {
    modifier modified() {
        // Before
        _;
        // After
    }
    function _unmodifiedTest3() internal virtual {
        // Something
    }
    function test3() external modified {
        _unmodifiedTest3();
    }
}

contract B is A {
    function _unmodifiedTest3() internal override {
        super._unmodifiedTest3();
        // Something extra
    }
}

The equivalent code for B.test3() will be:

// Before
// Something
// Something extra
// After

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.