Part II · Accounts, transactions, contracts

Lab: the Counter contract

By KangPublished: Chain snapshot: , block 12117419

Start by reading one on-chain state change, rather than equating smart contracts with finance from day one.

What the contract does

Counter is a teaching contract only a dozen lines long:

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

contract Counter {
    uint256 public count;
    address public owner;
    event Incremented(address indexed by, uint256 newCount);

    constructor() { owner = msg.sender; }

    function increment() external {
        count += 1;
        emit Incremented(msg.sender, count);
    }

    function reset() external {
        require(msg.sender == owner, "not owner");
        count = 0;
    }
}

Anyone may call increment (add one and emit Incremented); only the deployer, owner, may call reset (set to zero). It was compiled with solc 0.8.34.

On-chain result

Contract address (computed in advance from account A’s nonce 0, and matching exactly after deployment):

View address on Sepolia Etherscan (opens in a new tab): 0xAf6f88Cf8bf6e9211CD11B375AECBa37d61CD00f

Read-only check at the snapshot: count() = 2, owner() = account A.

Five circles show count: 0 after deploy, 1 after increment, 0 after reset, 1 after an increment with a 1 wei tip, 2 after an increment with a 2 wei tip. Notes: reads are free; reset does not erase history and only the owner may call it.
Figure 3 ·

Each Counter step is a mined transaction; reading count() needs no transaction.

Open the full-size diagram in a new tab

All five succeeded. Use the links or the Copy buttons for full hashes; Appendix A lists every transaction in full.

What the numbers teach

  • The chain keeps the books for you: count, owner and the event logs all live on-chain. Changing state means paying gas yourself.
  • Deploying costs far more than calling: deployment used 1,652,641 gas, reset only 23,626. Most of the cost is writing the contract’s code into chain state, not the few lines of arithmetic.
  • The same function can cost different gas: the increment from 0 to 1 used 127,229 gas, from 1 to 2 only 29,309. Writing a storage slot from zero to non-zero is expensive; changing an already non-zero value is much cheaper.
  • Confirmed transactions cannot be undone: reset sets the number back to zero but cannot erase the earlier increment transactions or events. The history is still there.
  • This contract cannot gain features: to add batch operations or upgradeability you must choose an upgradeable pattern at deployment time, which leads straight to UBOX (Chapter 13).

Everyday equivalent

Picture a public counter outside a shop that every partner merchant can check: each call changes the count by one. If the count tracks raffle entries or completed public tasks, an on-chain counter reduces disputes about one side changing the number. But it cannot prove that a real person ever stood at the counter.