Function Visibility & Modifiers in Solidity: Gatekeepers of Smart Contracts
Solidity uses visibility specifiers and modifiers to control who can interact with functions and under what conditions. These tools are essential for security and gas efficiency in blockchain development.
Quick Reference Guide
Visibility | Access | Gas Cost |
---|---|---|
public |
Any contract/external call | Higher |
external |
External calls only | Medium |
internal |
Contract & children | Low |
private |
Defining contract only | Lowest |
1. Function Visibility Explained
Public Functions (Open Door)
function mintToken() public {
// Can be called by anyone
}
External Functions (Outside Access Only)
function withdraw() external {
// Can't be called internally
}
Internal Functions (Family Access)
function _calculateFee() internal {
// Only within contract/inherited
}
Private Functions (Vault Access)
function _generateHash() private {
// Only this contract
}
2. Modifiers: Conditional Guards
Built-in Modifiers
// Read-only (no state change)
function getBalance() public view returns(uint256) {}
// No state read/write
function add(uint a, uint b) public pure returns(uint) {
return a + b;
}
// Accepts ETH
function deposit() public payable {}
Custom Modifiers
address owner;
modifier onlyOwner() {
require(msg.sender == owner, "Not owner!");
_; // Function body executes here
}
function changeOwner(address _new) public onlyOwner {
owner = _new;
}
⚠️ Common Mistakes
- Using
public
for sensitive functions - Forgetting
payable
on ETH-receiving functions - Misordering modifiers:
function x() public payable onlyOwner
Best Practices
- Use
external
for callbacks to save gas - Make helper functions
internal
orprivate
- Chain modifiers logically: access control first
Real-World Use Cases
- π‘️
onlyOwner
for admin functions - ⏳
modifier duringSale
for time limits - π°
modifier minAmount
for ETH checks
Comments
Post a Comment