DEV Community


Posted on • Updated on

Solidity Programming language tutorial

Solidity is a strongly typed high-level programming language for writing ethereum based smart contracts.Solidity code runs on Ethereum Virtual Machine(EVM). EVM’s are run time environments for running contract code in the Ethereum platform.A smart contract is a collection of contract functions and it’s data(state) that is stored in ethereum blockchain network.

-Before starting I do expect you to have some basic OOP knowledge.

Solidity Advantages:
-Object-oriented language that classes and inheritance
-Hight level language, and human-readable code
-Large community support
-Lot of developer tools available
-Static type language, means every data contains type before storing it
-Everything is contracted oriented
-Runs on Ethereum Virtual machine

Solidity Disadvantages:
-Once Contract is created, adding features to the existing contract is not possible.
-It does not have a floating type

Solidity files have an ending with .sol.
Solidity must have a semicolon at the end.
Solidity is case sensitive.

Deploying Solidity:

It uses private Ethereum networks for running contracts and testing the code.

Public Testnet:

These are public blockchain Ethereum network for testing contracts, and does not use fake funds

Public Mainnet:

These are public blockchains Ethereum real production-ready which uses real money funds and has access to everyone.


Each variable you use in solidity must declare of type. Like any programming language, It is used to store the value in a variable.

Variables in solidity are used to store the data in blockchain as well as used in functions for processing.

Variable type chart

variables are declared with the type of variable and visibility or access modifier and variable name.
datatype access-modifier variablename
Datatype is an inbuilt or custom user-defined data type such as boolean, unit256.

access-modifier: Also called visibility and how and where the variable values are accessible. Possible values are

Enter fullscreen mode Exit fullscreen mode

variablename is a valid identifier in solid, It contains a combination of alphabets and numeric. The reserved keywords are not used.

variable scopes

Global Scope(State) variable
Local Variable
Global Inbuilt Variable
Solidity State variable
variable declared in contract in one of the scopes.

variable declared in the contract are called state variables

data is stored permanently in blockchain storage.

Global variables:

//declaring solidity version.must be at the top
pragma solidity ^0.6.0;
contract SolidityTest {
   uint stateData;      // State variable
   constructor() public {
      stateData = 40;   // Using State variable
Enter fullscreen mode Exit fullscreen mode

Local variables:

pragma solidity ^0.5.0;
contract VariablesContractTest {
   *State variables are declared inside a contract ie global scope
   uint age; // State variable
   constructor() public {
      age = 10;   
   function add() public view returns(uint){
      // local variables are declared and accessed inside a function
      uint localVariable1 = 12; // local variable
      uint localVariable2 = 2; // local variable
      uint sum = localVariable1 + localVariable2; // local variable
      return sum; // access the local variable
Enter fullscreen mode Exit fullscreen mode

Global Inbuilt Variable:

Solidity defines Global scope predefined variables and accessible anywhere contract running in the blockchain.


It returns the block, transaction, and account information of the running blockchain node.

Data Type:
It allocates memory size based on datatype.

Value Types
Reference Types
Solidity Value Types
Bool It is a boolean, that contains true/false -Integer types
It provides multiple various integer types

Solidity provides multiple types to store signed and unsigned integers.

singed integers types: It uses store positive and negative numbers

unsigned integers types: It uses store positive numbers


Solidity Address Type:

the address is a type in the solidity that stores blockchain address memory location.

It contains a 20-byte value.

The address contains a properties balance and transfer

solidity Fixed-size byte array types
It provides multiple byte types - bytes1, bytes2 … bytes32.

Another type, bytes is an alias for bytes1

Abstracts contracts:

Abstract contract is an abstract design of an contract and implementation contract provides the implementation to abstract function in it.

Abstract contracts are contract that have at least one function without implementation.

abstract Contract are contracts that created with abstract keyword.
Abstract functions are created with virtual keyword
Once abstract contract is created, You need to extend by using is keyword.

pragma solidity >=0.4.0 <0.7.0;

abstract contract Animal {
    function eat() public virtual returns (bytes32);
Enter fullscreen mode Exit fullscreen mode


A solidity programming language supports various comments types.

-Single line and inline comments
-Multiline or block line comments
-Documentation or natspec comments.

Single Line:
//single line
Multi Line:

* multi-line comment line1
* multi-line comment line2
Enter fullscreen mode Exit fullscreen mode

documentation solidity Natspec comments:
Every program provides documentation for API.
Solidity provides special comments syntax for writing documentation comments in the code using `Ethereum Natural Specification(Natspec) syntax

It provides rich documentation for contract functions, classes, interfaces using the Doxygen notation format.

It helps the user to write user and developer documentation.

These can be included with single or multiple line comments

Single line comments three double slashes(///)
Multiple line comments start with /* and ends with */
It contains following tags:

Image description

Once you have the smart contract file, we have to run the following with a solidity compiler

solc --userdoc --devdoc Helloworld.sol
solc is a solidity compiler generated for compiling contracts.

--userdoc : generates solidity user documentation --devdoc : generates solidity developer documentation

It generates User and developer documentation json file.


Like any programming language, Solidity provides most of the control and conditional expressions that are provided by Javascript.

It does not have support for switch and goto in if the conditional expression

It provides the following features

if-else if

pragma solidity ^0.5.0;

contract SolidityTest {
uint age; // variable
constructor() public {
age = 60;

function checkAge() public view returns(string memory) {
if( age > 60) {

return "60";
} else {
return "less than 60";

return "default";



Interface is an abstract design of an contract and similar to Abstract Contract in Solidity.
It created using interface keyword,Contains function declaration without body. Interface functions always ends with semicolon.


  • Interface contracts only contains function declaration or header, No implementation in function.
  • It does not contain a constructor
  • It is not possible to use local or state Variables in interface
  • Interfaces can not be extend by other contracts or interfaces
  • Functions defined in Abstract without implementation created with virtual keyword
  • It is not possible with creating an instance of an Interface contracts
  • Function header in interface always end with semicolon. syntax: ` pragma solidity >=0.4.0 <0.7.0;

interface Animal {
function eat() public virtual returns (bytes32);

While Loops:

While loop executes the statements multiple times based on condition is true


pragma solidity ^0.5.0;

// While loop test
contract whileTest {

uint8 i = 0;
uint8 result = 0;

function sum(
) public returns(uint data){
while(i < 3) {
  return result;
Enter fullscreen mode Exit fullscreen mode



constructor is an optional function declared in the contract using the constructor keyword. It contains code to change and initialize the state variables.
It is called automatically once the contract is created and starts executing in the blockchain.
constructor([optional-parameters]) access-modifier {}

Constructor declaration is optional
The contract contain only one constructor declaration
Overloading constructor is not supported
if the constructor is not defined, the default constructor is used.

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;

contract ConstructorTest {
string name;

constructor() public {                 
    name = "John";       

function getName() public view returns (string memory) {       
    return name;       
Enter fullscreen mode Exit fullscreen mode


Constructs are also used in inheritance hierarchy.
-pass data in contract inheritance hierarchy
-Constructor inheritance Order execution

Let’s declare base contract
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;

contract Parent {
string name;
constructor(string memory _name) {
name = _name;



Events are used to tell font-end applications about blockchain actions.

It contains the information to log into EVM logs. These logs are stored as transaction logs in the blockchain. Client interfaces apps are notified with event actions.

Events in solidity:

used to log the event information to EVM logs.
Events are cheap than storing data in terms of gas consumption.
It maintains the history of transaction logs of every change to the transaction in Blockchain
deposit and transfer actions are written as events in the blockchain.

Events can be created using the event keyword.

event transfer(address indexed from, address indexed to, uint amount);


contract EventTest {
// Create an transfer event
event transfer(address indexed _from, address indexed _to, uint amount);

Listen for events:

Once events are emitted from a contract, You can subscribe to catch events in javascript.

Following is a code to listen and access the events in solidity.
let contract_abi = abi_json _code_during_contract_compilation;
let EventTest = web3.eth.contract(contract_abi);
let EventTestContract ="0x98...");

EventTestContract.transfer(function(err, data) {
if (!err)

For Loop
loop a piece of code untill required value acheived.


for (Initialize; Conditional Expression; updateIteration;) {
// Code block


Functions are reusable code that executes by the compiler.
Solidity functions execute the code In blockchains.


function functionname() <visibility-specifier> <modifier> returns (type) {
return typevalue;

public: - public functions are visible from internal and external contracts. - Can be called inside a contract or outside contract - Default is public - It is visible to public, so security concern.

private: - private functions are visible inside the same contract - Can be called inside a contract, Not able to call from an outside contract

internal: - Similar to private functions, and visible to contract hierarchy - Can be called inside a contract and Contracts that inherit from it.


external functions are visible to public functions.
Can be called outside contract only.

Modifier in functions:
Modifiers allows you to define the functions with behavior for changing the state of contract data.


Does not change the state of contract functions
Read the state global variables
Modification of state is not possible
used for getter of a state variable calling events or functions that modify the state,

The view functions display the data.
functions do not modify the state variable,
Suggest using for read data operations

pure functions does not access data from blockchain
does not allow read or write operations
No access to state data or transaction data
return type based on the data from a function
payable :

payable functions allows accepting ether from a caller
Function fails if the sender has not provided ether
Other functions do not accept ether, only payable functions allow.


The array is a data structure to store multiple variables values under a single name.
Array is one of the reference types defined in a solidity programming language.

Arrays are of two types

Fixed array: Array created with a fixed size of elements during declaration.
string[5] stringArray;
Dynamic array: Array created with dynamic size and no fixed size size
string[] stringArray;

Initialing array syntax:
pragma solidity ^0.8.4;

contract StaticArrayTest {
string[3] numbers = ["one", "two", "three"];

function getNumbers() external {
    string[3] memory mynumbers = ["one", "two", "three"];
Enter fullscreen mode Exit fullscreen mode

-length: length of an array push: adds an element to a dynamic array. It adds an element to the last position of an array. pop: removes an element from the dynamic array. It deletes an element from the last element of an array.


Enum defines the multiple values and creates the object with one of the values. Enum is an enumerable constant in Solidity.

The user creates a custom type to select one constant from multiple predefined constants.

Enums are useful to hold the status of transactions status and the flow of small contracts.

Enum types can be declared using the enum keyword. It assigns the index to each constants in enumeration list, For example, constants=0,constant=1 … constants=N-1. Syntax:
enum enumName {constants1,constant2 ... constantsN}
Once Enum type is declared, you can create a variable of a new type
enumName [visibile] variableName;

accessing enums:
// Defining contract
contract EnumTest {
enum Number { One,Two,Three}
Number public number=Number.Three;
constructor() public {

function getNumber() public view returns (Number) {
return number;
Enter fullscreen mode Exit fullscreen mode

enum to number type:

// Solidity program example for Enum Type declaration
pragma solidity ^0.5.0;

// Defining contract
contract EnumTest {
enum Number { One,Two,Three}
Number public number=Number.Three;
constructor() public {
function getNumber() public view returns (uint) {
return uint(number);
enums to string:

// Solidity program example for Enum Type declaration
pragma solidity ^0.5.0;

// Defining contract
contract EnumTest {
enum Number { One,Two,Three}
Number public number=Number.Three;
constructor() public {

function getNumber() public view returns (uint) {
 return uint(number);
Enter fullscreen mode Exit fullscreen mode

function getNumberName() external view returns (string memory) {
Number strNumber = number;
if (strNumber == Number.One) return "One";
if (strNumber == Number.Two) return "Two";
if (strNumber == Number.Three) return "Three";
return "";



structs are used to represent the object or classes in java, interface, and classes in typescript.

Structs used to combine the

Suppose you want to store employee data in Ethereum block and employee contains id, name, and salary details. For example, In contracts, declare three variables as seen below.

uint id;
string name;
uint salary;


struct Employee {
uint id;
string name;
uint salary;


Employee employee;
employee = Employee(1,'john', 5000);
employee = Employee(1,'john');


Solidity provides a data structure mapping to store keys and values in a hashtable kind of format.

It is similar to hashtable in java and Map in javascript and typescript. It is a reference type similar to Array and struct. In SOlidity, It does not support the loop to mapping keys and values.
mapping(keyType=> valueType) public mappingVariable;


In Solidity, We have literal numbers that can be suffixed with units. There are different types of units

Ether Units
Time Units
Ether or Currency Units
Ether Units are currency denominations of an Ether unit. The number can be suffixed with Ether Units for denominations Ether units.


The smallest Unit is wei which is equal to 1 x 10 power 12. the base unit is Ether

ether chart

That's it.Hope you got the basics of solidity.Thanks for reading.A like is appreciated.
Buy me a coffee

Top comments (0)