Skip to content
Last updated: March 11, 2025

SCWE-069: Shadowing State Variables

Stable Version v0.0.1

This content is in the version-(v0.0.1) and still under active development, so it is subject to change any time (e.g. structure, IDs, content, URLs, etc.).

Send Feedback

Relationships

Description

Shadowing occurs when a state variable in a derived contract uses the same name as one in the base contract. This can lead to confusion and unexpected behavior, as the derived contract will hide the state variable from the base contract, potentially causing errors in contract logic or making it harder to maintain and audit the code.

It is essential to avoid naming state variables in derived contracts the same as those in base contracts to ensure that the intended state is correctly accessed and modified.

Remediation

To avoid state variable shadowing, use unique names for state variables in derived contracts or explicitly refer to the base contract variable using super. This will ensure that the correct state variable is accessed and manipulated as intended.

Vulnerable Contract Example

contract Base {
    uint public balance;

    constructor() {
        balance = 100;
    }
}

contract Derived is Base {
    uint public balance;  // Shadows state variable from Base contract

    function updateBalance(uint amount) public {
        balance = amount;  // Refers to Derived's balance, not Base's balance
    }
}

Fixed Contract Example

contract Base {
    uint public balance;

    constructor() {
        balance = 100;
    }
}

contract Derived is Base {
    uint public newBalance;  // Unique name for Derived contract

    function updateBalance(uint amount) public {
        newBalance = amount;  // Updates Derived's balance without shadowing
    }
}