🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Writing Smart Contracts: State, Access, and Safety

Smart ContractsđŸŸĸ Free Lesson
Smart Contracts

The one-line mental model

A smart contract is a public program whose code and storage live on every node, whose every state change costs gas and is permanently recorded, and whose bugs cannot be patched unless you deliberately built in an upgrade path.

Prerequisites

  • !Comfort with a statically typed language such as JavaScript with types, Java, or Go
  • !Rough understanding of how a blockchain re-executes transactions

What You'll Learn

  • 1Explain what the constructor, state variables, and function visibility controls each determine
  • 2Estimate why an SSTORE costs orders of magnitude more than a memory operation
  • 3Apply checks-effects-interactions and a reentrancy guard to a withdrawal function
  • 4Write a Hardhat test that covers both the happy path and an expected revert

What deployment actually does

Deploying a contract means sending a creation transaction with the compiled bytecode as its payload. The network runs that bytecode once, the constructor executes, and its return value becomes the code permanently stored at a fresh address derived from your address and nonce. After that, nobody "runs" the contract the way you run a server; users send transactions to it, nodes re-execute those calls during validation, and the resulting state transition is what consensus agrees on.

This has three practical consequences. First, contract logic is immutable by default — an if you regret stays regretted. Second, every read is free only when you query your own node; anything you publish as a transaction must pay for the compute and storage it causes. Third, contracts can call each other synchronously, so a bug in one contract can drain funds held by an entirely different one that trusted it.

It also changes how you think about debugging. Once a transaction is mined, its trace is public forever: anyone can replay the exact call with the exact inputs and watch it fail. That transparency cuts both ways. You can diagnose a production revert without access logs of your own, and your users can see every admin action you ever took, including the ones you would rather have handled quietly.

Events: the interface for everything off chain

State lives on chain, but almost no product reads raw state directly. Wallets, dashboards, and indexers consume events instead, because a log entry is cheaper to write than storage and far cheaper to query in bulk. An event such as ValueChanged(uint256 indexed newValue, address indexed by) stores a topic hash plus indexed fields that an RPC node can filter with a substring query, and it stores non-indexed data in the log body where only a full scan can reach it.

The practical rule is to emit one event per meaningful state change and to design those events so a frontend can rebuild its view without ever calling back into the contract. If your user interface needs an array of historical values, you are either iterating storage on chain, which is ruinously expensive, or indexing events off chain, which is the correct answer. Once you accept that, the division of labor becomes clear: the contract is the source of truth and the arbiter of permissions; the indexer is a disposable cache; the frontend is a convenience layer that must handle the case where the cache lags the chain by a few blocks.

Reading a contract line by line

Start from a deliberately small contract and notice how much policy is packed into a few declarations:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract SimpleStorage {
    uint256 private storedValue;   // slot 0, persists forever
    address public owner;          // slot 1
    uint64 public updatedAt;       // packed into slot 2

    event ValueChanged(uint256 indexed newValue, address indexed by);

    error NotOwner();

    constructor(uint256 initialValue) {
        owner = msg.sender;
        storedValue = initialValue;
        updatedAt = uint64(block.timestamp);
    }

    function set(uint256 newValue) external {
        if (msg.sender != owner) revert NotOwner();
        storedValue = newValue;
        updatedAt = uint64(block.timestamp);
        emit ValueChanged(newValue, msg.sender);
    }

    function get() external view returns (uint256 value, uint64 at) {
        return (storedValue, updatedAt);
    }
}

Visibility is the first thing reviewers check. external functions are callable only from outside the contract and are cheaper than public ones for that role; internal and private keep functions out of the external interface, though private only hides data from other contracts, not from anyone reading the chain. view and pure promise no state writes, and the compiler enforces that promise. Events are not storage — they are logs your transaction paid for once and which off-chain indexers consume forever after.

Storage is the expensive part of the machine

The EVM has a tiny working memory and a large permanent storage area. Memory is scratch space freed at the end of the call; storage is a persistent mapping from 32-byte slots to 32-byte values, replicated to every node. That difference shows up directly in gas:

contract GasLesson {
    uint256 public count;              // slot 0 (cold SSTORE: 20,000 gas)

    function wasteful() external {
        count = count + 1;             // read slot, write slot
        count = count + 1;             // read slot, write slot again
    }

    function efficient() external {
        count += 2;                    // one read, one write
    }

    function free() external pure returns (uint256) {
        uint256 scratch = 100;         // memory only: negligible gas
        return scratch * 2;
    }

    function sumUp(uint256[] calldata values) external pure returns (uint256 total) {
        for (uint256 i = 0; i < values.length; i++) {
            total += values[i];        // calldata reads are cheap
        }
    }
}
OperationRough gas costPractical rule
Read a warm storage slot~100Cache in memory if read repeatedly
Write storage zero to non-zero~20,000Batch updates; write once
Memory expansion~3 per wordKeep arrays short inside loops
Read calldata~3Prefer calldata over memory for read-only arrays
Emit an event~1,500 plus dataHistory belongs in logs, not storage

The optimization habit that matters most: load storage into memory once, compute, then write back once. Compilers do some of this for you, but loops that touch storage on every iteration remain your job.

Gating callers before they reach your logic

Most lost funds come from functions that were written for the deployer and left open to the world. Solidity gives you three tools: the require or revert check, the modifier for reusable guards, and OpenZeppelin's audited Ownable2Step for anything resembling an admin role.

import "@openzeppelin/contracts/access/Ownable2Step.sol";

contract Treasury is Ownable2Step {
    mapping(address => uint256) public allowances;

    event AllowanceSet(address indexed who, uint256 amount);

    constructor() Ownable(msg.sender) {}

    function setAllowance(address who, uint256 amount) external onlyOwner {
        allowances[who] = amount;
        emit AllowanceSet(who, amount);
    }

    function withdraw(uint256 amount) external {
        require(amount <= allowances[msg.sender], "over allowance");
        allowances[msg.sender] -= amount;   // effect first
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "transfer failed");     // interaction last
    }
}

Two details in withdraw carry more weight than they look. State is updated before the external call, and the two-step ownership transfer forces the new owner to accept, so a mistyped address cannot silently seize control.

The reentrancy trap in one picture

If you transfer funds before zeroing the balance, a malicious receiver can call withdraw again from its fallback function and repeat the debit while the first call is still on the stack:

// Vulnerable: external call happens before state update
function withdrawVulnerable() external {
    uint256 bal = balances[msg.sender];
    (bool ok, ) = msg.sender.call{value: bal}("");
    require(ok);
    balances[msg.sender] = 0;           // too late: re-entered already
}

// Fixed: state settled first, plus a guard as belt and braces
function withdrawFixed() external nonReentrant {
    uint256 bal = balances[msg.sender];
    require(bal > 0, "nothing to withdraw");
    balances[msg.sender] = 0;
    (bool ok, ) = msg.sender.call{value: bal}("");
    require(ok, "send failed");
}

The pattern has a name — checks, effects, interactions — and it generalizes beyond reentrancy to any function that hands control to untrusted code midway through its bookkeeping.

Testing the way auditors do

Unit tests should prove both that the contract works and that it refuses what it should refuse. A minimal Hardhat suite covering both sides looks like this:

javascript
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("SimpleStorage", function () {
  async function deploy() {
    const [owner, stranger] = await ethers.getSigners();
    const Factory = await ethers.getContractFactory("SimpleStorage");
    const contract = await Factory.deploy(100);
    return { contract, owner, stranger };
  }

  it("stores the constructor value", async function () {
    const { contract } = await deploy();
    expect((await contract.get())[0]).to.equal(100);
  });

  it("lets only the owner update", async function () {
    const { contract, stranger } = await deploy();
    await contract.set(200);
    expect((await contract.get())[0]).to.equal(200);
    await expect(contract.connect(stranger).set(1)).to.be.reverted;
  });

  it("emits an event with the new value", async function () {
    const { contract } = await deploy();
    await expect(contract.set(42)).to.emit(contract, "ValueChanged");
  });
});

Add invariant tests that hold across randomized calls (total deposited never exceeds total withdrawn plus balance), and fuzz the arithmetic boundaries. Tests are the cheapest audit you will ever run, because the expensive kind bills by the hour and starts with reading the same code you already should have. A second habit separates strong teams from everyone else: run the same suite on a local fork of mainnet before deployment, so that integrations with live protocols are exercised against real state rather than against mocks that happen to agree with your assumptions. Mocks drift; forks do not.

â„šī¸Compiler versions are part of your threat model

Lock pragma solidity to an exact version in production builds. Behavior around overflow checks, ABI encoding, and optimizer defaults has changed between releases, and a contract compiled with a different version than your tests are a contract you have not actually tested.

Common Mistakes

Leaving a privileged function without a caller check

Fix: Audit every external function for an owner, role, or signature gate, and assume strangers will call it with hostile arguments

Doing external calls before updating balances

Fix: Follow checks-effects-interactions and add a reentrancy guard on any function that sends native currency or tokens

Using floating pragma like ^0.8.0 on deployments

Fix: Pin the exact compiler version used for verified deployments so audits and reproductions match bytecode

Treating a passing happy-path test as sufficient coverage

Fix: Test reverts, zero amounts, boundary values, and re-entrancy attempts; the failures that cost money are the untested branches

Best Practices

  • Pull over push: let users withdraw their own funds instead of pushing transfers in loops
  • Emit an event for every state change that off-chain systems must reconcile
  • Keep contracts small and compose them, so a flaw in one module cannot silently rewrite another
  • Run a static analyzer such as Slither in CI and fix findings before an external reviewer sees them

Interview Questions

Q1: What does the `onlyOwner` modifier actually guarantee?

That `msg.sender` equals the stored owner address at the start of the call. It says nothing about the logic inside the function, so the modifier narrows who can reach code — it does not make that code safe.

Q2: Why is checks-effects-interactions preferred over a reentrancy lock alone?

The lock is a speed bump that depends on every related function sharing it correctly. Fixing the ordering makes the state self-consistent even if control is interrupted, and the guard becomes a second line of defense rather than the only one.

Q3: When should a contract be upgradeable?

When the product requirements will genuinely change and users must not migrate to a new address. Upgradeability adds an admin key that can rewrite all logic, so it demands timelocks, multisig control, and transparent proxies — otherwise users are trusting a person, not code.

Key Takeaways

  • Deployment stores bytecode at an address and executes a constructor once; afterwards every call is re-executed by validators
  • Visibility keywords and modifiers define the attack surface long before business logic is examined
  • Storage writes dominate gas cost, so batch them and prefer calldata for read-only inputs
  • Checks-effects-interactions plus a reentrancy guard is the baseline for any function that hands control to untrusted code
  • Tests must cover reverts and hostile inputs, not just the happy path, because that is where lost funds hide
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement