Consider the following Solidity contract snippet that implements a simple role-based access control. What will be the output when checkAccess is called by address 0x123?
pragma solidity ^0.8.0; contract AccessControl { mapping(address => bool) public admins; constructor() { admins[msg.sender] = true; } function checkAccess(address user) public view returns (string memory) { if (admins[user]) { return "Access granted"; } else { return "Access denied"; } } }
Remember that only the contract deployer is set as admin in the constructor.
The constructor sets msg.sender as admin. Since 0x123 is not the deployer, admins[0x123] is false, so the function returns "Access denied".
This contract uses a mapping of addresses to booleans to control who can call certain functions. What is this pattern called?
mapping(address => bool) private whitelist; function addToWhitelist(address user) public onlyOwner { whitelist[user] = true; } modifier onlyWhitelisted() { require(whitelist[msg.sender], "Not whitelisted"); _; }
Think about the list of allowed users explicitly stored.
This pattern uses a whitelist, a list of allowed addresses, to control access. Only addresses in the whitelist can call protected functions.
Examine the following Solidity code. Why can anyone call restrictedFunction even though it is supposed to be restricted?
pragma solidity ^0.8.0;
contract FaultyAccess {
address public owner;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
function restrictedFunction() public onlyOwner {
// restricted logic
}
function changeOwner(address newOwner) public {
owner = newOwner;
}
}Check who can call changeOwner and what it does.
The changeOwner function is public and unprotected, so anyone can call it to become the owner. This breaks the access control.
Choose the correct Solidity code snippet that defines a modifier onlyAdmin which restricts function access to addresses marked as admins in a mapping.
Modifiers must include _; to continue execution.
Option D correctly uses require with a message and includes _; to continue function execution. Option D is valid but less common. Option D lacks _;. Option D lacks _; and will block all calls.
Given the following Solidity contract, how many addresses will have access after deploying and calling grantAccess three times with different addresses?
pragma solidity ^0.8.0; contract MultiAccess { mapping(address => bool) private accessList; function grantAccess(address user) public { accessList[user] = true; } function hasAccess(address user) public view returns (bool) { return accessList[user]; } }
Each call to grantAccess sets one address to true in the mapping.
Each call to grantAccess adds one address to the accessList. After three calls with different addresses, three addresses have access.