Solidity Fundamentals
Overview
Solidity is the primary language for Ethereum smart contract development. Understanding its fundamentals is essential for building secure and efficient decentralized applications.
âšī¸
Solidity is statically typed and supports inheritance, libraries, and complex user-defined types. It compiles to EVM bytecode.
Language Architecture
Data Types
Value Types
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract DataTypeDemo {
// Boolean
bool public isActive = true;
// Integers
uint256 public uintMax = type(uint256).max;
int256 public intMin = type(int256).min;
uint8 public smallUint = 255;
// Address
address public owner = msg.sender;
address payable public payableAddr;
// Bytes
bytes1 public singleByte = 0xFF;
bytes32 public fixedBytes;
// Enums
enum Status { Pending, Active, Completed, Cancelled }
Status public currentStatus;
// Function type
function modifier() internal pure returns (uint256) {
return 1;
}
}
Type Comparison Table
| Type | Size | Range | Gas Cost | Use Case |
|---|---|---|---|---|
| uint8 | 1 byte | 0 to 255 | Low | Small counters |
| uint256 | 32 bytes | 0 to 2^256-1 | Medium | Default choice |
| int256 | 32 bytes | -2^255 to 2^255-1 | Medium | Signed values |
| address | 20 bytes | N/A | Medium | Account addresses |
| bytes32 | 32 bytes | Raw data | Medium | Hashes, fixed data |
| bool | 1 byte | true/false | Low | Flags |
Reference Types
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract ReferenceTypes {
// Dynamic Arrays
uint256[] public dynamicArray;
uint256[] public fixedArray;
// Mappings
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowances;
// Structs
struct User {
uint256 id;
string name;
uint256 balance;
bool active;
}
User[] public users;
mapping(uint256 => User) public userById;
// Data Location
function processDataLocation() public pure {
// Memory - temporary, freed after function
uint256[] memory tempArray = new uint256[](10);
// Storage - persistent on blockchain
// dynamicArray is already in storage
// Calldata - read-only, for external function params
// Used in external functions for gas savings
}
// Struct in memory vs storage
function getMemoryUser() public pure returns (User memory) {
return User(1, "Alice", 100, true);
}
function getStorageUser() public view returns (User storage) {
return users[0];
}
}
Memory vs Storage Costs
| Location | Gas Cost | Persistence | Use Case |
|---|---|---|---|
| Storage | ~20,000 (write) | Permanent | Contract state |
| Memory | ~3 (per word) | Temporary | Function execution |
| Calldata | ~0 (read-only) | N/A | External function params |
Control Structures
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract ControlStructures {
// If/Else
function checkAge(uint256 age) public pure returns (string memory) {
if (age >= 18) {
return "Adult";
} else if (age >= 13) {
return "Teenager";
} else {
return "Child";
}
}
// For loops
function sumArray(uint256[] memory data) public pure returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < data.length; i++) {
total += data[i];
}
return total;
}
// While loops
function findFactorial(uint256 n) public pure returns (uint256) {
uint256 result = 1;
uint256 i = n;
while (i > 1) {
result *= i;
i--;
}
return result;
}
// Do-While
function countdown(uint256 start) public pure returns (uint256) {
uint256 count = start;
do {
count--;
} while (count > 0);
return count;
}
// Try-Catch
function safeTransfer(address token, uint256 amount) public returns (bool) {
(bool success, bytes memory data) = token.call(
abi.encodeWithSignature("transfer(address,uint256)", msg.sender, amount)
);
if (success) {
return true;
} else {
// Handle error
return false;
}
}
}
Loop Gas Optimization
Loops are gas-intensive. Optimize with these patterns:
| Pattern | Gas Impact | Example |
|---|---|---|
| Cache length | Saves ~100 gas/iteration | uint256 len = arr.length; |
| Unchecked increment | Saves ~30 gas/iteration | unchecked { i++; } |
| Storage in loop | Avoid entirely | Use memory arrays |
| Nested loops | Quadratic complexity | Refactor or paginate |
Functions
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract FunctionDemo {
address public owner;
uint256 public constant MAX_SUPPLY = 1000000;
uint256 public totalSupply;
mapping(address => uint256) public balances;
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
modifier validAmount(uint256 amount) {
require(amount > 0, "Amount must be positive");
_;
}
constructor() {
owner = msg.sender;
}
// View functions (read-only)
function getBalance(address account) public view returns (uint256) {
return balances[account];
}
// Pure functions (no state access)
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
// State-modifying functions
function mint(uint256 amount) public onlyOwner validAmount(amount) {
require(totalSupply + amount <= MAX_SUPPLY, "Exceeds max supply");
totalSupply += amount;
balances[owner] += amount;
emit Transfer(address(0), owner, amount);
}
// External functions (only called from outside)
function transfer(address to, uint256 amount) external validAmount(amount) {
require(balances[msg.sender] >= amount, "Insufficient balance");
balances[msg.sender] -= amount;
balances[to] += amount;
emit Transfer(msg.sender, to, amount);
}
// Internal functions (only called from within contract or derived)
function _updateBalance(address from, address to, uint256 amount) internal {
balances[from] -= amount;
balances[to] += amount;
}
// Private functions (only within this contract)
function _validateAddress(address addr) private pure {
require(addr != address(0), "Zero address");
}
// Function with multiple return values
function getInfo() public view returns (address, uint256, uint256) {
return (owner, totalSupply, MAX_SUPPLY);
}
// Named return values
function getNamedInfo() public view returns (
address _owner,
uint256 _supply,
uint256 _max
) {
_owner = owner;
_supply = totalSupply;
_max = MAX_SUPPLY;
return (_owner, _supply, _max);
}
}
Function Visibility Comparison
| Modifier | Internal | External | Public | Private |
|---|---|---|---|---|
| Within contract | â | â | â | â |
| From derived contracts | â | â | â | â |
| External calls | â | â | â | â |
| Gas cost | Low | Medium | Medium | Low |
Modifiers
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract ModifierDemo {
address public owner;
uint256 public lastAction;
bool public paused;
// Basic modifier
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
// Modifier with parameter
modifier minimumAge(uint256 _age) {
require(_age >= 18, "Under age");
_;
}
// Modifier with state change
modifier updateLastAction() {
lastAction = block.timestamp;
_;
}
// Modifier with revert message
modifier validAddress(address _addr) {
require(_addr != address(0), "Invalid address");
_;
}
// Chained modifiers
function sensitiveAction() public
onlyOwner
updateLastAction
whenNotPaused
{
// Action logic
}
// Reusable modifier pattern
modifier whenNotPaused() {
require(!paused, "Contract is paused");
_;
}
// Gas-efficient modifier
modifier costsGas(uint256 _gas) {
require(gasleft() >= _gas, "Insufficient gas");
_;
}
// Modifier with early return (gas optimization)
modifier earlyReturnModifier() {
if (msg.sender != owner) {
return; // Early return saves gas
}
_;
}
}
Events
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract EventDemo {
// Event declaration
event TokenMinted(
address indexed minter,
address indexed recipient,
uint256 amount,
uint256 timestamp
);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
// Indexed parameters (max 3 per event for non-anonymous)
// Indexed parameters are stored in log topics for efficient filtering
address public owner;
uint256 public totalMinted;
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
function mint(address to, uint256 amount) public {
require(msg.sender == owner, "Not authorized");
totalMinted += amount;
// Emit event with all parameters
emit TokenMinted(msg.sender, to, amount, block.timestamp);
emit Transfer(address(0), to, amount);
}
function transferOwnership(address newOwner) public {
require(msg.sender == owner, "Not owner");
require(newOwner != address(0), "Zero address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
Event Gas Costs
| Data Type | Storage Location | Gas Cost |
|---|---|---|
| Indexed (topic) | Log topics | 375 (base) |
| Non-indexed (data) | Log data | 8 (per byte) |
| String/Bytes | Log data | Dynamic |
| Static type | Log data | 32 bytes |
Event Design Patterns
// Pattern 1: Comprehensive logging
event OrderCreated(
uint256 indexed orderId,
address indexed maker,
address indexed taker,
uint256 amount,
uint256 price,
uint256 timestamp
);
// Pattern 2: State change tracking
event StateChanged(
uint256 indexed entityId,
uint8 oldState,
uint8 newState,
address changedBy,
uint256 timestamp
);
// Pattern 3: Audit trail
event Action(
bytes32 indexed actionId,
address indexed actor,
bytes data,
uint256 timestamp
);
Error Handling
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract ErrorHandling {
// Custom errors (gas efficient, introduced in 0.8.4)
error InsufficientBalance(uint256 available, uint256 required);
error Unauthorized(address caller);
error InvalidAmount(uint256 amount, uint256 max);
// Custom error with data
error TransferFailed(bytes reason);
uint256 public constant MAX_AMOUNT = 1000;
// Require with error message
function transferWithMessage(uint256 amount) public {
require(amount > 0, "Amount must be positive");
require(amount <= MAX_AMOUNT, "Amount exceeds maximum");
// Transfer logic
}
// Require with custom error
function transferWithError(uint256 amount) public {
if (amount == 0) revert InsufficientBalance(0, 1);
if (amount > MAX_AMOUNT) revert InvalidAmount(amount, MAX_AMOUNT);
// Transfer logic
}
// Revert with reason
function transferWithRevert(uint256 amount) public {
if (amount == 0) {
revert("Amount must be positive");
}
// Transfer logic
}
// Assert (should never fail if code is correct)
function criticalOperation() public {
// Assert uses all remaining gas on failure
assert(msg.sender == address(this));
}
// Try-catch for external calls
function safeExternalCall(address target, bytes memory data) public returns (bool, bytes memory) {
(bool success, bytes memory returnData) = target.call(data);
if (success) {
return (true, returnData);
} else {
// Catch specific error types
if (returnData.length > 0) {
// Decode error
bytes4 selector = bytes4(returnData[:4]);
// Handle specific errors
}
return (false, "");
}
}
}
Error Handling Comparison
| Method | Gas Cost | Use Case |
|---|---|---|
| require | ~22 (with message) | Input validation |
| require (no message) | ~8 | Simple checks |
| revert | ~22 | Complex conditions |
| custom error | ~8 | Gas-efficient, descriptive |
| assert | ~2 | Invariant checks |
Gas Optimization
Storage Optimization
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract GasOptimization {
// BAD: Wasteful storage layout
// Each variable uses a separate 32-byte slot
uint256 public a; // Slot 0
bool public b; // Slot 1
uint256 public c; // Slot 2
bool public d; // Slot 3
// GOOD: Packed storage
// Uses only 2 slots instead of 4
uint128 public e; // Slot 0: e (128 bits)
uint128 public f; // Slot 0: f (128 bits)
uint64 public g; // Slot 1: g (64 bits)
uint64 public h; // Slot 1: h (64 bits)
uint32 public i; // Slot 1: i (32 bits)
uint32 public j; // Slot 1: j (32 bits)
// Mapping optimization
mapping(address => uint256) public balances;
// Cache storage reads
function transfer(address to, uint256 amount) public {
uint256 senderBalance = balances[msg.sender]; // Cache
require(senderBalance >= amount, "Insufficient");
unchecked {
balances[msg.sender] = senderBalance - amount;
}
balances[to] += amount;
}
// Use events instead of storage for logs
event Transfer(address indexed from, address indexed to, uint256 amount);
function logTransfer(address to, uint256 amount) public {
// Events are 375 gas for first topic, 375 for each additional
// Much cheaper than storage (~20,000 gas)
emit Transfer(msg.sender, to, amount);
}
// Use calldata instead of memory for read-only parameters
function processArray(uint256[] calldata data) external pure returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < data.length;) {
total += data[i];
unchecked { ++i; }
}
return total;
}
}
Real-World Example: ERC-20 Token
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20 is IERC20 {
string public name;
string public symbol;
uint8 public decimals;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
constructor(string memory _name, string memory _symbol, uint8 _decimals) {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: from zero");
require(recipient != address(0), "ERC20: to zero");
require(_balances[sender] >= amount, "ERC20: insufficient balance");
unchecked {
_balances[sender] -= amount;
_balances[recipient] += amount;
}
emit Transfer(sender, recipient, amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from zero");
require(spender != address(0), "ERC20: approve to zero");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
Trade-offs
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Visibility | External (cheaper) | Public (flexible) | Use external for functions called from outside |
| Data location | Memory (fast) | Storage (persistent) | Use memory for temporary data |
| Error handling | Custom errors (cheap) | Require strings (clear) | Use custom errors for gas optimization |
| Storage packing | Manual packing | Natural ordering | Pack frequently accessed variables |
Interview Questions
-
Explain the difference between
memoryandstoragein Solidity. When would you use each?Storageis persistent on the blockchain and costs gas to modify.Memoryis temporary and used during function execution. Use storage for state that persists between calls, and memory for intermediate calculations. -
What are indexed parameters in events and why are they limited to three?
Indexed parameters are stored in log topics, which are 32 bytes each. The limit exists because EVM logs have a maximum of 4 topics (including the event signature hash). Indexed parameters enable efficient filtering in event queries.
-
How does Solidity 0.8.x handle integer overflow differently than previous versions?
Solidity 0.8.x includes built-in overflow/underflow checks that revert transactions on overflow. Previous versions required SafeMath library usage. This eliminates an entire class of vulnerabilities at the cost of slightly higher gas.
Quiz Questions
-
What is the default visibility for functions in Solidity?
- A) Public
- B) External
- C) Internal
- D) Private
Answer: A - Functions default to public visibility, meaning they can be called both internally and externally.
-
Which of the following is true about
viewfunctions?- A) They can modify state
- B) They can read state
- C) They cannot read or write state
- D) They must be external
Answer: B - View functions can read state but cannot modify it. They don't cost gas when called externally.
-
What is the maximum number of indexed parameters in a non-anonymous event?
- A) 1
- B) 2
- C) 3
- D) 4
Answer: C - Non-anonymous events can have up to 3 indexed parameters (stored in log topics).