0% found this document useful (0 votes)
39 views

Unit 4-Solidity

The document provides information about Solidity, which is a high-level programming language for implementing smart contracts on the Ethereum blockchain. It defines Solidity as a statically typed language that supports inheritance, libraries and complex user-defined types. It also explains that Solidity can be used to create smart contracts for applications like voting, crowdfunding and auctions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Unit 4-Solidity

The document provides information about Solidity, which is a high-level programming language for implementing smart contracts on the Ethereum blockchain. It defines Solidity as a statically typed language that supports inheritance, libraries and complex user-defined types. It also explains that Solidity can be used to create smart contracts for applications like voting, crowdfunding and auctions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Tutor: Dr Prasanna B T

Associate Professor
Dept. of CS&E
Sri Jayachamarajendra College of
Engineering
JSS Science and Technology University

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


BLOCKCHAIN : UNIT 4 :SOLODITY

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


SOLIDITY

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Solidity is a contract-oriented, high-level programming language for implementing smart
contracts. Solidity is highly influenced by C++, Python and JavaScript and has been
designed to target the Ethereum Virtual Machine (EVM).

Solidity is statically typed, supports inheritance, libraries and complex user-defined types
programming language.
You can use Solidity to create contracts for uses such as voting, crowdfunding, blind
auctions, and multi-signature wallets.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


What is Ethereum?
Ethereum is a decentralized ie. blockchain platform that runs smart contracts i.e. applications that run
exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


The Ethereum Virtual Machine (EVM)
The Ethereum Virtual Machine, also known as EVM, is the runtime environment for smart contracts in
Ethereum. The Ethereum Virtual Machine focuses on providing security and executing untrusted code by
computers all over the world.

The EVM specialised in preventing Denial-of-service attacks and ensures that programs do not have
access to each other's state, ensuring communication can be established without any potential interference.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


What is Smart Contract?
A smart contract is a computer protocol intended to digitally facilitate, verify, or enforce the negotiation or
performance of a contract. Smart contracts allow the performance of credible transactions without third parties.
These transactions are trackable and irreversible.

The concept of smart contracts was first proposed by Nick Szabo in 1994. Szabo is a legal scholar and
cryptographer known for laying the groundwork for digital currency.
It is fine if you do not understand Smart Contract right now, we will go into more detail later.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


This explains how we can setup Solidity compiler on CentOS machine. If you do not have a Linux machine then you
can use our Online Compiler for small contracts and for quickly learning Solidity.

Method 1 - npm / Node.js


This is the fastest way to install Solidity compiler on your CentoS Machine. We have following steps to install Solidity Compiler −
Install Node.js
First make sure you have node.js available on your CentOS machine. If it is not available then install it using the following commands −
# First install epel-release
$sudo yum install epel-release
# Now install nodejs
$sudo yum install nodejs
# Next install npm (Nodejs Package Manager )
$sudo yum install npm
# Finally verify installation $npm --version
If everything has been installed then you will see an output something like this −
3.10.10

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Install solc
Once you have Node.js package manager installed then you can proceed to install Solidity compiler as below −
$sudonpm install -g solc
The above command will install solcjs program and will make it available globally through out the system. Now you can test your Solidity compiler by issuing following
command −
$solcjs-version
If everything goes fine, then this will print something as follows −
0.5.2+commit.1df8f40c.Emscripten.clang
Now you are ready to use solcjs which has fewer features than the standard Solidity compiler but it will give you a good starting point.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Method 2 - Docker Image
You can pull a Docker image and start using it to start with Solidity programming. Following are the simple steps. Following is the command to pull a Solidity Docker Image.
$docker pull ethereum/solc:stable
Once a docker image is downloaded we can verify it using the following command.
$docker run ethereum/solc:stable-version
This will print something as follows −
$ docker run ethereum/solc:stable -version solc, the solidity compiler commandlineinterfaceVersion: 0.5.2+commit.1df8f40c.Linux .g++

Method 3: Binary Packages Installation


If you are willing to install full fledged compiler on your Linux machine, then please check official website Installing
the Solidity Compiler.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


A Solidity source files can contain an any number of contract definitions, import directives and pragma directives.
Let's start with a simple source file of Solidity. Following is an example of a Solidity file −
pragma solidity >=0.4.0 <0.6.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint)
{
return storedData;
}
}

Pragma
The first line is a pragma directive which tells that the source code is written for Solidity version 0.4.0 or anything newer that does not break functionality up to, but not
including, version 0.6.0.
A pragma directive is always local to a source file and if you import another file, the pragma from that file will not automatically apply to the importing file.
So a pragma for a file which will not compile earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0 will be written as follows −
pragma solidity ^0.4.0;
Here the second condition is added by using ^.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Contract
A Solidity contract is a collection of code (its functions) and data (its state) that resides at a specific address on
the Ethereumblockchain.
The line uintstoredData declares a state variable called storedData of type uint and the functions set and get can
be used to modify or retrieve the value of the variable.

Importing Files
Though above example does not have an import statement but Solidity supports import statements that are very similar to those available in JavaScript.
The following statement imports all global symbols from "filename".
import "filename";
The following example creates a new global symbol symbolName whose members are all the global symbols from "filename".
import * as symbolName from "filename";
To import a file x from the same directory as the current file, use import "./x" as x;. If you use import "x" as x; instead, a different file could be referenced in a global "include
directory".

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Now, let's write a simple smart contract. Our contract will allow us to store an unsigned integer and retrieve it.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


The code snippet above is a smart contract written in Solidity language. Let’s
take a moment to understand what the code we wrote in our smart contract
is doing line by line.

Line 1: Specifying SPDX license type, which is an addition after Solidity ^0.6.8;
whenever the source code of a smart contract is made available to the public,
these licenses can help resolve/avoid copyright issues. If you do not wish to
specify any license type, you can use a special value UNLICENSED or simply
skip the whole comment (it won’t result in an error, just a warning).

Line 2: On the first line we are declaring which Solidity compiler we want to
use. For instance, we are targeting any version between ≥ 0.4.0 and <0.7.0 .

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Line 3: We are declaring our contract here and naming it as Simplestorage. It is normal
practice to use the same filename as the contract name. For example - this contract will be
saved in the file name SimpleStorage.sol (.sol is the file extension for solidity smart contracts).

Line 4: We are declaring a uint (Unsigned Integer) variable named storedData, this variable
will be used to store data.

Line 5-7: Next, we will add a set function, using which we will change the value of our
variable storeData. Here set function is accepting a parameter x whose value, we are storing
into storeData. In addition, the function is marked as public which means that the function
can be called by anyone.

Line 8-10: We will add a get function to retrieve the value of storeData variable. This function
is marked as view which tells Solidity compiler that this is a read-only function.

Other than that the get function also has returns (uint), which means that the function will
return a uint. Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru
Deploying the Smart contract
After writing a smart contract it needs to be deployed on the ethereum
network, we will deploy our smart contract using Remix. There are other
ways to deploy smart contracts, but to make it beginner-friendly, we will use
Remix. Remix is an online web Ethereum IDE. It’s simple and supports many
functionalities.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Reserved Keywords
Following are the reserved keywords in Solidity −

abstract after alias apply


auto case catch copyof
default define final immutable
implements in inline let
macro match mutable null
of override partial promise
reference relocatable sealed sizeof
static supports switch try
typedef typeof unchecked

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


We're using Remix IDE to Compile and Run our Solidity Code base.
Step 1 − Copy the given code in Remix IDE Code Section.
Example
pragma solidity ^0.5.0;
contract SolidityTest {
constructor() public{
}
function getResult() public view returns(uint){
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}
}
Step 2 − Under Compile Tab, click Start to Compile button.
Step 3 − Under Run Tab, click Deploy button.
Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down.
Step 5 − Click getResult Button to display the result.

Output
0: uint256: 3

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Solidity supports both C-style and C++-style comments, Thus −
•Any text between a // and the end of a line is treated as a comment and is ignored by Solidity Compiler.
•Any text between the characters /* and */ is treated as a comment. This may span multiple lines.

Example
The following example shows how to use comments in Solidity.
function getResult() public view returns(uint){
// This is a comment. It is similar to comments in C++
/*
*This is a multi-line comment in solidity
*It is very similar to comments in C Programming
*/
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
}

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


While writing program in any language, you need to use various variables to store various information. Variables
are nothing but reserved memory locations to store values. This means that when you create a variable you
reserve some space in memory.
You may like to store information of various data types like character, wide character, integer, floating point, double
floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory.
Value Types
Solidity offers the programmer a rich assortment of built-in as well as user defined data types. Following table lists
down seven basic C++ data types −

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Type Keyword Values
Boolean bool true/false
Integer int/uint Signed and unsigned integers of varying
sizes.
Integer int8 to int256 Signed int from 8 bits to 256 bits. int256 is
the same as int.
Integer uint8 to uint256 Unsigned int from 8 bits to 256 bits. uint256
is the same as uint.
Fixed Point Numbers fixed/unfixed Signed and unsigned fixed point numbers of
varying sizes.
Fixed Point Numbers fixed/unfixed Signed and unsigned fixed point numbers of
varying sizes.
Fixed Point Numbers fixedMxN Signed fixed point number where M
represents number of bits taken by type
and N represents the decimal points. M
should be divisible by 8 and goes from 8 to
256. N can be from 0 to 80. fixed is same as
fixed128x18.

Fixed Point Numbers ufixedMxN Unsigned fixed point number where M


represents number of bits taken by type
and N represents the decimal points. M
should be divisible by 8 and goes from 8 to
256. N can be from 0 to 80. ufixed is same
as ufixed128x18.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Note: You can also represent the signed and unsigned fixed-point numbers as fixedMxN/ufixedMxN where M
represents the number of bits taken by type and N represents the decimal points. M should be divisible by 8 and
goes from 8 to 256. N can be from 0 to 80.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


address
address holds the 20 byte value representing the size of an Ethereum address. An address can be used to get the balance using .balance method and can be used to
transfer balance to another address using .transfer method.
address x = 0x212;
address myAddress = this;
if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Solidity supports three types of variables.
•State Variables − Variables whose values are permanently stored in a contract storage.
•Local Variables − Variables whose values are present till function is executing.
•Global Variables − Special variables exists in the global namespace used to get information about the
blockchain.
Solidity is a statically typed language, which means that the state or local variable type needs to be
specified during declaration. Each declared variable always have a default value based on its type. There
is no concept of "undefined" or "null".

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


State Variable
Variables whose values are permanently stored in a contract storage.
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10; // Using State variable
}
}
Local Variable
Variables whose values are available only within a function where it is defined. Function parameters are always local to that function.
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return result; //access the local variable
}
}

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Example
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return storedData; //access the state variable
}

Output
0: uint256: 10
We're using Remix IDE to Compile and Run our Solidity Code base.
Step 1 − Copy the given code in Remix IDE Code Section.
Step 2 − Under Compile Tab, click Start to Compile button.
Step 3 − Under Run Tab, click Deploy button.
Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down.
Step 5 − Click getResult Button to display the result.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Global Variables
These are special variables which exist in global workspace and provide information about the blockchain and
transaction properties.
Name Returns

blockhash(uint blockNumber) returns (bytes32) Hash of the given block - only works for 256 most recent, excluding
current, blocks
block.coinbase (address payable) Current block miner's address
block.difficulty (uint) Current block difficulty
block.gaslimit (uint) Current block gaslimit
block.number (uint) Current block number
block.timestamp (uint) Current block timestamp as seconds since unix epoch

gasleft() returns (uint256) Remaining gas


msg.data (bytes calldata) Complete calldata
msg.sender (address payable) Sender of the message (current caller)

msg.sig (bytes4) First four bytes of the calldata (function identifier)

msg.value (uint) Number of wei sent with the message

now (uint) Current block timestamp


tx.gasprice (uint) Gas price of the transaction
tx.origin (address payable) Sender of the transaction

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Solidity Variable Names
While naming your variables in Solidity, keep the following rules in mind.
•You should not use any of the Solidity reserved keywords as a variable name. These keywords are
mentioned in the next section. For example, break or boolean variable names are not valid.
•Solidity variable names should not start with a numeral (0-9). They must begin with a letter or an
underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
•Solidity variable names are case-sensitive. For example, Name and name are two different variables.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Scope of local variables is limited to function in which they are defined but State variables can have three
types of scopes.
•Public − Public state variables can be accessed internally as well as via messages. For a public state
variable, an automatic getter function is generated.
•Internal − Internal state variables can be accessed only internally from the current contract or contract
deriving from it without using this.
•Private − Private state variables can be accessed only internally from the current contract they are defined
not in the derived contract from it.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Example:
pragma solidity ^0.5.0;
contract C {
uint public data = 30;
uint internal iData= 10;

function x() public returns (uint) {


data = 3; // internal access
return data;
}
}
contract Caller {
C c = new C();
function f() public view returns (uint) {
return c.data(); //external access
}
}
contract D is C {
function y() public returns (uint) {
iData = 3; // internal access
return iData;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return storedData; //access the state variable
}
}
Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and '+' is
called the operator. Solidity supports the following types of operators.
•Arithmetic Operators
•Comparison Operators
•Logical (or Relational) Operators
•Assignment Operators
•Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
Solidity supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Sr.No. Operator & Description

1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Comparison Operators
Solidity supports the following comparison operators − , Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the
condition becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are
not equal, then the condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the
right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the
value of the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value
of the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru
Logical Operators
Solidity supports the following logical operators −, Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 && (Logical AND)


If both the operands are non-zero,
then the condition becomes true.
Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-
zero, then the condition becomes
true.
Ex: (A || B) is true.

3 ! (Logical NOT)
Reverses the logical state of its
operand. If a condition is true, then
the Logical NOT operator will make
it false.
Ex: ! (A && B) is false.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Bitwise Operators
Solidity supports the following bitwise operators −,Assume variable A holds 2 and variable B holds 3, then −
Sr.No. Operator & Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or
operand two is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a
value left by one position is equivalent to multiplying it by 2, shifting two
positions is equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.

6 >> (Right Shift)


Binary Right Shift Operator. The left operand's value is moved right by the
number of bits specified by the right operand.
Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on
the left are always zero.
Ex: (A >>> 1) is 1.
Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru
Assignment Operators, Solidity supports the following assignment operators −

Sr.No. Operator & Description


1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result to
the left operand.
Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the
result to the left operand.
Ex: C -= A is equivalent to C = C - A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the
result to the left operand.
Ex: C *= A is equivalent to C = C * A
5 /= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result
to the left operand.
Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left
operand.
Ex: C %= A is equivalent to C = C % A

Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes one of the two
given statements depending upon the result of the evaluation.

Sr.No Operator and Description


.

1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


While writing a contract, you may encounter a situation where you need to perform an action over and over
again. In such situations, you would need to write loop statements to reduce the number of lines.
Solidity supports all the necessary loops to ease down the pressure of programming.

Sr.No Loops & Description


1 While Loop
The most basic loop in Solidity is the while loop
which would be discussed in this chapter.

2 do...while Loop
The do...while loop is similar to the while loop
except that the condition check happens at the
end of the loop.

3 For Loop
The for loop is the most compact form of
looping. It includes the following three important
parts.

4 Loop Control
Solidity provides full control to handle loops and
switch statements

Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru


Dr Prasanna B T, Assoc Prof, CSE, SJCE, Mysuru

You might also like