Solidity File Structure

Structure of a Solidity file

SPDX License Identifier

All solidity contracts should have License declaration in the first line.

// SPDX-License-Identifier: MIT

List of licenses from SPDX repository: https://spdx.org/licenses/

Pragmas

pragma is the keyword used to declare the compiler version of Solidity. pragma only applies to the current local file so you must add pragma to all files in the project directory.

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

You can use the ^ sign or the comparison operators <, <=, >, >= in conjunction with the compiler declaration.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20; // use compiler version 0.8.20 and above
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0; // use compiler version bigger or equal to 0.4.22 and less than 0.9.0

Import file from other sources

Import the whole file

import "FileName"

Import all and assign alias

import * as symbolName from "FileName";

Name import

Name import means you will specify the name of the import object from another file. The reason you should use this option is that it makes your code clearer.

import {ContractOne as alias, ContractTwo} from "FileName";

Comment

To comment, you can use // and /* */

// comment for 1 line.

/*
Comment for
multiple lines
*/

There is also NatSpec comment with /// or /** **/

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.9.0;

/// @author The Project Team
/// @title A simple storage example
contract SimpleStorage {
    uint storedData;

    /// Store `x`.
    /// @param x the new value to store
    /// @dev stores the number in the state variable `storedData`
    function set(uint x) public {
        storedData = x;
    }

    /// Return the stored value.
    /// @dev retrieves the value of the state variable `storedData`
    /// @return the stored value
    function get() public view returns (uint) {
        return storedData;
    }
}

Last updated