Writing First Smart Contract

Learn the basics of the Solidity programming language and how to define a simple smart contract in Solidity.

In this lesson, we'll implement our first smart contract and go through every line to understand how it works. This will allow us to cover basic Solidity features and see how it differs from other programming languages.

Defining a smart contract

Let’s start by writing one of the simplest possible smart contracts. Our first smart contract will only be able to store a single integer variable in an Ethereum network and allow us to change it and read its current value.

Here's a complete definition that takes just a few lines of Solidity code.

Press + to interact
pragma solidity ^0.8.0;
contract Storage {
uint private number;
function setNumber(uint newNumber) public {
number = newNumber;
}
function getNumber() public view returns(uint) {
return number;
}
}

This example likely contains a few unfamiliar language constructs. Let’s now break it down and learn what each line of the smart contract does.

Compiler version

The first line of the smart contract defines the version of the Solidity compiler that should be used to compile this smart contract:

Press + to interact
pragma solidity ^0.8.0;

It's needed because the Solidity language is constantly changing, and we want to specify which compiler version we want to use for our project to avoid compatibility issues.

The 0.8.0 versions follow the Semantic Versioning scheme that breaks the version into three components separated by dots:

<major version>.<minor version>.<patch version>

The ^ symbol is also from the Semantic Versioning specification, specifying the range of versions we allow to compile our smart contract. Semantic Versioning provides several options:

  • ~0.8.0: Use any patch version, e.g., 0.8.0, 0.8.1.

  • ^0.8.0: Use any minor version, e.g., 0.8.0, 0.9.0, etc. ...