Solidity Contract Structure
A Solidity file follows a set order, with a licence line and a version line first and the code inside a contract. Knowing the parts makes every later file easy to read.
Licence and pragma come first
Every file starts with these two lines. The licence line names the sharing terms, and the pragma line pins the compiler version range.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;The contract block holds variables
The contract keyword opens a block with braces. A state variable declared inside the block belongs to the contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract StructureDemo {
uint256 public itemCount = 4;
}Functions live inside the contract
A function is declared inside the same braces as the variables. This one changes the variable it sits next to.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract StructureDemo {
uint256 public itemCount = 4;
function setItemCount(uint256 newCount) public {
itemCount = newCount;
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract TeamBoard {
uint256 public players = 11;
uint256 public matches = 0;
function setMatches(uint256 newMatches) public {
matches = newMatches;
}
}Key points
- Licence line: the top line that names the terms for sharing the code.
- Pragma: the line that states which compiler versions may build the file.
- Compiler: the tool that turns Solidity code into instructions a blockchain can run.
- Contract block: the braces that hold a contract's variables and functions.
- State variable: a value declared inside the contract and stored by it.
- Function: a named block of code inside the contract that runs when called.
In this example, the file opens with the licence line and the pragma line, like every Solidity file. The TeamBoard contract holds two state variables, players set to 11 and matches set to 0. Its one function, setMatches, saves a new value into matches.
Note
Every Solidity file carries a pragma line, while many other languages need no version line at all.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
Which line comes first in a Solidity file?