Blog

Basic Access Control ABC


1. Owner Variable:

We declare a public owner variable of type address to store the address of the contract owner. When the contract is deployed, the constructor sets the deployer’s address (msg.sender) as the owner.

2. Modifier onlyOwner:

This modifier is a key feature of the contract. It restricts access to certain functions, ensuring only the owner can call them. The require statement checks if msg.sender (the one calling the function) is the same as the owner. If not, the function call is reverted with an error message: "Not the contract owner". Modifiers are a convenient way to add access control without repeating code.

3. Constructor:

The constructor is executed when the contract is deployed. It sets the owner variable to the address of the deployer (msg.sender).

4. transferOwnership Function:

This function allows the current owner to transfer ownership to a new address. The new owner’s address must not be a zero address (0x0), which could otherwise lock the contract and make it unusable. This function can only be called by the owner due to the onlyOwner modifier.

5. privilegedAction Example:

This is an example of a function restricted to the owner. By using the onlyOwner modifier, only the current owner can execute this function. You can replace the logic inside this function with any privileged action the owner should be able to perform.


Why you could use this instead of OZ Ownable?

Minimalistic: Unlike OpenZeppelin's Ownable, this contract doesn't include additional functionality like renouncing ownership or event emission.

If your goal is simply to restrict access to certain functions for the owner, this minimal approach is sufficient.

Less Complexity: OpenZeppelin's Ownable contract includes extra features and is designed to cover a wide range of use cases, which adds some complexity. In situations where you don't need those extra features, this basic contract reduces complexity and keeps the contract lightweight.

Customizable: You can easily extend this contract by adding more functionalities as needed without pulling in the entire OpenZeppelin library. For example, if you need more fine-grained access control, you can add additional roles.