Smart Contract Security Basics Every Developer Needs
A practical introduction to smart contract security covering access control, reentrancy, unsafe external calls, compiler protections and a review workflow.
In this guide
Smart contract security comes down to a small set of habits: restrict who can call what, validate every input, update state before you talk to other contracts, and test the properties that must never break. The Solidity compiler catches some arithmetic mistakes for you, but most real losses come from access control and logic errors that no compiler can see. This guide covers the basics you need before you deploy anything that holds value.
Why contract security is different from web security
If you come from backend or frontend work, three properties of deployed contracts change the way you think about risk:
- Code is public and callable by anyone. Every external function is an open API endpoint with no firewall in front of it. Attackers can read your bytecode, simulate calls for free and try as often as they like.
- Deployment is hard to undo. A plain contract cannot be patched. Upgradeable proxies exist, but they add their own class of bugs and a privileged upgrade key that must be protected.
- Bugs move assets directly. There is no chargeback and no database restore. The contract is the ledger.
The best-known early example is The DAO. In 2016 an insecure contract was drained of more than 3.6 million ETH, and the community responded with a hard fork at block 1,920,000 that moved the funds to a recovery contract; the participants who rejected the fork continued as Ethereum Classic. The bug class behind it, reentrancy, is still on every checklist today.
If you are still choosing your learning path, the blockchain developer roadmap shows where security fits among the other skills.
What the compiler does and does not protect
Use a recent compiler. At the time of writing the newest Solidity release is 0.8.39 (November 2026), and several 2026 releases fixed code generation and optimizer bugs, so staying current is itself a security measure. Pin the exact version in your build configuration and read the release notes when you upgrade.
Since Solidity 0.8.0, arithmetic on integers reverts on overflow and underflow by default. Before that, values wrapped silently and developers had to import a checked-math library. This default removes one whole family of bugs, but it has limits:
- Code inside an
unchecked { ... }block wraps again. Only use it where you can prove the bounds. - Explicit type conversions truncate. Casting a
uint256touint128drops the high bits without reverting. - Shifts and other bitwise operators are never checked.
- Inline assembly bypasses all of these checks.
Two more things the compiler will not do for you. First, the private keyword only stops other contracts from reading a variable; everything stored on chain is visible to anyone who inspects state. Second, on-chain values such as block timestamps are a poor source of randomness, because block producers have some influence over them.
Access control: who may call this function?
The current OWASP Smart Contract Top 10 (2026 edition) ranks access control vulnerabilities first. The typical mistake is boring: an initializer, mint, withdraw or upgrade function that anyone can call because a modifier was forgotten.
// Vulnerable: anyone can change the fee recipient
function setTreasury(address newTreasury) external {
treasury = newTreasury;
}
The fix is to state the rule explicitly and to use an audited implementation rather than a hand-written owner variable.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
contract Vault is Ownable2Step {
address public treasury;
event TreasuryChanged(address indexed previous, address indexed current);
constructor(address initialOwner) Ownable(initialOwner) {}
function setTreasury(address newTreasury) external onlyOwner {
require(newTreasury != address(0), "zero address");
emit TreasuryChanged(treasury, newTreasury);
treasury = newTreasury;
}
}
Practical rules:
- In OpenZeppelin Contracts 5.x,
Ownabletakes the initial owner as a constructor argument.Ownable2Stepmakes the new owner accept the role, which protects against transferring ownership to a mistyped address. - When you need more than one privileged role, use
AccessControlwith named roles andonlyRole, orAccessManagerwhen one permission system must govern several contracts. - Never authorize with
tx.origin. A malicious contract can forward a call that the real owner started. Usemsg.sender. - Treat the owner key as part of the system. A multisig behind a timelock gives users time to react to an administrative change.
Reentrancy and the checks-effects-interactions pattern
Whenever your contract calls another contract or sends ETH, control passes to code you do not own. That code can call back into your contract before your function has finished. If your state is not yet updated, the second call sees stale balances.
// Vulnerable: balance is cleared after the external call
function withdraw() external {
uint256 amount = balances[msg.sender];
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
balances[msg.sender] = 0;
}
The fix is to order every function as checks, then effects, then interactions, and to add a reentrancy guard as a second layer.
import {ReentrancyGuardTransient} from
"@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
contract Bank is ReentrancyGuardTransient {
mapping(address => uint256) public balances;
function withdraw() external nonReentrant {
uint256 amount = balances[msg.sender]; // check
require(amount > 0, "nothing to withdraw");
balances[msg.sender] = 0; // effect
(bool ok, ) = msg.sender.call{value: amount}(""); // interaction
require(ok, "transfer failed");
}
}
Notes on the guard:
ReentrancyGuardTransientrelies on transient storage, so it only works on networks that support EIP-1153. OpenZeppelin's documentation marks the older storage-basedReentrancyGuardas deprecated and scheduled for replacement by the transient variant in version 6.0.- A guard on one function does not protect a different function that reads the same state. Cross-function and read-only reentrancy are why the ordering rule matters more than the modifier. Recent OpenZeppelin versions also offer a
nonReentrantViewmodifier for view functions that must not be read mid-call. - Token callbacks count as external calls. Transfers of some token standards invoke code on the receiver.
External calls and input validation
Two further entries in the OWASP list are closely related: unchecked external calls and lack of input validation.
- Check return values. Low-level
callreturns a success flag instead of reverting. Ignoring it means your contract continues as if the transfer happened. - Prefer pull over push. Instead of looping over recipients and sending funds, record what each user is owed and let them withdraw. One reverting recipient can otherwise block everyone.
- Avoid unbounded loops. A loop over an array that grows with usage will eventually cost more gas than a block allows.
- Validate at the boundary. Reject zero addresses, zero amounts, out-of-range percentages, mismatched array lengths and expired deadlines at the top of the function.
- Be careful with
delegatecall. It runs foreign code against your storage. Only delegate to addresses you control and trust.
The reference lists worth knowing
You do not need to memorise catalogues, but you should know which ones exist and which are current.
| Resource | What it is | Status |
|---|---|---|
| OWASP Smart Contract Top 10 | Ranked list of ten risk categories, built from incident data and a practitioner survey | 2026 edition is current |
| SWC Registry | Numbered weakness catalogue (for example SWC-107 for reentrancy) | No longer actively maintained; not thoroughly updated since 2020 |
| EEA EthTrust Security Levels | Requirement-based specification with three levels, [S], [M] and [Q] | Version 3 (March 2025) is the published specification; the SWC site points readers to it |
| Solidity security considerations | Language-level pitfalls and recommendations | Updated with the compiler docs |
The 2026 OWASP list is, in order: access control, business logic, price oracle manipulation, flash loan–facilitated attacks, lack of input validation, unchecked external calls, arithmetic errors (rounding and precision), reentrancy, integer overflow and underflow, and proxy and upgradeability vulnerabilities. Note that reentrancy sits at number eight while access control and logic errors lead. The classic bugs are well understood; the expensive ones are now mostly about design.
You will still see SWC identifiers in older audit reports and tool output, so they are worth recognising. Our guide to common audit findings walks through how these categories appear in practice.
A basic security workflow
Security is a process applied throughout development, not a review at the end.
- Write down invariants first. For example: "the sum of all user balances never exceeds the contract's token balance". These become tests.
- Reuse audited components. Token standards, access control and guards from a maintained library are safer than your own versions.
- Test the unhappy paths. Unit tests for every revert condition, plus fuzz and invariant tests for the properties from step one. See our overview of smart contract testing tools.
- Run static analysis in CI. Analyzers catch missing checks, dangerous patterns and shadowed variables cheaply. Triage every warning instead of silencing it.
- Rehearse on a fork or testnet. Deployment scripts, constructor arguments and role assignments cause real incidents too.
- Get independent review. A second developer, then an external audit for anything holding significant value. An audit lowers risk; it does not certify the absence of bugs.
- Plan for failure. Decide in advance who can pause, how upgrades are approved, and how you monitor for abnormal activity.
Security knowledge is also a frequent topic in hiring; many of the items above appear in blockchain developer interview questions.
FAQ
Is Solidity 0.8 or later enough to prevent overflow bugs?
It prevents silent wrapping in ordinary arithmetic. It does not cover unchecked blocks, explicit downcasts, shifts or assembly, and it does nothing about rounding and precision mistakes, which OWASP now lists as a separate category.
Do I still need a reentrancy guard if I follow checks-effects-interactions?
The ordering rule is the primary defence. A guard is an inexpensive second layer that helps when a later code change breaks the ordering or when several functions share state.
Does an audit make a contract safe?
No. An audit is a time-boxed review by people who can miss things, and it only covers the reviewed commit. Any change after the audit, including configuration and deployment parameters, is unreviewed.
Is the SWC Registry still worth reading?
Yes as background, because its entries explain classic weaknesses clearly. For current guidance use the OWASP Smart Contract Top 10 and the EEA EthTrust Security Levels specification.
Sources
- OWASP Smart Contract Top 10 (2026)
- Solidity documentation: Security Considerations
- Solidity documentation: Checked or Unchecked Arithmetic
- Solidity release announcements
- OpenZeppelin Contracts 5.x: Access Control
- OpenZeppelin Contracts 5.x: Utilities API (ReentrancyGuard, ReentrancyGuardTransient)
- SWC Registry
- EEA EthTrust Security Levels Specification v3
- ethereum.org: History and forks of Ethereum (DAO fork)