File structure

We'll use the 0.5.0 version of Solidity for all the examples in this book. A smart contract in Solidity always starts with the version that is used in the file to ensure that the contract is not compatible with newer versions that could break the contract because of newly added functionalities.

Let's look at the structure of a contract in Solidity using the following steps:

  1. You define the version at the beginning of the file with the pragma statement:
pragma solidity 0.5.0;
  1. Then you can start writing your contracts. All statements in Solidity must end with a semicolon (;) to be valid. After defining the version used in the file, you have to create the contracts, as shown here:
pragma solidity 0.5.0;
contract Example {}
  1. You can define multiple contracts in one single file:
pragma solidity 0.5.0;
contract Example {}
contract Another {}
contract Token {}
contract ICO {}
  1. Inside the contract, you'll have state variables, functions, modifiers, and a single constructor. I'll explain later how they are used in detail:
pragma solidity 0.5.0;
contract Example {
uint256 counter;
modifier onlyOwner {}
constructor() {}
function doSomething() {}
}
  1. The variables that are defined directly in the contract, meaning that they are outside functions, are called state variables. These are special variables that store their value even after executing the contract. Think of them as special permanent variables that you can always read and modify:
pragma solidity 0.5.0;
contract Example {
uint256 myStateVariable;
string myOtherStateVariable;
function example(){
uint256 thisIsNotAStateVariable;
}
}

As you can see, they are outside functions but inside the contract, and they are defined at the top of the file, right when the contract begins. As I said, they keep their value forever, even after making changes to your contract. So, if your myStateVariable has a value of 5, you'll be able to read the value of that variable days or months after it has been modified, as long as you don't modify it.

They store their value directly on the blockchain storage, not in memory. In-memory variables, as you'll learn later, lose their value and are reset after the contract execution.

Finally, Solidity files use the .sol extension, for instance, example.sol. You will learn how to deploy them with the Remix IDE and Truffle in Chapter 3, Mastering Smart Contracts, and Chapter 9, Decentralized Exchanged Workflow.