Skip to main content

When a Solidity storage reference changes contract state

Updated 2 min readMarkdown
When a Solidity storage reference changes contract state

Both functions below assign 27 to a field called score. Call changeStorage(27) and the contract stores 27. Call changeCopy(27) on a fresh contract and the function returns 27 while the stored score stays at 10.

The difference is on the assignment line. A local storage variable refers to the existing record. A memory variable initialized from storage gets a copy. You can check both outcomes in the same Foundry test file.

Save this as test/DataLocations.t.sol in a Foundry project. The file uses Solidity 0.8.30 and does not need a test library.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract Scoreboard {
    struct Record {
        uint256 score;
    }

    Record private current = Record(10);

    function score() external view returns (uint256) {
        return current.score;
    }

    function changeStorage(uint256 value) external {
        Record storage entry = current;
        entry.score = value;
    }

    function changeCopy(uint256 value) external view returns (uint256) {
        Record memory entry = current;
        entry.score = value;
        return entry.score;
    }
}

contract DataLocationsTest {
    function testStorageReferenceChangesState() public {
        Scoreboard board = new Scoreboard();

        board.changeStorage(27);

        require(board.score() == 27, "expected a state change");
    }

    function testMemoryCopyLeavesStateAlone() public {
        Scoreboard board = new Scoreboard();

        require(board.changeCopy(27) == 27, "expected the changed copy");
        require(board.score() == 10, "expected the original state");
    }
}

Run just these two tests.

forge test --match-contract DataLocationsTest --use 0.8.30

Each test deploys a fresh contract. The storage test reads state after changing the reference. The memory test checks the returned copy and then reads the stored score separately. Both passed with Forge 1.7.1 and Solidity 0.8.30.

If a function is only meant to preview a change, test the stored value as well as the return value. The return value alone looks the same in both cases.

Read the broader guide to storage, memory and calldata

Solidity reference types and assignment rules

About the author

  • I’m HaoJie Luo, an independent developer working on Web3 and AI applications. I write about payment workflows, wallet permissions and content licensing, with runnable examples and tests. My client handovers typically include testnet delivery and deployment scripts. Clients or their operations teams handle production deployment. The public examples use separate business logic from client projects. Projects and engineering notes: https://fone.cc/?utm_source=hashnode&utm_medium=referral&utm_campaign=profile

No comments yet. Be the first to comment.