Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Solidity Programming

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Solidity Programming
Solidity language designed for implementing smart contracts.

It is statically-typed object-oriented(contract-oriented) language.

Solidity is highly influenced by Python, c++, and JavaScript which runs on the Ethereum Virtual Machine(EVM).

Solidity supports complex user-defined programming, libraries and inheritance.

Solidity is primary language for blockchains running platforms.

Solidity can be used to creating contracts like voting, blind auctions, crowdfunding, multi-signature wallets, etc.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Variable
• 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
“A to Z” or digits from “0 to 9” and characters also.

• 3. The name of variables are case sensitive

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Declaration of Variables

• In Solidity declaration of variables is a little bit different, to declare a variable the user
has to specify the data type first followed by access modifier.

Syntax:
<type> <access modifier> <variable name> ;
Example:
int public number;

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Types of Variables
• Solidity supports three types of variables:

1. State Variables: Values of these variables are permanently stored in the contract storage. Each
function has its own scope, and state variables should always be defined outside of that scope.

// Solidity program to
// demonstrate state
// variables
pragma solidity ^0.5.0;

// Creating a contract
contract Solidity_var_Test {

// Declaring a state variable


uint8 public state_var;
// Defining a constructor
constructor() public {
state_var = 16;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
2. Local Variable: Values of these variables are present till the function executes and it cannot be
accessed outside that function. This type of variable is usually used to store temporary values.

// Solidity program to demonstrate


// local variables
pragma solidity ^0.5.0;

// Creating a contract
contract Solidity_var_Test {

// Defining function to show the declaration and


// scope of local variables
function getResult() public view returns(uint){

// Initializing local variables


uint local_var1 = 1;
uint local_var2 = 2;
uint result = local_var1 + local_var2;

// Access the local variable


return result;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
• 3. Global Variables: These are some special variables that can be used globally and give information
about the transactions and blockchain properties. Some of the global variables are listed below :

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
// Solidity program to
// show Global variables
pragma solidity ^0.5.0;

// Creating a contract
contract Test {

// Defining a variable
address public admin;

// Creating a constructor to
// use Global variable
constructor() public {
admin = msg.sender;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Literals
• Solidity provides usage of literal for assignments to variables.

• Literals do not have names; they are the values themselves.

• Variables can change their values during a program execution, but a literal remains the same value
throughout.

• Example:

1.Examples of integer literal are 1, 10, 1,000, -1, and -100.


2.Examples of string literals are "Ritesh" and 'Modi'. String literals can be in single or double quotes.
3.Examples of address literals are 0xca35b7d915458ef540ade6068dfe2f44e8fa733c and
0x1111111111111111111111111111111111111111.
4.Hexadecimal literals are prefixed with the hex keyword. An example of hexadecimal literals is hex"1A2B3F".
5.Solidity supports decimal literals with use of dot. Examples include 4.5 and 0.2.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Solidity – Operators

• Solidity supports the following types of operators based upon their


functionality.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment operators
6. Conditional Operator

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Arithmetic Operators

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Relational Operators

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Logical Operators

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Bitwise Operators

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Assignment Operator

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Conditional Operators
Syntax: condition true ? then A: else B

contract SolidityTest{

// Defining function to demonstrate


// conditional operator
function sub(
uint a, uint b) public view returns(
uint){
uint result = (a > b? a-b : b-a);
return result;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Data Structure and Control Structure

• A data structure is a particular way of organizing data in a computer memory so that it


can be used effectively.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Control Structures

• if, else, while, do, for, break, continue, with the usual semantics known
from C or JavaScript.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Loops
• While Loop.
This is the most basic loop in solidity, Its purpose is to execute a statement or block of statements
repeatedly as far as the condition is true and once the condition becomes false the loop terminates.
contract Types {

// Declaring a dynamic array


Syntax: uint[] data;

while (condition) { // Declaring state variable


uint8 j = 0;
statement or block of code to be executed if the condition is True
} // Defining a function to
// demonstrate While loop'
function loop(
) public returns(uint[] memory){
while(j < 5) {
j++;
data.push(j);
}
return data;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Do-While Loop
This loop is very similar to while loop except that there is a condition check which happens at the end of loop i.e. the loop will always
execute at least one time even if the condition is false.

Syntax:
do {
block of statements to be executed

} while (condition);

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
For Loop

Syntax:
for (initialization; test condition; iteration statement)
{
statement or block of code to be executed if the condition is True
}

// Creating a contract
contract Types {

// Declaring a dynamic array


uint[] data;

// Defining a function
// to demonstrate 'For loop'
function loop(
) public returns(uint[] memory){
for(uint i=0; i<5; i++){
data.push(i);
}
return data;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
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.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Creating an Array
• To declare an array in Solidity, the data type of the elements and the number of elements should be
specified. The size of the array must be a positive integer and data type should be a valid Solidity type.
//SPDX-License-Identifier;MIT
Syntax:
pragma solidity >=0.6.0 <0.9.0;
contract Types {
<data type> <array name>[size] = <initialization>
// Declaring state variables
// of type array
// uint[6] public data1;
int[5] public data;

// Defining function to add


// values to an array
function array_example() public returns (int[5] memory
){

data
= [int(50), -63, 77, -28, 90];
/* data1
= [uint(10), 20, 30, 40, 50, 60];*/

return data;
Introduction to Blockchain and distributed ledger & 19CS3618
} Department of Computer Science and Engineering
}
Array Operations
// Creating a contract
contract Types {

// Declaring an array
1. Accessing Array Elements. uint[6] data;

// Defining function to
2. Length of Array. // assign values to array
function array_example(
) public payable returns (uint[6] memory){
3. Push. data
= [uint(10), 20, 30, 40, 50, 60];
4. Pop. }
return data;

// Defining function to access


// values from the array
// from a specific index
function array_element(
) public payable returns (uint){
uint x = data[2];
return x;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
// Creating a contract
// Creating a contract function array_push( contract Types {
contract Types { ) public returns(uint[] memory){
// Defining an array
// Declaring an array data.push(60); uint[] data
uint[6] data; data.push(70); = [10, 20, 30, 40, 50];
data.push(80);
// Defining a function to // Defining a function to
// assign values to an array return data; // pop values from the array
function array_example( } function array_pop(
) public payable returns (uint[6] memory){ ) public returns(uint[] memory){
data = [uint(10), 20, 30, 40, 50, 60]; data.pop();
return data; return data;
} }
}
// Defining a function to
// find the length of the array
function array_length(
) public returns(uint) {
uint x = data.length;
return x;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
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 value type.

Syntax:

mapping(key => value) <access specifier> <name>;


Mapping(_Keytype => _ValueType )

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Creating a Mapping
• Mapping is defined as any other variable type, which accepts a key type and a value type.

// Defining contract
contract mapping_example {

//Defining structure
struct student
{
// Declaring different
// structure elements
string name;
string subject;
uint8 marks;
}

// Creating a mapping
mapping ( address => student) result;
address[] public student_result;
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Example

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
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 few predefined values, these values of the enumerated list
are called as enums.

• Options of are represented with integer values starting from zero, a default value can also be given
for the enum.

• By using enums it is possible to reduce the bugs in the code.

Syntax:
enum <enumerator_name> { element 1, elemenent 2,....,element n }

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
//SPDX-License-Identifier;MIT
pragma solidity >=0.6.0 <0.9.0;
contract My_data{
enum data1{
Sunday,
Monday,
Tuesday,
Wednesday,
Thruesday,
friday,
satuday

}
data1 day;
data1 constant x=data1.Monday;
function Get_value() public pure
returns(data1){
return x;
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Struct
• Solidity allows user to create their own data type in the form of structure.
• The struct contains a group of elements with a different data type.
• Generally, it is used to represent a record.
• To define a structure struct keyword is used, which creates a new data type.
Syntax:
struct <structure_name> {
<data type> variable_1;
<data type> variable_2;
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Project: Library Management System
• The contract Test consists of a structure Book, and functions are defined to set and
contract test {
get values of the elements of the structure. // Declaring a structure
struct Book {
string name;
string writter;
uint id;
bool available;
// Defining a function to set values }
// Declaring a structure object
// for the fields for structure book1 Book book1;
// Assigning values to the fields for the structure object book2
function set_book_detail() public { Book book2 = Book("Building Ethereum DApps",
book1 = Book("Introducing Ethereum "Roberto Infante ",2, false);

and Solidity", // Defining function to print book2 details


function book_info(
"Chris Dannen", )public view returns (
string memory, string memory, uint, bool) {
1, true);
} return(book2.name, book2.writter,
book2.id, book2.available);
}

// Defining function to print book1 details


function get_details(
) public view returns (string memory, uint) {
return (book1.name, book1.id);
}
Introduction to Blockchain and distributed ledger & 19CS3618 } Department of Computer Science and Engineering
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 state.

• A default constructor is created by the compiler if there is no explicitly defined


constructor.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Creating a constructor
• Define the smart Contractor Creating a constructor

Syntax: Syntax:
contract contractorName{ constructor <Access Modifier> {
} }

➢A Constructor is defined using a constructor keyword without any function name


followed by an access modifier.

➢It’s an optional function which initializes state variables of the contract.

➢ A constructor can be either internal or public, an internal constructor marks contract as


abstract.
Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
pragma solidity ^0.5.0;

// Creating a contract
contract constructorExample {

// Declaring state variable


string str;

// Creating a constructor
// to set value of 'str'
constructor() public {
str = “welcome to Solidity programming Language";
}

// Defining function to
// return the value of 'str'
function getValue( ) public view returns (string memory) {
return str;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Functions
Function can be declared inside or outside the contract.

contract Helloworld{

string public hello = "Hello World;

function hello() public view returns(string memory)


{
return hello;
}
}

If we want to access the state variable from outside, we need to set the visibility type to public and do the same for the function.
In our case, the function returns something, and we can mark it as view.
It returns a string that is stored in the memory and removed after the execution is finished.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
The places, where the function variables and return data can be stored, are:

•memory - the lifetime of the variable is limited to the function scope, it isn't saved
anywhere;
•storage - data is stored in the smart contract storage on the blockchain;
•calldata - data is stored outside from where the function is being called.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Function Types
• Functions in Solidity can execute instructions, view data. It can be a view or pure when we view the data.
• The difference between these two is that pure functions don't modify nor read the state variables.

function helloWorld() public pure returns(string memory) {


return "Hello World";
}

The above code, we are not reading nor changing anything on the blockchain but just returning some data.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
view function

• The view functions are read-only function, which ensures that state variables cannot be
modified after calling them.

contract Test {

// Declaring state
// variables
uint num1 = 2;
uint num2 = 4;

// Defining view function to


// calculate product and sum
// of 2 numbers
function getResult(
) public view returns(
uint product, uint sum){
uint num1 = 10;
uint num2 = 16;
product = num1 * num2;
sum = num1 + num2;
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
pure functions
• The pure functions do not read or modify the state variables, which returns the values only
using the parameters passed to the function or local variables present in it.

• If the statements which read the state variables, access the address or balance, accessing any
global variable block or msg, calling a function which is not pure, etc. are present in pure
functions then the compiler throws a warning in such cases.
// Defining a contract
contract Test {

// Defining pure function to


// calculate product and sum
// of 2 numbers
function getResult(
) public pure returns(
uint product, uint sum){
uint num1 = 2;
uint num2 = 4;
product = num1 * num2;
sum = num1 + num2;
}
}
Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Constructor in Inheritance
• In case if a constructor is not defined then the default constructor is called, but if the constructor is
defined in a parent contract and having some arguments then the child contract should also provide
the required parameters to the constructor.

• If the child contract is not passing any parameter to the parent’s constructor the child contract will
become an abstract contract.

• There are two ways of calling a parent contract’s constructor:

1. Direct Initialization:

2. Indirect Initialization:

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
1. Direct Initialization: In the below example, the direct initialization method is used to
initialize the constructor of the parent class.

// Solidity program to demonstrate


// Constructor in Inheritance
pragma solidity ^0.5.0;

// Creating a contract
contract Base {

// Declaring variable
uint data;

// Defining a constructor
constructor(uint _data) public {
data = _data;
}

// Defining function
function Print(
) public returns(string memory){
return "Direct Initialization";
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
// Child contract inheriting
// the parent contract 'Base'
contract Derived is Base(2){
// Defining a constructor
constructor() public {}
// Defining function to access
// variable of parent contract
function getData(
) external returns(uint){
uint result = data ** 2;
return result;
}
}
// Caller contract
contract caller{
// Creating an object of child contract
Derived c = new Derived();
// Accessing functions of parent
// and child contract using
// object of child contract
function getResult() public returns(uint){
c.Print();
return c.getData();
}
}

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
• Indirect Initialization:
In the below example, the indirect initialization
using Base(string(abi.encodePacked(_info, _info))) is done to initialize the
constructor of the base class.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Solidity libraries
• Libraries in Solidity smart contracts are blocks of reusable code. They contain functions
used by other contracts on the blockchain network.

• There are advantages to using libraries in Solidity smart contracts.

• The biggest advantage is code reusability across contracts. Since libraries are reusable
they help prevent duplication of code. In addition, libraries save on gas since the same
code is not deployed multiple times to the blockchain.

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Creating Library

• A library contract is defined by using the library keyword instead of a general contract.

• Libraries do not have any storage thus it cannot hold state variables, fallback or payable functions also
cannot be created inside the library as it cannot store ethers.

• Libraries are not for changing the state of the contract, it can only be used for performing basic operations
based on inputs and outputs. // Library Definition
library libraryExample {
// Defining structure
struct Constants {
Syntax: // Declaring variables
library <libraryName> uint Pi;
uint EulerNb;
{ uint PythagoraConst;
uint TheodorusConst;
// block of code }
} }

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
Deploying Library

import <libraryName> from “./library-file.sol”;

Syntax:
<libraryName> for <dataType>

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering
//SPDX-License-Identifier;MIT

pragma solidity >=0.6.0 <0.9.0;

library Search {

function indexOf(uint[] storage self, uint value) public view returns (uint) {

for (uint i = 0; i < self.length; i++)

if (self[i] == value)

return i;

return uint(-1);

contract Test {

uint[] data;

constructor() public {

data.push(1);

data.push(2);

data.push(3);

data.push(4);

data.push(5);

function isValuePresent() external view returns(uint){

uint value = 4;

//search if value is present in the array using Library function

uint index = Search.indexOf(data, value);

return index;

Introduction to Blockchain and distributed ledger & 19CS3618 Department of Computer Science and Engineering

You might also like