Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 47 ยท Language Basics

Comments, NatSpec and the Style Guide

Write clear Solidity: single-line, multi-line and NatSpec comments, the SPDX line, the official layout and naming rules, with a runnable NatSpec reader and style checker.

Code on a blockchain is read far more often than it is written. Auditors read it before launch, users read it on Etherscan, wallets read parts of it to show a signing prompt, and you will read it again in six months. Because a deployed contract cannot be edited, the cost of a misunderstanding is higher than in most software. Good comments and a consistent style are cheap insurance.

This lesson covers the three comment forms, NatSpec (the structured comment format that tools turn into documentation and wallet messages), the first two lines every file needs, and the official style conventions for layout and naming. Solidity is shown read-only, and two small JavaScript stand-ins let you extract NatSpec and check style rules yourself. You should already have seen a contract in Your First Contract.

The three comment forms

Solidity borrows its comment syntax from C and JavaScript.

SOLIDITY
// A single-line comment runs to the end of the line.
uint256 public total; // it can also follow code

/*
   A multi-line comment can span as many
   lines as you like. It cannot be nested.
*/

/// A single-line NatSpec comment (three slashes).

/**
 * A multi-line NatSpec comment (starts with two stars).
 */

The compiler ignores ordinary comments completely. They cost no gas, because comments never reach the bytecode. The last two forms are different: the compiler reads them and can produce documentation files from them.

What to put in a comment

A comment should explain why, not repeat what. Compare these:

SOLIDITY
// add one to count   <- tells the reader nothing new
count += 1;

// Each vote is counted once; the voted flag below prevents repeats.
count += 1;

Good places for comments are: the intent of a function, assumptions (for example "caller must have approved this contract first"), units (wei or token units? seconds or blocks?), security reasoning, and links to the specification a standard follows. Poor comments restate the code, become stale, or describe a plan nobody finished.

Comments carry real risks too. A misleading comment is worse than none, because readers trust it over the code. When you change behavior, change the comment in the same commit. In an audit, a mismatch between a comment and the code is itself a finding, since it means someone believed the contract does something it does not.

Why bother at all? Comments improve maintenance (the next person understands your intent), improve collaboration (reviewers can check intent against implementation) and save time (no digging through call chains to learn what an assumption was).

The first lines of a file

Every Solidity file starts with two lines:

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

The SPDX license identifier is a machine-readable comment naming the license of the source (MIT, GPL-3.0-only, UNLICENSED and so on). The compiler warns if it is missing, because published source needs a clear license. The pragma states which compiler versions the file accepts. ^0.8.24 means "0.8.24 or a later 0.8.x release, but not 0.9". Pin a narrow range for deployed code so that it is always built by the compiler you tested.

NatSpec

NatSpec (Ethereum Natural Language Specification) is a doc-comment format in the style of Javadoc. Put it directly above a contract, function, event, error or state variable, using /// or /** */. Tags begin with @.

SOLIDITY
/// @title A tiny savings vault
/// @author Your Name
/// @notice Lets an account deposit ETH and withdraw it later
/// @dev Uses the checks-effects-interactions order to avoid reentrancy
contract Vault {
    mapping(address => uint256) public balanceOf;

    /// @notice Deposit the ETH you send with this call
    /// @dev Emits nothing; the balance is simply increased
    function deposit() external payable {
        balanceOf[msg.sender] += msg.value;
    }

    /// @notice Withdraw part of your balance
    /// @param amount The amount in wei to withdraw
    /// @return remaining Your balance after the withdrawal
    function withdraw(uint256 amount) external returns (uint256 remaining) {
        balanceOf[msg.sender] -= amount;
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "transfer failed");
        return balanceOf[msg.sender];
    }
}

The main tags:

Tag Used on Meaning
@title contract, library, interface A short title
@author contract, library, interface The author's name
@notice everything A plain-language explanation for end users
@dev everything Extra detail for developers
@param name function, event Describes a parameter; the name must match
@return function Describes a return value (one tag per return value)
@inheritdoc Base function, variable Copy the documentation from a base contract or interface
@custom:name everything Your own tag, such as @custom:security-contact

Two points are worth knowing. First, the compiler checks NatSpec: an @param whose name is not an actual parameter is an error, so documentation cannot quietly drift from the signature. Second, a doc comment on a function that is overridden does not automatically carry over; use @inheritdoc to inherit it.

Run solc --userdoc --devdoc Vault.sol and the compiler outputs two JSON files. The user documentation (from @notice) can be shown by wallets when a person signs a transaction, and the developer documentation (from @dev, @param, @return) feeds documentation sites and editors that show hover help.

The official style guide

The Solidity documentation includes a style guide. It is a set of conventions, not compiler rules, and following it makes your code look like everyone else's.

Layout

  • Indentation: four spaces per level. Never mix tabs and spaces.
  • Blank lines: two blank lines between top-level declarations (contracts, libraries, interfaces); one blank line between functions inside a contract. Related one-line declarations, such as several abstract functions in an interface, may be grouped without blank lines.
  • Line length: keep lines to 120 characters or fewer. When a call is too long, put each argument on its own line with the closing bracket aligned to the start of the statement.
  • Braces: the opening brace stays on the same line as the declaration, the closing brace gets its own line and matches the indentation of the opener.
  • Whitespace in expressions: avoid extra spaces inside parentheses and brackets. Write spam(ham[1], Coin({name: "ham"})), not spam( ham[ 1 ], Coin( { name: "ham" } ) ). Put one space around binary operators.
SOLIDITY
// Good
function transfer(address to, uint256 amount) external returns (bool) {
    balances[msg.sender] -= amount;
    balances[to] += amount;
    return true;
}

// Too long, so wrap one argument per line
bytes32 digest = keccak256(
    abi.encode(
        owner,
        spender,
        value
    )
);

Order of layout

Inside a file, use this order: SPDX line, pragma, imports, then interfaces, libraries and contracts. Inside a contract, put these in order:

  1. Type declarations (using, struct, enum)
  2. State variables
  3. Events
  4. Errors
  5. Modifiers
  6. Functions

Order functions by visibility: constructor, receive, fallback, then external, public, internal, private. Within each group, put view and pure functions last.

Naming

Thing Convention Example
Contracts, libraries, structs, enums, events PascalCase TokenSale, Transfer
Functions, variables, modifiers, arguments camelCase totalSupply, onlyOwner
Constants UPPER_CASE_WITH_UNDERSCORES MAX_SUPPLY
Private and internal members optional leading underscore _balances, _mint
Function arguments that clash with a state variable trailing or leading underscore owner_
Enum members PascalCase Status.Active

Contract and library file names should match the contract name (Vault.sol holds Vault).

Try it: read NatSpec

The first stand-in is a tiny parser that takes a doc comment and builds the same kind of "user doc" and "dev doc" objects that solc writes. It shows that NatSpec is plain structured text.

JS Extract NatSpec tags

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

No output.

The last line shows why compiler-checked NatSpec is useful: renaming a parameter without updating the comment is caught immediately.

Try it: a mini style checker

The second stand-in applies a few of the rules above to source text. Real teams use solhint, forge fmt or the Prettier Solidity plugin for this, but the rules themselves are simple.

JS Check a few style rules

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

No output.

What is real: the comment forms, the NatSpec tags, the SPDX and pragma lines, and the layout and naming conventions follow Solidity and its official style guide. What is the stand-in: the parser and checker are small regular-expression sketches, not the real compiler or a full linter, so they handle only the simple shapes shown here.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which comment form does the compiler turn into documentation?

    Triple-slash and double-star comments are NatSpec. The compiler reads their @tags and can emit user and developer documentation. Plain // and /* */ comments are ignored.
  2. 2. Do comments increase the gas cost of deploying a contract?

    Comments are discarded at compile time and never reach the deployed bytecode, so you can document freely.
  3. 3. What does the @notice tag describe?

    @notice is the plain-language text for users, while @dev is for developers. The compiler outputs them into separate userdoc and devdoc files.
  4. 4. Which naming matches the official style guide?

    Contracts use PascalCase, functions and variables use camelCase, and constants use UPPER_CASE_WITH_UNDERSCORES.
  5. 5. What is the recommended order of functions inside a contract?

    Grouping by visibility, with the entry points first, lets a reader see a contract's public surface immediately.

Summary

  • Comments cost no gas. Explain why and state assumptions and units; never leave a comment that disagrees with the code.
  • Start every file with an SPDX license line and a pragma solidity version range.
  • NatSpec (/// or /** */) uses tags such as @title, @notice, @dev, @param, @return and @inheritdoc; the compiler validates parameter names and writes user and developer docs.
  • The style guide asks for 4-space indentation, lines of at most 120 characters, PascalCase for contracts, camelCase for functions and variables, and UPPER_CASE for constants.
  • Order a contract as types, state variables, events, errors, modifiers, then functions grouped by visibility. Use a formatter or linter to enforce this automatically.

Next: the types you will write in every contract, in Value Types.