# 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**:

```solidity
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

{% hint style="info" %}
Since Solidity **0.4.22**, the `constructor` keyword solves this issue:

```solidity
//Correct constructor definition for Solidity >=0.4.22
constructor() public {
    owner = msg.sender;
}
```

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

{% tabs %}
{% tab title="Exploit" %}
A common pattern that becomes vulnerable:

```solidity
contract Wallet {
    address public owner;

    function wallet() public {   // Incorrect: contract name is "Wallet"
        owner = msg.sender;      // Anyone can now call this
    }
}
```

Using [cast](https://getfoundry.sh/cast/overview), an attacker simply calls `wallet()` after deployment and becomes the owner.

```shellscript
cast call $CONTRACT_ADDRESS "wallet()" --rpc-url $RPC_URL --private-key $PK -vv 
```

{% endtab %}
{% endtabs %}

## Resources

{% embed url="<https://github.com/AmazingAng/WTF-Solidity/tree/main/Languages/en/11_Modifier_en>" %}

{% embed url="<https://swcregistry.io/docs/SWC-118/>" %}

{% embed url="<https://scs.owasp.org/SCWE/SCSVS-ARCH/SCWE-070/>" %}
