Blockchain and Ethereum Certification Tr... (38 Blogs)
AWS Global Infrastructure

Solidity Tutorial – Solidity Programming For Beginners

Last updated on Nov 17,2022 20K Views

Shashank
Shashank is a Research Analyst at Edureka. He is an expert in... Shashank is a Research Analyst at Edureka. He is an expert in Blockchain technology with profound knowledge in Ethereum, smart contracts, solidity, distributed networks...
8 / 8 Blog from Ethereum

Solidity Tutorial: 

This blog on Solidity tutorial showcases a lot of Solidity features. This tutorial assumes some knowledge of the Ethereum Virtual Machine and programming in general.

Ethereum, the world Computer provides an enormously powerful shared global infrastructure to build a Decentralized application using a programming Language called Solidity.

This blog on Solidity tutorial covers the following topics:

  1. What is Solidity?
  2. Contracts in Ethereum Solidity
  3. Layout of Solidity File
  4. Value Types in Solidity
  5. Operators
  6. Data Structures in Solidity
  7. Control Structures
  8. Functions
  9. Inheritance

Let’s start our Solidity Tutorial with an introduction to Solidity.

What is Solidity?Ethereum Solidity

Ethereum Solidity is a contract-oriented, high-level language with syntax like that of JavaScript. 

A solidity is a tool used to generate a machine-level code to execute on EVM. The solidity compiler takes the high-level code and breaks it down into simpler instructions.

                   Solidity code is encapsulated in Contracts

Contracts in Ethereum Solidity

A contract is the fundamental building block of Ethereum’s decentralized Applications. All variables and functions are part of a contract and this is the starting point of all the projects.

An empty contract named MyFirst would look like this:

version pragma ^0.4.19;
contract MyFirst{
}


llets-code-it-solidity tutorial-edureka

Stick to your screen because next in our Solidity tutorial we’re gonna start coding…

Layout of Solidity File

Source files can contain an arbitrary number of contract definitions, include directives and pragma directives.

Version Pragma

Version Pragma is the declaration of the version of the Solidity compiler that the particular code should use.

version pragma ^0.4.00;

Note:  The source file shown above will not compile with a compiler earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0.

Importing other Source Files

Ethereum Solidity supports import statements that are very similar to those available in JavaScript, although Solidity does not know the concept of a “default export”.

At a global level you can use import statements of the following form:

import "filename";

The above statement imports all global symbols from “filename” into the current global scope.

import * as symbolName from "filename";

…creates a new global symbol symbolName whose members are all the global symbols from “filename”

Comments

Just like any other language, single line and multi-line comments are possible in Solidity.

// This is a single-line comment.
/*
This is a
multi-line comment
*/

Now, before we move further in our Solidity tutorial, you should know that Ethereum has three areas where it can store items.

  1. Storage: where all the contract state variables reside. Every contract has its own storage and it is persistent between function calls
  2. Memory:  hold temporary values and gets erased between (external) function calls and is cheaper to use
  3. Stack: hold small local variables and is almost free to  use, but can only hold a limited amount of values

For almost all the types, you cannot specify where they should be stored, because they are copied everytime they are used.

Alright, now that you are aware of the storage locations in Ethereum Solidity, let me tell you about the general value types.

Value Types in Solidity

The following types are also called value types because variables of these types will always be passed by value.

Value types-Solidity tutorial-edureka

Boolean

Keyword: Bool

The possible values are constants i.e., true or false

Integers

Keyword: int/uint (uint8 to uint256 in steps of 8 (unsigned of 8 up to 256 bits) and int8 to int256)

Signed and unsigned integers of various sizes.

Example:

contract MySample{
uint UnsignedInt =50;
}

In the above statement, we have created a uint called InsignedInt & set it to 50.

Address: 

Keyword: address

Holds a 20-byte value (size of an Ethereum address). Address types also have members and serve as a base for all contracts.

Members of Addresses: Balance & Transfer

It is possible to query the balance of an address using the property balance and to send Ether to an address using the transfer function.

address x = 0x123;
address myAddress = this;
if&nbsp; (x.balance < 10 && myAddress.balance > = 10)
x.transfer(10);

Strings: 

Keyword: String literals are written with either double or single-quotes “foo” or ‘bar’.

Used for arbitrary-length UTF-data.

string language = "Solidity";

These value types can interact with each other in expressions containing operators. Next, in our Solidity tutorial, let me tell you about the various operators.

Operators

Operators in solidity are same as in JavaScript. Solidity has four types of operators:

Operators-Solidity Tutorial-edurekaArithmetic Operators

Solidity has pretty straightforward Math operations. The following are similar to most of the programming languages:

  • Addition: x + y
  • Subtraction: x - y
  • Multiplication: x * y
  • Division: x / y
  • Modulus / remainder: x % y

Solidity also give you an option to use an exponential operator, here’s how:

uint x = 10 **  3; // equal to 10^3 = 1000

Incremental Operators

Incremental operators in solidity: a++, a–, ++a, –a, a+=1, a=a+1

Rules applicable to other programming languages are similar in solidity also.

Bitwise Operators:

Following are the operators: (Bitwise OR) ‘|’, (Bitwise XOR), (Bitwise negation) ‘~’ , (Bitwise right shift) ‘>>’, (Bitwise left shift) ‘<<‘

Logical Operators:

Logical operators in Solidity:  ! (logical negation),  && (logical  and),  || (logical or),  ==(equality), != (not equal)

Example:

contract operators {
// Arithmetic Operators
// +,-,*,/, %, **
// Incremental Operators
// a++, a--, a+=1, a=a+1,++a,--a;
a=10;
a= a++; //here, output will be 10, because the value is first returned and then then increment is done
a=++a;
//Logical Operators
!, &&, ||, ==, !=
isOwner = true && false;
var orValue= 0x02 | 0x01; // output would be 0x03
//Bitwise Operators~,>>, <<;
function Operators() {
// Initialize state variables here}}


Now Sometimes there is a need for a more complex data type. For this Solidity provides structs.

Data Structures in Solidity

Solidity provides three types of data structures:data structures in solidity-Solidity Programming-edureka

Structs

Solidity provides a way to define new types in the form of structs. Structs are custom defined types that can group several variables.

pragma solidity ^0.4.0;
contract Ballot {
struct Voter { // Struct
uint weight1, weight2, weight3;
bool voted;
address delegate1, delegate2, delegate3, delegate4;
string name;
uint vote1, vote2, vote3, vote4, vote5;
uint height1, height2, height3   } }

Note: Structs can only have 16 members, exceeding which the following error might occur: Stack too Deep.

Structs allow you to create more complicated data types that have multiple properties.

Now, what if you need a collection of something, say addresses. Well, just like most of the languages, Solidity also has Arrays.

Arrays

Arrays in Solidity can have a compile-time fixed size or they can be dynamic.

uint[3] fixed;  //array of fixed length 3
uint[] dynamic; //a dynamic array has no fixed size, it can keep growing

You can also create an array of structs. Using the previously created Voter struct:

Voter[] voting;

Note:  declaring an array as public will automatically create a getter method for it.

Voter[] public voting;

Mappings

Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value.

Mappings are declared as:

Mapping(_Keytype => _ValueType )

Note: _Keytype can be almost any type except for a dynamically sized array, a contract, an enum and a struct.

Example:

contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) {
balances[msg.sender] = newBalance;&nbsp; }}
contract MappingUser {
function f() returns (uint) {
MappingExample m = new MappingExample();
m.update(100);
return m.balances(this);
}}

Control Structures

Most of the control structures in JavaScript are available in Solidity except for switch and goto.

So there is: if, else, while, do, for, break, continue, return, ? :, with the usual semantics known from C or JavaScript.

Note: There is no type conversion from non-boolean to boolean types as there is in C and JavaScript.

Now let’s see how these Control structures are used in Solidity.

Example:

contract ControlStructure {
address public a;
function ControlStructure>){
// if-else can be used like this
if(input1==2)
a=1;
else
a=0;
// while can be used like this
while(input1>=0){
if(input1==5)
continue;
input1=input1-1;
a++;}
// for loop can be used like this
for(uint i=0;i<=50;i++) { a++; if(a==4) break; } //do while can be used like this do { a--; } (while a>0);
// Conditional Operator can be used like this
bool IsTrue = (a == 1)?true: false;
/*will show an error because
there is no type conversion from non-boolean to boolean
*/
if(1)
{
}

Moving on with our Solidity tutorial blog, let’s talk about the executable units of code within a Contract. These are called functions.

Functions

Here is how a function is declared in Solidity.

function sampleFunc(string name, uint amount) {
}

The above-declared is an empty body function which takes two parameters: a string and a uint.

You would call this function like:

sampleFunc("Shashank", 10000);

Talking about functions, Solidity also provides function modifiers.

Function Modifiers

It is used to easily change the behavior of the functions. These conditions can be checked before even making the function calls because they have been declared in the function definitions in the smart contracts.

Example: If you want to call a kill contract function through only the owner or creator of the function.

contract FunctionModifiers{
address public creator;
function FunctionModifiers() {
creator = msg.sender;}
Modifier onlyCreator() {
if(msg.sender!=creator){
throw; }
_; //resumes the function wherever the access modifier is used
}
function killContract() onlyCreator{ //function will not execute if an exception occurs
self-destruct(creator); }}

Inheritance

Solidity supports multiple Inheritance by copying code including polymorphism.

contract Owned {
address Owner ;
function owned() {
owner = msg.sender;
}}
contract Mortal is Owned {  // 'is' keyword is used for inheritance
function kill(){
self-destruct(owner);   }}
contract User is Owned, Mortal //Multiple inheritance
{
string public UserName;
function User(string _name){
UserName = _name;
}}

Alright, I feel the above-discussed concepts are sufficient enough for you to kick-start with Solidity programming.  

Go Code!!

With that, I conclude this Solidity Tutorial blog. I hope you enjoyed reading this blog and found it informative. By now, you must have acquired a sound understanding of what Solidity Programming Language is. Now go ahead and practice.

Got a question for us? Please mention it in the comments section and we will get back to you at the earliest.

If you wish to learn Solidity Language, build a career in the domain of Blockchain and gain expertise in Solidity programming, get enrolled in live-online Edureka Blockchain Certification Training here, that comes with 24*7 support to guide you throughout your learning period.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Solidity Tutorial – Solidity Programming For Beginners

edureka.co