What is Solidity?

Solidity is a high-level programming language inspired by C++, Python, and JavaScript. This programming language is designed to run on an EVMEthereum Virtual Machine. Solidity is used to create smart contracts used in voting applications, wallets, auctions, etc.

What are smart contracts?

Smart contracts are digital contracts that help verify a transaction's credibility without the involvement of any third party.

Set up the Solidity environment

First, install Node.js on your machine. Once this is done, we can run the following command in our terminal to install the Solidity compiler.

npm install -g solc

Now, let's run the command above and see what happens.

Terminal 1
Terminal
Loading...

Solidity program

We have the Solidity compiler set up on our machine. Let’s look at an example of a basic Solidity program.

pragma solidity ^0.5.0;
contract HelloWorld {
bytes32 message;
constructor (bytes32 myMessage) public {
message = myMessage;
}
function getMessage() public view returns(bytes32) {
return message;
}
}

Explanation

  • Line 1: We define a pragma. A pragma is a directive that tells the compiler which version of Solidity the source code can run on. Here, we have specified that it can run on Solidity version 0.5.0, up to but not including version 0.6.0 (or anything newer that does not break the functionality). This ensures that the smart contract does not behave abnormally due to a newer compiler version.

  • Line 3: We create a contract. A contract is nothing but a collection of functions and data.

  • Line 4: We define a variable message that is of bytes32 type. This will represent a state.

  • Line 5: We define a constructor for our contract.

  • Line 8: We define a getMessage() function that will return the state (message).

This is a default contract that we can relate to as the "Hello World" program in other programming languages.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved