Solidity Security Patterns

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 Protection

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:

State-Transition Safety

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:

Overflow and Underflow Protection

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:

Access Control with Roles

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:

Events for Traceability

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:

Gas Optimization and Memory Usage

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:

Error Handling and Custom Errors

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:

Upgradability with Proxy Patterns

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:

Final Checklist

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.