Solidity Basics — Web3

Solidity is the language for writing smart contracts on Ethereum: it starts with SPDX and pragma, and holds a contract with state variables (permanent, in…

Here are two of the cashier's rules at Raka's Shirt Shop: "if the person asking isn't Raka, refuse" and "if there isn't enough PTS, refuse and say how much is missing". In this lesson we write those rules so carefully that a machine can follow them, as the RakaPoints contract. Once it's printed and pinned up (deployed), the rule sheet can't be changed again.

The language is Solidity, the programming language for writing smart contracts on Ethereum and other chains that use the EVM. It looks like JavaScript (curly braces, semicolons, function), but every variable has a fixed type, and the code is compiled into bytecode plus an ABI before it's deployed.

A first contract: RakaPoints

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

contract RakaPoints {
    string public constant name = "Raka Points";
    string public constant symbol = "PTS";
    uint8 public constant decimals = 18;

    address public owner;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;

    event Earned(address indexed customer, uint256 amount);
    event Redeemed(address indexed customer, uint256 amount);

    error NotEnoughPoints(uint256 balance, uint256 needed);

    constructor() {
        owner = msg.sender;
    }

    function earn(address customer, uint256 cents) external {
        require(msg.sender == owner, "Only owner");
        uint256 amount = pointsFor(cents);
        balanceOf[customer] += amount;
        totalSupply += amount;
        emit Earned(customer, amount);
    }

    function redeem(uint256 amount) external {
        uint256 balance = balanceOf[msg.sender];
        if (balance < amount) revert NotEnoughPoints(balance, amount);
        balanceOf[msg.sender] = balance - amount;
        totalSupply -= amount;
        emit Redeemed(msg.sender, amount);
    }

    function pointsFor(uint256 cents) public pure returns (uint256) {
        return (cents / 100) * 10 ** decimals;
    }
}

State variables and mappings

A state variable lives in the contract's storage and lasts between transactions, unlike local variables (amount, balance) that vanish once the function ends. Writing one is expensive: tens of thousands of gas per new slot.

mapping(address => uint256) balanceOf is a table from addresses to numbers. Every address that was never set is automatically 0, so there's no "key not found". A mapping has no length and can't be looped over. The word public makes the compiler add a reading function automatically, balanceOf(address).

Functions: visibility, view and pure

Visibility Who may call it
public from outside (a transaction or another contract) and from inside this contract
external only from outside
internal this contract and contracts derived from it
private only this contract

private doesn't mean secret. All storage can be read by anyone through a node; private only stops other contracts calling it.

Then there's the state mutability marker:

Calling a view or pure function from outside uses eth_call: free, no transaction, no gas.

Events and errors

emit Earned(customer, amount) writes an event to the transaction's log. Contracts can't read events, but frontends and indexers can. After earn(Dinda, 9500), viem reads the log as:

{ eventName: 'Earned', args: { customer: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', amount: 95000000000000000000n } }

indexed makes customer usable as a filter: "show every Earned for Dinda".

There are two ways to refuse. require(condition, "message") cancels the transaction with a text. A custom error (error NotEnoughPoints(...) then revert NotEnoughPoints(balance, amount)) costs less gas and carries data. These are viem 2.57.4's real messages for both:

The contract function "earn" reverted with the following reason:
Only owner

The contract function "redeem" reverted.

Error: NotEnoughPoints(uint256 balance, uint256 needed)
                    (95000000000000000000, 100000000000000000000)

Numbers: uint256, decimals and checked arithmetic

Solidity has no decimal numbers. uint256 is a whole number from 0 to 2^256 - 1. So that PTS can be split like ETH, we use decimals = 18: 1 PTS is stored as 10^18 of its smallest unit. Buying a Coffee Print Shirt for $95 (9,500 cents) gives pointsFor(9500) = 95000000000000000000. Division is whole too: pointsFor(99) = 0, because 99 / 100 rounds down to 0.

Before you read on, guess: Dinda has 95 PTS and calls redeem for 100 PTS. If the balance check is deleted, so the contract goes straight to balanceOf[msg.sender] -= amount, what happens? Does Dinda's balance become -5, a huge number, or is the transaction cancelled?

Since Solidity 0.8.0, every +, - and * is checked. If the result falls outside its type's range, the transaction is cancelled with Panic 0x11. So if the balance check in redeem is deleted, 95 PTS minus 100 PTS does not become -5 and does not become a huge number: the transaction reverts. The real message:

The contract function "redeem" reverted with the following reason:
Arithmetic operation resulted in underflow or overflow.

and the Hardhat node writes reverted with panic code 0x11 (Arithmetic operation overflowed outside of an unchecked block). The same happens with a uint8 (0 to 255): 255 + 1 reverts. Inside an unchecked { ... } block the check is switched off, and 255 + 1 becomes 0. Before 0.8, that was the default behaviour, and many contracts were drained because of it. We still write the NotEnoughPoints check, because its message is far clearer than a Panic.

Compiling for real with solc-js

solc on npm is the Solidity compiler in a JavaScript build. In an empty folder:

npm install [email protected]
npx solcjs --abi --bin RakaPoints.sol -o build

When it succeeds there's no output at all, and two files appear: build/RakaPoints_sol_RakaPoints.bin (the bytecode that gets deployed) and build/RakaPoints_sol_RakaPoints.abi. The ABI (Application Binary Interface) is the contract's list of functions, events and errors in JSON. In an easier-to-read form (ethers' Interface.format()):

constructor()
error NotEnoughPoints(uint256 balance, uint256 needed)
event Earned(address indexed customer, uint256 amount)
event Redeemed(address indexed customer, uint256 amount)
function balanceOf(address) view returns (uint256)
function decimals() view returns (uint8)
function earn(address customer, uint256 cents)
function name() view returns (string)
function owner() view returns (address)
function pointsFor(uint256 cents) pure returns (uint256)
function redeem(uint256 amount)
function symbol() view returns (string)
function totalSupply() view returns (uint256)

When something's wrong, solcjs stops with an error. A missing semicolon after totalSupply += amount:

ParserError: Expected ';' but got 'emit'
  --> RakaPoints.sol:27:9:
   |
27 |         emit Earned(customer, amount);
   |         ^^^^

Marking earn as view even though it writes storage:

TypeError: Function cannot be declared as view because this expression (potentially) modifies the state.
  --> RakaPoints.sol:25:9:
   |
25 |         balanceOf[customer] += amount;
   |         ^^^^^^^^^^^^^^^^^^^

⚠️ Small lines that throw PTS off

TL;DR: Solidity is the language for writing smart contracts on Ethereum: it starts with SPDX and pragma, and holds a contract with state variables (permanent, in storage), mappings (default 0, can't be looped), a constructor (once, at deployment), functions, events and errors. Visibility: public, external, internal, private (not secret). view reads state without changing it, pure neither reads nor changes it, and both are free to call from outside. require refuses with a text, a custom error refuses with data. No decimals: PTS uses 18 decimals, and division is always whole. Since 0.8, overflow and underflow revert with Panic 0x11. npx solcjs --abi --bin produces the bytecode and ABI; its errors name the file, line and column.

⚡ State variables: stored permanently

Write:

address public owner;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;

Meaning: A state variable lives in the contract's storage and lasts between transactions. A mapping is a table from addresses to numbers: an address never set is automatically 0, and a mapping can't be looped over.

⚡ view and pure

Write:

function pointsFor(uint256 cents) public pure returns (uint256) {
    return (cents / 100) * 10 ** decimals;
}

Meaning: view may read state without changing it, like the balanceOf(address) getter. pure neither reads nor changes state; the result depends only on the arguments. Both are free to call from outside.

⚡ Overflow reverts on the spot

Guess first: Dinda has 95 PTS, and the balance check in redeem is deleted. Dinda redeems 100 PTS. Does her balance become -5, a huge number, or is the transaction cancelled?

Cancelled. Since Solidity 0.8.0, every +, - and * is checked, so the transaction reverts with Panic 0x11.

Meaning: We still write the NotEnoughPoints check, because its message is far clearer than a Panic.

⚡ No decimal numbers

Meaning: 1 PTS is stored as 10^18 of its smallest unit (decimals = 18), and division always rounds down: pointsFor(99) = 0.

What you will learn