Comprehensive guide for solidity security patterns covering essential concepts, practical examples, and production best practices.
Solidity security patterns are recurring solutions to common vulnerabilities and failure modes in smart contract systems built with the Solidity language. They matter when deploying contracts on Ethereum or any EVM-compatible blockchain, especially in production environments where funds, state, and trust are at stake. These patterns guide developers in writing contracts that resist reentrancy, overflow, underflow, incorrect access control, unexpected state transitions, and complex transactional workflows.
Reentrancy occurs when an external call to a contract can invoke a callback into the same contract before the original call completes. This is a leading cause of lost funds, particularly in payment and token systems.
Use the Checks-Effects-Interactions (CEI) pattern to prevent reentrancy:
contract Payment {
mapping(address => uint256) public balances;
function withdraw(uint256 amount) external {
// Checks
require(balances[msg.sender] >= amount, "Insufficient balance");
// Effects
balances[msg.sender] -= amount;
uint256 previousBalance = address(this).balance;
// Interactions
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
// Optional: log event
emit Withdrawn(msg.sender, amount);
}
}
The key is to perform all state changes *before* any external calls. This ensures that even if the external call triggers a reentrant call to withdraw, the balance is already updated and no double-withdrawal occurs.
To further harden against reentrancy, apply the withdrawal pattern with a lock:
contract SecurePayment {
mapping(address => uint256) public balances;
bool public locked;
modifier lock() {
require(!locked, "Already locked");
locked = true;
_;
locked = false;
}
function withdraw(uint256 amount) external lock {
require(balances[msg.sender] >= amount, "Insufficient balance");
balances[msg.sender] -= amount;
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
}
The lock modifier uses a single bool flag to prevent reentrancy at the function level. This is especially effective when multiple functions can be called during a transaction.
Sharp edges:
call method does *not* forward all gas; call{value: amount}(bytes memory data) forwards only 63,000 gas by default. Use call{value: amount, gas: 200000}("") to ensure sufficient gas.transfer and send are inefficient for reentrancy: transfer sends 2300 gas, send sends 2300 but returns a bool, but neither allows custom gas.address(this).balance *after* the external call, but this value may include the transferred funds, leading to over-withdrawals.State transitions in contracts often involve multiple steps, and failure in any step can leave the contract in an inconsistent state.
Use state enums with validation checks:
enum State { Created, Deposited, Approved, Finalized, Cancelled }
struct Order {
uint256 id;
address owner;
State state;
uint256 amount;
}
mapping(uint256 => Order) public orders;
function approveOrder(uint256 id) external {
Order storage order = orders[id];
require(order.state == State.Created, "Order not created");
require(order.owner == msg.sender, "Only owner can approve");
order.state = State.Approved;
emit OrderApproved(id);
}
Add a require check at the start of each function that depends on state, and use require *before* and *after* external calls.
Use onlyOwner and onlyRole modifiers for access control:
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can call");
_;
}
modifier onlyRole(bytes32 role) {
require(hasRole(role, msg.sender), "Sender does not have role");
_;
}
function setOwner(address newOwner) external onlyOwner {
owner = newOwner;
emit OwnerSet(newOwner);
}
Sharp edges:
require checks are *not* automatically reverted; they use revert with a bytes memory message. Use revert(abi.encodePacked("Invalid state: ", string(abi.encodePacked(state)))) for structured error messages.msg.sender is not always the same as tx.origin. Use msg.sender for function calls and tx.origin for transaction-level sender.address(this).balance is not equivalent to address(this).balance in storage; address(this).balance reads from storage, but this.balance reads from storage and caches the this address.Solidity’s uint256 types are default-sized, but uint256 overflows at 2^256 - 1 and underflows at 0. Use SafeMath for arithmetic, either via a library or inline.
// Using OpenZeppelin’s SafeMath
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract Token {
using SafeMath for uint256;
mapping(address => uint256) public balances;
function transfer(address to, uint256 amount) external {
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[to] = balances[to].add(amount);
}
}
Sharp edges:
SafeMath uses require for overflow checks, so a failed addition reverts with a uint256 error code.add and sub for uint types, but add is not equivalent to add in uint256.uint256 arithmetic is not automatic: a + b where a and b are uint256 returns uint256, but a + b where a is uint32 and b is uint64 returns uint64.uint is 256 bits, but uint256 is the same. uint and uint256 are interchangeable in memory but not in storage.Use mapping(bytes32 => mapping(address => bool)) for role-based access control.
mapping(bytes32 => mapping(address => bool)) public roles;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
modifier onlyRole(bytes32 role) {
require(roles[role][msg.sender], "Missing role");
_;
}
function grantRole(bytes32 role, address account) external onlyRole(ADMIN_ROLE) {
roles[role][account] = true;
}
function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
// mint logic
}
Sharp edges:
keccak256 of a string literal is not the same as the keccak256 of a bytes32 literal.keccak256("ADMIN_ROLE") returns bytes32, and keccak256("ADMIN_ROLE") returns bytes32, but keccak256("ADMIN_ROLE") is not keccak256("ADMIN_ROLE").roles[role][account] is not equivalent to roles[keccak256("ADMIN_ROLE")][account] unless role is bytes32.bytes32 for role IDs to reduce gas cost and ensure consistency.Events are essential for debugging, monitoring, and off-chain processing.
event OrderCreated(
uint256 indexed id,
address indexed owner,
uint256 amount,
uint256 timestamp
);
event OrderUpdated(
uint256 indexed id,
bytes32 indexed field,
bytes oldData,
bytes newData
);
function createOrder(uint256 amount) external {
uint256 id = nextId++;
orders[id] = Order(id, msg.sender, State.Created, amount);
emit OrderCreated(id, msg.sender, amount, block.timestamp);
}
Sharp edges:
indexed fields are stored in the event’s topic, not the data. The first three topics are indexed fields.bytes and string are stored in data, but bytes32 is stored in topics.emit with indexed fields generates a Log with topics[0] = keccak256("EventName"), topics[1] = indexedValue, etc.events are not automatically persisted; they are emitted during transaction execution and can be queried later using eth_getLogs.Solidity contracts are gas-sensitive. Use memory, storage, and calldata efficiently.
function transferMany(address[] calldata recipients, uint256[] calldata amounts) external {
require(recipients.length == amounts.length, "Length mismatch");
for (uint256 i = 0; i < recipients.length; i++) {
address to = recipients[i];
uint256 amount = amounts[i];
balances[to] += amount;
}
}
Sharp edges:
calldata is read-only and is not copied into memory. Use calldata for function parameters that are not modified.memory is a copy-on-write array. Use memory for temporary data.storage is persistent and accessed via storage pointer.memory and storage are not automatically synchronized. Use storage for state variables and memory for temporary data.for loops with memory arrays are gas-inefficient if memory is not used.Use error declarations for structured error handling.
error InsufficientBalance(address account, uint256 balance, uint256 required);
error InvalidState(string state);
error TransferFailed();
function withdraw(uint256 amount) external {
uint256 balance = balances[msg.sender];
if (balance < amount) {
revert InsufficientBalance(msg.sender, balance, amount);
}
balances[msg.sender] -= amount;
(bool success, ) = msg.sender.call{value: amount}("");
if (!success) revert TransferFailed();
emit Withdrawn(msg.sender, amount);
}
Sharp edges:
revert uses abi.encodePacked for error data.error definitions are stored in the contract bytecode and can be decoded by off-chain clients.revert with abi.encodePacked is more gas-efficient than revert(abi.encode(...)).require and assert statements.Use the Transparent Proxy pattern for upgradable contracts.
contract UpgradeableToken {
address public implementation;
function upgradeTo(address newImplementation) external {
require(msg.sender == owner, "Only owner");
implementation = newImplementation;
}
function initialize(uint256 initialSupply) external {
// initialize logic
}
}
// Proxy contract
contract TokenProxy {
address public implementation;
fallback() external payable {
address impl = implementation;
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(calldatasize(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
Sharp edges:
delegatecall uses the calling contract’s storage.implementation is stored in the proxy contract’s storage.fallback is called on any unknown function.delegatecall does not forward msg.value, but call does.delegatecall uses msg.data and msg.value from the calling contract.require for preconditions, assert for invariants.immutable for values that are set once at construction.view for pure functions, pure for functions that do not read or modify state.external for functions called from outside, public for functions called from inside and outside.internal for functions called only within the contract.private for functions called only within the contract and not from outside.These patterns form a foundation for writing robust, secure, and maintainable Solidity contracts that withstand the rigors of real-world usage on blockchain networks.
This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy