This series will provide answers to the list of Solidity interview questions that were published by RareSkills.
Access control is the concept of limiting permission to a resource and only allowing utilization by those with an authorized role. It is important to control access to certain resources because they may be sensitive or critical to the functioning of the system and could allow an attacker to cause a disruption or commit an exploit. Implementing proper access control mechanisms is vital to maintaining privacy, security and good user experience.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
// SimpleAccessControl demonstrates basic access control mechanisms
contract SimpleAccessControl {
// Contract's owner address
address public owner;
// Modifier to restrict function access to the contract's owner
modifier onlyOwner() {
require(msg.sender == owner, "Caller is not the owner");
_;
}
// Constructor sets the deploying address as the contract's owner
constructor() {
owner = msg.sender;
}
// Function to change the owner, restricted to the current owner
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}
In the context of Solidity smart contracts, state variables and functions have visibility modifiers that can be used as access control mechanisms.
For example, a variable can be declared as public
, internal
or private
while a function can be declared as public
, internal
, private
or external
. These will determine the scope where these resources will be visible.
Also, it’s common practice to define roles, such as owner, and use require statements to gate functions by checking if msg.sender is equal to the address with the specified role.
For example, Solidity constructors often set msg.sender as owner and then have checks throughout the contract to determine if the caller’s address matches the address of owner.
A popular library to manage access controls in a contract is Openzeppelin’s Access Control.