Search code examples
ethereumblockchainsolidityweb3jshardhat

How to Ensure Security of a Function in a Solidity Smart Contract?


I'm working on a smart contract in Solidity and I have a function that updates the state of the contract.

Here's a simplified version of my code:

pragma solidity ^0.8.0;

contract MyContract {
    uint public state;

    function updateState(uint _state) public {
        state = _state;
    }
}

I’m concerned about the security of the updateState function. As it stands, any address could call this function and change the state of the contract.

I’ve read about modifiers in Solidity and I think they might be a solution to this problem. However, I’m not sure how to implement them correctly.

Could someone provide an example of how to use a modifier to restrict access to the updateState function? Specifically, I want to restrict access so that only a specific address (e.g., the address that deployed the contract) can call this function.

Any help would be greatly appreciated!


Solution

  • I suggest you use a library for that. The most common one is Openzeppelin's Ownable, you can find some docs here https://docs.openzeppelin.com/contracts/5.x/access-control.

    So the contract will look like this:

    pragma solidity ^0.8.0;
    import '@openzeppelin/contracts/access/Ownable.sol';
    
    contract MyContract is Ownable {
        uint public state;
    
        constructor() Ownable(msg.sender) {}
    
        function updateState(uint _state) public onlyOwner {
            state = _state;
        }
    }