Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 41 ยท Smart Contracts

Reading Solidity: A First Contract

Learn to read a first Solidity contract: pragma, state variables, functions, events, msg.sender and require, with a counter and a token and Python equivalents.

Solidity is the most widely used language for writing smart contracts on Ethereum and on the many chains that copy its virtual machine. Its syntax looks like a mix of JavaScript, C++ and TypeScript, so if you can read one of those you can read Solidity within minutes. This lesson is about reading contracts, not deploying them. The Solidity code is shown as read-only listings, and for each one you get a Python version you can run, which behaves the same way for the cases we test.

The site cannot run a Solidity compiler, so the Python is a stand-in: it shows the logic, not the real gas costs or the exact bit-level behavior. Everything you learn here transfers directly to the real language. You met the ideas behind it in What Are Smart Contracts? and built a model engine in Building a Toy Smart Contract Engine.

Anatomy of a contract

Here is a complete counter contract. Read it once from top to bottom, then we go through the parts.

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

contract Counter {
    address public owner;
    uint256 public count;

    event Incremented(address indexed by, uint256 newCount);
    event Reset(address indexed by);

    constructor() {
        owner = msg.sender;
    }

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

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

License comment. The first line is a machine-readable license tag; the compiler warns if it is missing.

Pragma. pragma solidity ^0.8.24; says which compiler versions may build this file. The caret means "0.8.24 or any later 0.8.x". Version 0.8 matters: since then arithmetic checks for overflow by default and reverts instead of wrapping around (see Smart Contract Security Pitfalls).

Contract. contract Counter { ... } is like a class. Deploying it creates one instance with its own address and storage.

State variables. address public owner; and uint256 public count; live in the contract's permanent storage. uint256 is an unsigned 256-bit integer; there are no negative numbers or decimals in it. address holds a 20-byte account address. The keyword public makes the compiler generate a free getter function, so anyone can read count() and owner(). Unset variables start at zero (or the zero address).

Constructor. The constructor runs exactly once, at deployment. Here it records who deployed the contract.

Functions. function increment() external { ... } is callable from outside the contract. Visibility keywords include external (only from outside), public (inside and outside), internal (this contract and children) and private (this contract only). Functions that only read state may be marked view; those that read nothing from storage may be pure.

Events. event Incremented(...) declares a log entry shape, and emit writes one. Events are cheap, are stored in the transaction receipt rather than in contract storage, and cannot be read by contracts; front ends and indexers listen to them to learn what happened. indexed parameters can be searched efficiently.

msg.sender. Inside any function, msg.sender is the address that called it. It is how a contract knows who is asking. Since transactions are signed (see Digital Signatures with a Toy Scheme), the sender cannot be faked. Do not confuse it with tx.origin, the original external account of the whole call chain, which is dangerous to use for authorization.

require. require(condition, "message") checks a rule. If the condition is false the call reverts: all state changes in this call are undone and the message is returned to the caller.

The counter in Python

Here is the same contract in Python. msg_sender is passed explicitly as the first argument because Python has no hidden call context. require raises an exception, and a failed call changes nothing because the check happens before any state is written.

Python Counter: Solidity logic in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two increments make the count 2. Bob's reset hits the require and reverts with not the owner; Alice's succeeds. The events list reads like a transaction log of the contract, which is what a block explorer would show.

A token in Solidity

The next contract is a minimal token. It is the foundation of what you will study in Tokens, ERC-20 and NFTs.

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

contract SimpleToken {
    mapping(address => uint256) public balanceOf;
    uint256 public totalSupply;

    event Transfer(address indexed from, address indexed to, uint256 amount);

    constructor(uint256 initialSupply) {
        balanceOf[msg.sender] = initialSupply;
        totalSupply = initialSupply;
    }

    function transfer(address to, uint256 amount) external {
        require(to != address(0), "cannot send to the zero address");
        require(balanceOf[msg.sender] >= amount, "not enough balance");
        balanceOf[msg.sender] -= amount;
        balanceOf[to] += amount;
        emit Transfer(msg.sender, to, amount);
    }
}

New pieces:

  • mapping(address => uint256) is a hash table from addresses to numbers. Every possible key exists and holds 0 until written. You cannot loop over a mapping or ask for its size, which is a deliberate design choice because iteration would have an unbounded gas cost.
  • Constructor arguments such as initialSupply are given at deployment. The deployer starts with all tokens.
  • address(0) is the zero address, a common "nobody" marker. Sending tokens there usually means a mistake.
  • -= and += are checked in Solidity 0.8: if balanceOf[msg.sender] -= amount would go below zero, the call reverts automatically. The explicit require just gives a friendlier message.
  • Checks, effects, interactions. The function checks conditions first, then changes state, and only then talks to the outside. Keeping that order prevents a whole class of bugs.

Here is the Python version, which also checks that the supply stays equal to the sum of balances:

Python SimpleToken: Solidity logic in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Dave never received anything, but balance_of("dave") is 0, just like an untouched mapping entry. The two bad transfers revert with the messages from the require lines, and only the two valid transfers produced events.

A mapping from Solidity to Python

Solidity Python stand-in
contract class
state variable instance attribute
constructor __init__
msg.sender an explicit msg_sender argument
mapping(address => uint256) dict read with .get(key, 0)
require(cond, "msg") if not cond: raise Revert("msg")
emit Event(...) append to an events list
view function method that only reads
Revert undoing state not modelled here; our engine's snapshots do it

The last row is worth a thought. In real Solidity the compiler and the virtual machine undo state changes automatically on revert. In the simple Python classes above that only works because each require runs before any state is modified. The engine from the previous lesson restores a snapshot, which is how a real VM behaves.

Things to watch for when reading contracts

  • Who can call what? Look for require(msg.sender == ...) or modifiers (reusable checks written as modifier onlyOwner).
  • What can change the state? Anything not marked view or pure.
  • Where does value leave? Search for transfer, send and call{value: ...}.
  • Which numbers can be user-controlled? Every function argument is hostile input.
  • Is there an admin key? A contract the owner can freely change is only as trustworthy as the owner.

You do not need to write Solidity to understand blockchains, but reading it is a useful skill: contract code is public, and auditing it is the main way users can verify what a service really does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does msg.sender contain?

    msg.sender is the immediate caller, an account or another contract, and contracts use it for permission checks.
  2. 2. What does require(condition, "message") do when the condition is false?

    A failed require reverts the transaction's effects on the state. The message helps callers and tools understand the reason.
  3. 3. What is true about a Solidity mapping such as mapping(address => uint256)?

    A mapping behaves like a hash table where unset keys return the default value. Iterating over it is not supported.
  4. 4. Why does the pragma ^0.8.24 matter for arithmetic?

    Since Solidity 0.8 arithmetic is checked, a big class of overflow bugs is prevented unless code explicitly opts out.
  5. 5. Where do emitted events live?

    Events are cheap logs attached to the transaction. Front ends and indexers read them; contracts cannot.

Summary

  • A Solidity file starts with a license tag and a pragma; a contract is like a class with permanent state.
  • State variables live in storage; public creates getters, and unset values start at zero.
  • msg.sender identifies the caller, require guards rules and reverts on failure, and emit writes events.
  • mapping is a hash table where every key reads as zero until set; it cannot be iterated.
  • Since Solidity 0.8, arithmetic is checked and reverts on overflow or underflow.
  • Reading contracts means asking who can call what, what changes state, and where value can leave.

Next: Tokens, ERC-20 and NFTs, where this small token grows into a standard.