[Ethereum] Accessing not public variables

accesssolidityvisibilityweb3js

Is it possible as the creater of the smart contract to access a not public variable? E.g.:

contract MyContract {

    uint256 someLevel;

    function changeLevel(uint _newLevel) public {
        someLevel = _newLevel;
    }
}

How would I access in this case someLevel via web3 or at all?

Best Answer

All variables on Ethereum are accessible and readable by everyone in the contract storage, even if they are marked private. In the situation where you want to access the contract storage, you can do so using web3.eth.getStorageAt():

web3.eth.getStorageAt(contractAddress, 0)
.then(console.log);

If your contract only stores this one variable, it should be the first index in the storage as noted above.

That being said, in your sample, the variable is not marked private, so then it is made public by default, and there should be a getter function automatically generated for it. So you can simply call that function to read the variable.

Related Topic