1

I just came across this while testing around with the Diamond Storage pattern. Here is a 'pure' function that reads from storage. This had me wondering, is there actually any difference between pure and view functions from a compiler pov? Is this bug known?

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

import "forge-std/Test.sol";
import "forge-std/console.sol";

struct Settings {
    uint256 a;
    uint256 b;
}

contract MyContract {
    Settings settings;

    constructor() {
        getSettingsDS().a = 123;
        getSettingsDS().b = 456;
    }

    function getSettingsDS() internal pure returns (Settings storage s) {
        assembly {
            s.slot := 0xabc
        }
    }

    // // @note this will give a compiler error:
    // // Compiler run failed
    // // error[2527]: TypeError: Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires "view".
    // function getSettings() public pure returns (Settings memory) {
    //     return settings;
    // }

    // @note this won't
    function getSettings() public pure returns (Settings memory) {
        return getSettingsDS();
    }
}

contract TestSettings is Test {
    function test_setUp() public {
        MyContract myContract = new MyContract();

        assertEq(myContract.getSettings().a, 123);
        assertEq(myContract.getSettings().b, 456);
    }
}
1
  • One can argue that technically getSettingsDS isn't reading storage, it is just returning a numeric value that happens to be a storage slot. On the other hand getSettings does read from storage because it is converting to memory. You should report the finding to solidity developers. It should trigger at least a warning.
    – Ismael
    Jun 7, 2022 at 22:42

0

Your Answer

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

Browse other questions tagged or ask your own question.