Introduction to Solidity

Solidity File Structure

Beginner Level

Solidity File Structure and Essential Components

When writing Solidity contracts, it’s important to understand the file structure and some essential components that every contract file typically includes. This ensures your code is organized, secure, and compatible with Ethereum tools.

1. .sol Files

  • Solidity source files use the .sol extension.
  • Each .sol file can contain one or more contracts, interfaces, or libraries.
  • Naming convention: the filename usually matches the main contract name (e.g., HelloWorld.sol contains contract HelloWorld).

Example structure of a .sol file:


HelloWorld.sol
├── SPDX-License-Identifier
├── Pragma statement
├── Contract definitions
│   ├── State variables
│   ├── Functions
│   └── Constructor
├── Optional: Interfaces or Libraries

2. SPDX License Identifier

  • Indicates the license under which the code is released.
  • Helps tools, auditors, and users understand the legal terms of usage.
  • Required by most modern Solidity compilers; omitting it will show a compiler warning.

Syntax:


// SPDX-License-Identifier: MIT

Common SPDX Licenses:

  • MIT – Permissive license allowing reuse with minimal restrictions.
  • GPL-3.0 – Copyleft license requiring derivative works to also be open source.
  • Apache-2.0 – Permissive license with patent protection clauses.

Example usage:


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

contract HelloWorld {
    string public message;
}

3. Pragma Statement

  • Specifies the compiler version the contract is compatible with.
  • Ensures your contract does not break due to incompatible compiler changes.
  • Must appear at the top of every Solidity file.

Syntax:


pragma solidity ^0.8.20;

  • ^ means compatible with version 0.8.20 and above, up to but not including 0.9.0.
  • >=0.8.0 <0.9.0 specifies an exact compatible range.

Example:


pragma solidity >=0.8.0 <0.9.0;

4. Putting It Together

A basic .sol file with SPDX License and Pragma looks like this:


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

contract HelloWorld {
    string public message;

    constructor(string memory initMessage) {
        message = initMessage;
    }

    function setMessage(string memory newMessage) public {
        message = newMessage;
    }

    function getMessage() public view returns (string memory) {
        return message;
    }
}

Key Points

  1. SPDX License – Always placed at the top to avoid compiler warnings.
  2. Pragma Statement – Defines compatible Solidity compiler versions.
  3. Contract Definition – Main part containing state variables, functions, and constructor.

Continue Learning

Explore more topics in Solidity or browse other tutorials.