TExcelTAD
Home › Solidity › Contract Structure

Contract Structure

A Solidity source file is a list of declarations: a license line, version pragmas, imports, and then one or more contracts, interfaces, libraries, and free-standing types and functions. Inside a contract, the building blocks always come from the same short list.

The file header

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

import "./Token.sol";                         // the whole file
import { Ownable } from "./access/Ownable.sol"; // one symbol
  • SPDX license: because contract source code is usually published, the compiler asks you to state its license. Use UNLICENSED for code you do not license to others.
  • pragma solidity: a version constraint. ^0.8.24 means "0.8.24 or newer, but below 0.9.0". You can also write ranges such as >=0.8.20 <0.9.0.
  • import: brings declarations from other files. In this playground the only importable file is hardhat/console.sol; all other code must be in the same example.

What goes inside a contract

Element Example Purpose
State variables uint256 public total; Data stored permanently in contract storage
Constructor constructor(uint256 x) { … } Runs once, at deployment
Functions function deposit() external payable { … } Executable code
Modifiers modifier onlyOwner() { …; _; } Reusable checks wrapped around functions
Events event Deposited(address who, uint256 amount); Logs for the outside world
Errors error NotOwner(address caller); Named, cheap revert reasons
Struct and enum types struct Order { … }, enum Status { … } Custom data types

Here is a small contract that uses each kind of element:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Notebook {
    // --- types ---
    enum Mood { Neutral, Happy, Busy }
    struct Note { string text; Mood mood; }

    // --- state variables ---
    address public owner;
    Note[] private notes;

    // --- events and errors ---
    event NoteAdded(uint256 index, string text);
    error NotOwner(address caller);

    // --- modifier ---
    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner(msg.sender);
        _;
    }

    // --- constructor ---
    constructor() {
        owner = msg.sender;
    }

    // --- functions ---
    function add(string calldata text, Mood mood) external onlyOwner {
        notes.push(Note(text, mood));
        emit NoteAdded(notes.length - 1, text);
    }

    function count() external view returns (uint256) {
        return notes.length;
    }
}

contract Main {
    function main() external {
        Notebook book = new Notebook();
        book.add("Learn Solidity", Notebook.Mood.Happy);
        book.add("Write tests", Notebook.Mood.Busy);
        console.log("Notes stored:", book.count());
        console.log("Owner is Main:", book.owner() == address(this));
    }
}
Notes stored: 2
Owner is Main: true
event NoteAdded(index: 0, text: Learn Solidity)
event NoteAdded(index: 1, text: Write tests)

Notice the order of the output: console.log lines appear while main() runs, and the events emitted during the call are listed after it. You will learn about events in their own lesson.

The owner is Main, not the playground's account, because Main is the one that sent the deployment (new Notebook()). Inside Notebook, msg.sender is always the immediate caller.

Style conventions

The official Solidity style guide recommends this order inside a contract: type declarations, state variables, events, errors, modifiers, constructor, receive/fallback, external functions, public, internal, private. Naming conventions:

Kind Convention Example
Contracts, structs, events, errors, enums CapWords TokenSale, Transfer
Functions, variables, modifiers mixedCase balanceOf, onlyOwner
Constants UPPER_CASE MAX_SUPPLY
Private/internal helpers often prefixed with _ _mint

Comments and NatSpec

Solidity has // line comments and /* … */ block comments. Comments starting with /// or /** … */ are NatSpec: structured documentation that tools display to users and developers.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

/// @title A tiny temperature converter
/// @notice Converts whole degrees Celsius to Fahrenheit
contract Main {
    /// @param celsius Temperature in degrees Celsius
    /// @return fahrenheit The same temperature in Fahrenheit (rounded down)
    function toFahrenheit(int256 celsius) public pure returns (int256 fahrenheit) {
        /* integer arithmetic only: Solidity has no floating point */
        return celsius * 9 / 5 + 32;
    }

    function main() external pure returns (int256, int256, int256) {
        return (toFahrenheit(0), toFahrenheit(100), toFahrenheit(-40));
    }
}
main() returned: 32, 212, -40

Note: Solidity has no floating-point numbers. Values like prices are stored as integers in the smallest unit (wei, cents, or a token's base unit).

Several contracts in one file

A file may hold many contracts. They can reference each other, inherit from each other, and deploy each other. In this course, the contract named Main is the one the playground deploys; the others are helpers that Main uses.

Test yourself

Which part of a source file tells the compiler which versions may compile it?

  1. The SPDX comment
  2. The pragma solidity line
  3. The import statements
  4. The contract name

Inside a contract deployed by Main with new, what is msg.sender in the constructor?

  1. The playground's account
  2. The address of Main
  3. address(0)
  4. The new contract's own address

How do you write documentation comments that tools can read?

  1. # comments
  2. <!-- --> comments
  3. NatSpec comments starting with /// or /**
  4. Strings at the top of the contract