Why Best Practices Are Non-Negotiable
Smart contracts are immutable once deployed and often custody real value, so a single mistake can be permanent and expensive. Unlike a web app you can hotfix, a flawed contract may be unpatchable, and attackers are financially motivated to find the flaw. Best practices exist to shrink the attack surface systematically: follow proven patterns, reuse audited code, minimize trust in external calls, and make failure states explicit. The mindset shift is from 'make it work' to 'make it impossible to misuse,' because on-chain, correctness and security are the same requirement.
Cricket analogy: Deploying an unaudited contract is like declaring your innings with no review left and a dodgy top order—one collapse and there is no second chance to bat.
Guard Against Reentrancy
The most infamous Solidity vulnerability is reentrancy, where an external call lets an attacker re-enter your function before its state updates finish—the pattern behind the 2016 DAO hack. The primary defense is the checks-effects-interactions order: first validate inputs and permissions (checks), then update your contract's state (effects), and only then make external calls or transfers (interactions). Updating balances before sending funds means a re-entrant call sees the already-decremented state and cannot drain the contract. For extra safety, add OpenZeppelin's ReentrancyGuard nonReentrant modifier on functions that make external calls.
Cricket analogy: Checks-effects-interactions is like updating the scoreboard the instant a run is completed, so a fielder's appeal (the external call) cannot con the umpire into awarding the same run twice.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Vault is ReentrancyGuard, Ownable {
mapping(address => uint256) private balances;
error InsufficientBalance(uint256 requested, uint256 available);
constructor() Ownable(msg.sender) {}
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint256 amount) external nonReentrant {
// 1. CHECKS
uint256 bal = balances[msg.sender];
if (amount > bal) revert InsufficientBalance(amount, bal);
// 2. EFFECTS (update state BEFORE the external call)
balances[msg.sender] = bal - amount;
// 3. INTERACTIONS
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "Transfer failed");
}
}Never use tx.origin for authorization—it can be spoofed by a malicious intermediary contract that tricks a victim into calling it. Always authorize with msg.sender. Similarly, avoid block.timestamp or blockhash as a source of randomness; validators can influence them. Use a dedicated oracle like Chainlink VRF for on-chain randomness.
Access Control, Errors, and Reuse
Restrict sensitive functions with explicit access control: OpenZeppelin's Ownable for single-admin contracts or AccessControl for granular roles, applied via modifiers like onlyOwner or onlyRole. Prefer custom errors (error InsufficientBalance(...)) over long require strings—they cost less gas and encode structured data for the caller. Validate all inputs, check the return values of low-level calls, and lock your compiler with a fixed pragma (for example pragma solidity 0.8.20;) rather than a floating caret so a surprise compiler upgrade cannot change behavior. Above all, reuse audited libraries like OpenZeppelin instead of hand-rolling token, access, or math logic; unaudited custom code is where most exploits live.
Cricket analogy: Access-control modifiers are like only the captain being allowed to set the field; reusing OpenZeppelin is fielding a proven XI instead of debuting eleven untested rookies in a final.
Testing and analysis are best practices too. Write unit tests with Hardhat or Foundry (including fuzz tests in Foundry), run static analyzers like Slither, and use fixed compiler versions. Before mainnet, deploy to a testnet, verify the source on Etherscan for transparency, and—for anything holding meaningful value—get a professional audit.
- Contracts are immutable and hold value, so security equals correctness—design to make misuse impossible.
- Follow checks-effects-interactions and add ReentrancyGuard to defeat reentrancy attacks.
- Authorize with msg.sender, never tx.origin; never use block values for randomness—use Chainlink VRF.
- Enforce access control with Ownable/AccessControl modifiers on sensitive functions.
- Prefer custom errors over long require strings for lower gas and structured failure data.
- Lock the compiler with a fixed pragma and reuse audited libraries like OpenZeppelin instead of custom logic.
- Test with Hardhat/Foundry, run Slither, verify on Etherscan, and audit before mainnet.
Practice what you learned
1. What is the correct ordering the checks-effects-interactions pattern prescribes?
2. Why should you avoid tx.origin for authorization?
3. What is a benefit of custom errors over long require() strings?
4. Which is the recommended source of on-chain randomness?
5. Why pin the compiler with a fixed pragma like 0.8.20 instead of ^0.8.20?
Was this page helpful?
You May Also Like
Reentrancy and Common Vulnerabilities
How reentrancy attacks drain contracts by re-entering functions before state updates, plus the defensive patterns and other common Solidity vulnerability classes.
Access Control Patterns
Techniques for restricting who can call privileged contract functions, from simple Ownable to role-based access control, safe ownership transfer, and timelocks.
Gas Optimization in Solidity
How the EVM prices computation and storage, and the practical patterns, storage packing, caching, calldata, unchecked math, that reduce transaction costs without sacrificing safety.
Auditing Smart Contracts
What a smart contract audit is and is not: the common vulnerability classes auditors hunt, the static, symbolic, and fuzzing tools that assist them, and why manual review plus layered defenses matter more than any single report.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics