gotchajavascriptMajor
Solidity basics: common pitfalls with integer overflow and visibility
Viewed 0 times
Solidity 0.8.x
solidity visibilityoverflowSafeMathuncheckedpublicexternal
Error Messages
Problem
Solidity functions without explicit visibility default to internal, not public. Additionally, integer arithmetic behaved differently before Solidity 0.8.0.
Solution
Always explicitly declare function visibility (public, external, internal, private). Use Solidity 0.8.0+ for built-in overflow protection, or use SafeMath for older contracts.
// Always explicit:
function transfer(address to, uint256 amount) external returns (bool) { ... }Why
Silent overflow was a major vulnerability class before 0.8.0. Undeclared visibility leads to unexpected access control bugs.
Gotchas
- external is slightly more gas efficient than public for functions called from outside the contract
- In Solidity 0.8+, unchecked { } blocks can still overflow deliberately — use only for gas optimization when overflow is provably impossible
- State variables default to internal visibility (not public) — always declare explicitly
Code Snippets
Solidity visibility and safe arithmetic example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SafeCounter {
uint256 public count; // explicit public
function increment() external {
count += 1; // safe in 0.8+, reverts on overflow
}
function incrementUnchecked() external {
unchecked { count += 1; } // gas optimized, use only when safe
}
function _internalHelper() internal view returns (uint256) {
return count * 2;
}
}Context
Writing Solidity smart contracts for the first time or reviewing legacy code
Revisions (0)
No revisions yet.