SolidityIn

Foundational: Solidity 101: Understanding State Variables, Functions, and Modifiers

November 1, 2026 · admin · Uncategorized


Every smart contract deployed to the Ethereum Virtual Machine (EVM) is built on a few core architectural primitives. If you are transitioning into Web3 development, mastering state variables, functions, and modifiers is your non-negotiable first step.


At its core, a Solidity smart contract behaves like a class in object-oriented programming: it holds data, exposes routines to query or mutate that data, and enforces rules governing who can execute those routines. Let’s break down the three foundational building blocks that make this possible.

1. State Variables: Persistent Blockchain Storage

Unlike local variables that exist only during the execution of a function, state variables are permanently written to blockchain storage. When you declare a state variable, you are allocating dedicated storage slots on the EVM, which costs gas to write and update.

Common Primitive Types

  • bool: Stores a boolean value (true or false).
  • uint256: An unsigned integer (non-negative) ranging from $0$ to $2^{256} – 1$.
  • address: Holds a 20-byte Ethereum address. Use address payable if the address needs to receive native Ether.
  • mapping(key => value): A hash table that links unique keys to values (e.g., an address to a token balance).
  • string and bytes: Dynamically sized arrays for text or raw byte sequences.

Visibility of State Variables

Solidity enforces three levels of visibility for state variables:

  • public: Solidity automatically generates a getter function behind the scenes. Other contracts and off-chain clients can read this variable directly.
  • internal: Accessible only from within the current contract and contracts derived from it (inheritance). This is the default visibility if none is specified.
  • private: Accessible only within the contract where it is explicitly declared. Note: “Private” does not mean secret; all data on a public blockchain is visible to anyone inspecting chain data.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract StateVariablesDemo {
// Public: auto-generates a getter: contractInstance.protocolName()
string public protocolName = "DeFi Vault";
// Private: only accessible within this specific contract
uint256 private vaultSecretNumber;
// Mapping: tracks user deposits
mapping(address => uint256) public userBalances;
}

2. Functions: The Contract’s Execution Engine

Functions encapsulate the executable logic of your smart contract. They define how state variables are modified, how Ether flows in and out, and how data is queried.

Function Visibility

Every function must declare its visibility to specify where it can be invoked:

  • external: Part of the contract’s public interface; can be called from transactions or other contracts, but not internally (unless using this.functionName(), which is gas-inefficient).
  • public: Can be called internally (from within the contract) or externally via transactions.
  • internal: Only callable from the current contract or derived contracts.
  • private: Only callable within the contract in which it is defined.

State Mutability: Pure, View, and State-Changing

Solidity requires you to explicitly state whether a function reads or writes to the blockchain:

  • State-changing (No keyword): Modifies the contract’s storage. These functions require a transaction, consume gas, and must be signed by an account.
  • view: Reads from state storage but does not modify it. Free to call when executed off-chain.
  • pure: Neither reads from nor modifies state. Typically used for computation or mathematical formulas. Free when called off-chain.
  • payable: Allows the function to accept native Ether along with the call (accessible via msg.value).

// Pure: depends only on passed arguments, reads no state
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
// View: reads state (userBalances), but does not alter it
function getBalance(address user) external view returns (uint256) {
return userBalances[user];
}
// State-changing + Payable: accepts ETH and writes to storage
function deposit() external payable {
require(msg.value > 0, "Zero deposit");
userBalances[msg.sender] += msg.value;
}

3. Modifiers: The Gatekeepers of Execution

Function modifiers are reusable decorators used to alter or validate the behavior of functions. They are most commonly used to check preconditions—such as access control, contract status, or input validity—before the main function body runs.

The Merge Point: The Underscore (_;)

The core mechanism of a modifier is the merge point token: _;. This symbol tells the compiler where to insert the actual body of the modified function.

modifier onlyOwner() {
require(msg.sender == owner, "Caller is not the owner");
_; // The function body is executed here
}

If the condition in require fails, execution reverts immediately, unspent gas is refunded, and the code represented by _; is never executed.

Modifiers with Arguments

Modifiers can also accept arguments, making them dynamic validation tools:

modifier checkMinimum(uint256 amount) {
require(amount >= 1 ether, "Amount too low");
_;
}
function processLargeTransfer(uint256 amount) external checkMinimum(amount) {
// Logic runs only if amount is >= 1 ether
}

Putting It All Together: A Simple Vault Contract

Here is a complete, deployable example demonstrating state variables, functions, and modifiers working in tandem:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleVault {
// 1. STATE VARIABLES
address public owner;
bool public isPaused;
mapping(address => uint256) public balances;
// 2. MODIFIERS
modifier onlyOwner() {
require(msg.sender == owner, "Unauthorized: Only owner");
_;
}
modifier whenNotPaused() {
require(!isPaused, "Vault is paused");
_;
}
constructor() {
owner = msg.sender;
isPaused = false;
}
// 3. FUNCTIONS
// Admin function using a modifier to restrict access
function setPaused(bool _paused) external onlyOwner {
isPaused = _paused;
}
// State-modifying, payable function guarded by a modifier
function deposit() external payable whenNotPaused {
require(msg.value > 0, "Deposit must be greater than zero");
balances[msg.sender] += msg.value;
}
// State-modifying function with balance check
function withdraw(uint256 amount) external whenNotPaused {
require(balances[msg.sender] >= amount, "Insufficient funds");
balances[msg.sender] -= amount;
(bool success, ) = payable(msg.sender).call{value: amount}("");
require(success, "Transfer failed");
}
// View function to check the total vault balance
function getVaultBalance() external view returns (uint256) {
return address(this).balance;
}
}

Summary & Key Takeaways

Component Role Key Considerations
State Variables Persistent on-chain data storage High gas cost to write; default to private or internal when possible.
Functions Operations and queries Strictly define visibility (external/public) and mutability (view/pure).
Modifiers Pre-conditions and validation logic Promotes DRY code; uses _; as the execution insertion marker.

Tags: , , ,