100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Solidity Best Practices

A practical checklist of security, gas, and maintainability practices for production Solidity: checks-effects-interactions, access control, safe external calls, custom errors, and reuse of audited libraries.

PracticeIntermediate10 min readJul 10, 2026
Analogies

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.

solidity
// 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

Was this page helpful?

Topics covered

#Programming#SolidityStudyNotes#SolidityBestPractices#Solidity#Non#Negotiable#Guard#StudyNotes#SkillVeris#ExamPrep