The Wayback Machine - https://web.archive.org/web/20240927152600/https://www.geeksforgeeks.org/introduction-to-solidity/
Open In App

Introduction to Solidity

Last Updated : 24 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Solidity is a brand-new programming language created by Ethereum which is the second-largest market of cryptocurrency by capitalization, released in the year 2015 and led by Christian Reitwiessner. Some key features of solidity are listed below: 

  • Solidity is a high-level programming language designed for implementing smart contracts.
  • It is a statically typed object-oriented(contract-oriented) language.
  • Solidity is highly influenced by Python, c++, and JavaScript which run on the Ethereum Virtual Machine(EVM).
  • Solidity supports complex user-defined programming, libraries, and inheritance.
  • Solidity is the primary language for blockchains running platforms.
  • Solidity can be used to create contracts like voting, blind auctions, crowdfunding, multi-signature wallets, etc.

Ethereum

Ethereum is a decentralized open-source platform based on the blockchain domain, used to run smart contracts i.e. applications that execute the program exactly as it was programmed without the possibility of any fraud, interference from a third party, censorship, or downtime. It serves as a platform for nearly 2,60,000 different cryptocurrencies. Ether is a cryptocurrency generated by Ethereum miners, used to reward for the computations performed to secure the blockchain. 

Ethereum Virtual Machine(EVM) 

Ethereum Virtual Machine abbreviated as EVM is a runtime environment for executing smart contracts in ethereum. It focuses widely on providing security and execution of untrusted code using an international network of public nodes. EVM is specialized to prevent Denial-of-service attack and confirms that the program does not have any access to each other’s state, also ensures that the communication is established without any potential interference. 

Smart Contract

Smart contracts are high-level program codes that are compiled to EVM byte code and deployed to the ethereum blockchain for further execution. It allows us to perform credible transactions without any interference of the third party, these transactions are trackable and irreversible. Languages used to write smart contracts are Solidity (a language library with similarities to C and JavaScript), Serpent (similar to Python, but deprecated), LLL (a low-level Lisp-like language), and Mutan (Go-based, but deprecated).

Example: In the below example, we have discussed a sample solidity program to demonstrate how to write a smart contract in Solidity.

Solidity




// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.4.16 < 0.9.0;
/// @title A contract for demonstrate how to write a smart contract
/// @author Jitendra Kumar
/// @notice For now,this contract just show to set the value of state variable,calculate the sum and get this sum value from the smart contract
 
contract Test
{
     
    // Declaring state variables
    uint public var1;
    uint public var2;
    uint public sum;
   
    // Defining public function 
    // that sets the value of 
    // the state variable
    function set(uint x, uint y) public
    {
        var1 = x;
        var2 = y;
        sum=var1+var2;
    }
       
    // Defining function to
    // print the sum of
    // state variables
    function get(
    ) public view returns (uint) {
        return sum;
    }
}


Output:

Smart contract

Explanation:

1. Version Pragma: 

pragma solidity >=0.4.16 <0.9.0;

Pragmas are instructions to the compiler on how to treat the code. All solidity source code should start with a “version pragma” which is a declaration of the version of the solidity compiler this code should use. This helps the code from being incompatible with the future versions of the compiler which may bring changes. The above-mentioned code states that it is compatible with compilers of version greater than and equal to 0.4.16 but less than version 0.9.0

2. The contract keyword: 

contract Test
{ 
//Functions and Data 
}

The contract keyword declares a contract under which is the code encapsulated.

3. State variables: 

uint public var1;
uint public var2;
uint public sum;

State variables are permanently stored in contract storage that they are written in Ethereum Blockchain. The line uint public var1 declares a state variable called var1 of type uint (unsigned integer of 256 bits). Think of it as adding a slot in a database. Similarly, goes with the declaration uint public var2 and uint public sum.

4. A function declaration:

function set(uint x, uint y) public
function get() public view returns (uint)
  • This is a function named set of access modifier type public which takes a variable x and variable y of datatype uint as a parameter.
  • This was an example of a simple smart contract that updates the value of var1 and var2. Anyone can call the function set and overwrite the value of var1 and var2 which is stored in the Ethereum blockchain. This is an example of a decentralized application that is censorship-proof and unaffected to the shutdown of any centralized server. As long as someone is running a single node of the Ethereum blockchain, this smart contract will be accessible.
  • The variable sum is calculated by adding the values of the variables var1 and var2.
  • Function get will retrieve and print the value of the state variable sum.

How to Execute The Code:

There are practically two ways to execute a solidity smart contract:

1. Offline Mode: Running a solidity smart contract in Offline mode requires three prerequisites and 4 major steps to be followed to get the smart contract running:

  • Prerequisites:
  • Objectives:
    • Create a truffle project and configure a development network
    • Create and deploy smart contracts
    • Interact with the smart contract from Truffle console
    • Write tests for testing the main features offered by Solidity.

2. Online Mode: Remix IDE is generally used to compile and run Solidity smart contracts in the Online Mode. You can find the complete articles with all the steps here.



Previous Article
Next Article

Similar Reads

Introduction to Bytecode and Opcode in Solidity
Solidity is a high-level programming language and when an Ethereum client like geth is installed, it comes with a lightweight operating system called Ethereum Virtual Machine (EVM) that is specially created to run smart contracts. Ethereum Virtual Machine (EVM) is a virtual machine that is a collection of individual, networked machines called nodes
3 min read
Solidity - Types
Solidity is a statically typed language, which implies that the type of each of the variables should be specified. Data types allow the compiler to check the correct usage of the variables. The declared types have some default values called Zero-State, for example for bool the default value is False. Likewise other statically typed languages Solidi
4 min read
How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity (Blockchain)?
There are various processes involved in deploying a smart contract using Ganache and Truffle Suite: 1. Install Ganache first. Ganache is a personal blockchain for Ethereum development. You must first download and install it. It is available for download from https://www.trufflesuite.com/ganache, the official website. 2. Install Truffle Suite: The n
4 min read
Solidity - Functions
A function is basically a group of code that can be reused anywhere in the program, which generally saves the excessive use of memory and decreases the runtime of the program. Creating a function reduces the need of writing the same code over and over again. With the help of functions, a program can be divided into many small pieces of code for bet
4 min read
What are Events in Solidity?
Solidity Events are the same as events in any other programming language. An event is an inheritable member of the contract, which stores the arguments passed in the transaction logs when emitted. Generally, events are used to inform the calling application about the current state of the contract, with the help of the logging facility of EVM. Event
2 min read
Solidity - Inheritance
Inheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. Solidity supports inheritance between smart contracts, where multiple contracts can be inherit
6 min read
Solidity - Polymorphism
Polymorphism is the ability to process data in more than one form. Like any other programming language, Solidity also supports polymorphism. Solidity supports two types of polymorphism, Function Polymorphism, and Contract Polymorphism. Function Polymorphism Function Polymorphism is also known as method overloading. In function polymorphism, multipl
3 min read
Solidity - View and Pure Functions
The view functions are read-only function, which ensures that state variables cannot be modified after calling them. If the statements which modify state variables, emitting events, creating other contracts, using selfdestruct method, transferring ethers via calls, Calling a function which is not 'view or pure', using low-level calls, etc are prese
2 min read
Solidity - Encapsulation
Encapsulation is fundamental and one of the most important concepts of object-oriented programming languages. It refers to the mechanism of manipulation of the scope of variables, i.e. it restricts the access of the variable outside the scope. It allows enough constraint access to a method for taking action on it. The scope of the objects can have
3 min read
Solidity - Abstract Contract
Abstract contracts are contracts that have at least one function without its implementation or in the case when you don't provide arguments for all of the base contract constructors. Also in the case when we don't intend to create a contract directly we can consider the contract to be abstract. An instance of an abstract cannot be created. Abstract
3 min read
How to Install Solidity in Windows?
To install solidity on windows ensure that you are using windows 10, as only windows 10 provides built-in Linux Subsystem. With the help of this feature, we can run the Ubuntu terminal on the Windows machine. Below are the steps to setup Solidity on windows: Step 1: Open control panel on your system and toggle to Windows Subsystem for Linux under C
1 min read
Solidity - While, Do-While, and For Loop
Loops are used when we have to perform an action over and over again. While writing a contract there may be a situation when we have to do some action repeatedly, In this situation, loops are implemented to reduce the number of lines of the statements. Solidity supports following loops too ease down the programming pressure. While Loop This is the
3 min read
Solidity - Break and Continue Statements
In any programming language, Control statements are used to change the execution of the program. Solidity allows us to handle loops and switch statements. These statements are usually used when we have to terminate the loop without reaching the bottom or we have to skip some part of the block of code and start the new iteration. Solidity provides t
2 min read
Solidity - Variables
A Variable is basically a placeholder for the data which can be manipulated at runtime. Variables allow users to retrieve and change the stored information. Rules For Naming Variables 1. A variable name should not match with reserved keywords. 2. Variable names must start with a letter or an underscore (_), and may contain letters from "a to z" or
4 min read
Solidity - Error Handling
Solidity has many functions for error handling. Errors can occur at compile time or runtime. Solidity is compiled to byte code and there a syntax error check happens at compile-time, while runtime errors are difficult to catch and occurs mainly while executing the contracts. Some of the runtime errors are out-of-gas error, data type overflow error,
6 min read
Steps to Execute Solidity Smart Contract using Remix IDE
Remix IDE is generally used to compile and run Solidity smart contracts. Below are the steps for the compilation, execution, and debugging of the smart contract. Step 1: Open Remix IDE on any of your browsers, select on New File and click on Solidity to choose the environment. Step 2: Write the Smart contract in the code section, and click the Comp
1 min read
Solidity - Arrays
Arrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the elements in the array and can be accessed using the index
6 min read
Solidity - Enums and Structs
Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. Enums restrict the variable with one of a few predefined values, these values of the enumerated list are called enums. Options are represented with integer values starting fro
3 min read
Solidity - Constructors
A constructor is a special method in any object-oriented programming language which gets called whenever an object of a class is initialized. It is totally different in case of Solidity, Solidity provides a constructor declaration inside the smart contract and it invokes only once when the contract is deployed and is used to initialize the contract
4 min read
Solidity - Decision Making Statements
Decision making in programming is used when we have to adopt one out of a given set of paths for program flow. For this purpose, conditional statements are used which allows the program to execute the piece of code when the condition fulfills. Solidity uses control statements to control the flow of execution of the program to advance and branch-bas
4 min read
Solidity - Operators
In any programming language, operators play a vital role i.e. they create a foundation for the programming. Similarly, the functionality of Solidity is also incomplete without the use of operators. Operators allow users to perform different operations on operands. Solidity supports the following types of operators based upon their functionality. Ar
7 min read
Solidity - Mappings
Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type. Mappings are mostly used to associate the unique Ethereum address with the associated val
4 min read
Solidity - Basics of Contracts
Solidity Contracts are like a class in any other object-oriented programming language. They firmly contain data as state variables and functions which can modify these variables. When a function is called on a different instance (contract), the EVM function call happens and the context is switched in such a way that the state variables are inaccess
4 min read
Solidity - Basics of Interface
Interfaces are the same as abstract contracts created by using an interface keyword, also known as a pure abstract contract. Interfaces do not have any definition or any state variables, constructors, or any function with implementation, they only contain function declarations i.e. functions in interfaces do not have any statements. Functions of In
2 min read
Creating a Smart Contract that Returns Address and Balance of Owner using Solidity
Problem: Create a smart contract named MyContract having a state variable as owner. Create a constructor to fetch the address of the owner from msg and hold it into the state variable owner. Also, create a function getBalance() to show the current balance of the owner. Solution: Every smart contract is owned by an address called as owner. A smart c
2 min read
What is Smart Contract in Solidity?
Solidity's code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum. Now let's look at the code example for making smart contract : Example #
4 min read
Solidity - Assembly
Assembly or Assembler language indicates a low-level programming language that can be converted to machine code by using assembler. Assembly language is tied to either physical or a virtual machine as their implementation is an instruction set, and these instructions tell the CPU to do that fundamental task like adding two numbers. Solidity has an
4 min read
How Does Solidity Works?
Solidity is a programming language that helps developers create special programs called smart contracts. These contracts are used on the Ethereum blockchain, Which is like a giant computer that runs Decentralized Applications (DApps). In this article, We will explain how Solidity works in a simple way, using Examples to make it easier to understand
6 min read
What is Hashing in Solidity?
A cryptographic hash function is an algorithm that takes an arbitrary amount of data as input and produces the enciphered text of fixed size. Even a slight change in the input gives a completely different output. Solidity provides the following cryptographic functions: Function Properties keccak256(bytes memory) returns (bytes32)Computes the Keccak
2 min read
Solidity - Programming ERC-20 Token
ERC token standard 20 tokens in a smart contract token that follows the Ethereum Request for Comment proposal 20 guidelines. Our program will have the following mandatory functions: function totalSupply() public view returns (uint256);function balanceOf(address tokenOwner) public view returns (uint);function allowance(address tokenOwner, address sp
4 min read