Solidity – How to Add a Modifier to Public State Variable

modifierssoliditysolidity-0.8.x

I have a contract that looks like this

pragma solidity >=0.7.0 <0.9.0;

contract SomeContract {

    uint256 public id;
    address public creator;

    enum Status {ACTIVE, INACTIVE}

    Status contractStatus;

    modifier checkStatus {

        require(contractStatus == Status.ACTIVE);

        _;

    }

    modifier onlyCreator {
    
        require(msg.sender == creator);

        _;

    }

    constructor() {

        contractStatus = Status.ACTIVE;
        creator = msg.sender;

    }

    function doSomething() external checkStatus {

        // do something here

    }

    function changeStatus(bool _isActive) external onlyCreator {

        if (_isActive) {
            contractStatus = Status.ACTIVE;
        } else {
            contractStatus = Status.INACTIVE;
        }
        
    }}

}

This contract works fine. The problem is after I deactivate the contract, people still can access public state variables like id and creator because solidity automatically creates a getter for each of these variables. Is there any faster way besides making it internal and creating my own getter and adding a modifier to it?

Best Answer

By default public variables have already built-in getter, you can stop that by changing the variable type to private or internal. But don't get confused with the word "private", because nothing is really private on the blockchain. Even if you change id and creator to private type this will remove the automatic getters that you see in Remix, but this data is not hidden and everyone can still access it.

On top of my head the first ideas I have to save sensitive data in smart contracts are via asymmetric encryption ( the contract is saving encrypted format of the data and the data is being decrypted on the front end ) or keep the sensitive data offchain and make connection to it with the smart contract.

Related Topic