Incorrect Constructor Name

SCWE-070: Incorrect Constructor Name

Theory

Constructor is a special function, which will automatically run once during contract deployment. Each contract can have one constructor. They often perform critical, privileged actions such as setting the owner of the contract.

In Solidity versions prior to 0.4.22, constructors were defined by giving a function the same name as the contract:

contract Example {
    //Constructor function of the "Example" contract  
    //for Solidity <0.4.22 
    function Example() public {
        owner = msg.sender; 
    }
}

If the developer misspelled the function name, changed the contract name without updating the constructor, or refactored code incorrectly, the function would not be treated as a constructor. Instead, it became a public callable function.

This means:

  • The contract deploys without running the intended constructor logic.

  • Any user can later call the "constructor" function.

  • If this function sets state variables such as owner, admin, or critical configuration, an attacker can take over the contract.

Practice

Since Solidity 0.4.22, the constructor keyword solves this issue:

However, many legacy contracts still use the old syntax, and some modern contracts inherit from older codebases, making this vulnerability still important in audits.

A common pattern that becomes vulnerable:

Using cast, an attacker simply calls wallet() after deployment and becomes the owner.

Resources

Last updated

Was this helpful?