100% found this document useful (1 vote)
121 views

Smart Contracts

Smart contracts are lines of code that automatically execute when predetermined terms are met. Solidity is a programming language for writing smart contracts. It supports variables, functions, operators and control structures like if/else statements. Smart contracts provide benefits like speed, accuracy, security and cost savings.

Uploaded by

harikach2208
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
100% found this document useful (1 vote)
121 views

Smart Contracts

Smart contracts are lines of code that automatically execute when predetermined terms are met. Solidity is a programming language for writing smart contracts. It supports variables, functions, operators and control structures like if/else statements. Smart contracts provide benefits like speed, accuracy, security and cost savings.

Uploaded by

harikach2208
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/ 69

Smart Contracts & Solidity

By
Dr. Shashidhar R
Assistant Professor, Dept of CSE,
Bennett University-Greater Noida
What are smart contracts?
• Smart contracts are lines of code that are stored on a blockchain and
automatically execute when predetermined terms and conditions are met.
• It’s a computer protocol. It is called smart because of its ability to verify
and execute a contract without any help from third parties. The contract
exists in the decentralized Blockchain network and contains all the terms
of a particular agreement.
• The blockchain is then updated when the smart contract is completed.
What are the benefits of smart contracts?

• Speed and accuracy: Smart contracts are digital and automated, so you
won’t have to spend time processing paperwork and correcting the errors.
• (It saves time: instead of taking days, a contract can be verified in
minutes.)
• Trust: Smart contracts automatically execute transactions following
predetermined rules, and the encrypted records of those transactions are
shared across participants.
• Security: Blockchain transaction records are encrypted, and that makes
them very hard to hack. Because each individual record is connected to
previous and subsequent records on a distributed ledger.
• Savings: Smart contracts remove the need for intermediaries because
participants can trust the visible data and the technology to properly
execute the transaction.
• (It saves money: there is no need to pay fees to any intermediaries (such
as lawyers, real estate).)
Solidity Programming

• Solidity is an object-oriented, high-level language for implementing smart


contracts.
• Solidity was influenced by C++ and JavaScript and is designed to target
the Ethereum Virtual Machine (EVM).
• Solidity is statically typed, supports inheritance, libraries and complex
user-defined types among other features.
Compilation
• A smart contract is a stand-alone script usually written in Solidity and
compiled into binary or JSON and deployed to a specific address on
the blockchain.
• The solidity compiler turns code into EVM bytecode, which can then be
sent to the Ethereum network as a deployment transaction.
• Such deployments have more substantial transaction fees than smart
contract interactions and must be paid by the owner of the contract.
Ethereum Smart Contract
When you’re writing Solidity code, you should first make sure to use a proper
layout. Contracts should be at the end of it. Here is the proper order of elements:
• The pragma statement
• Import statements
• Interfaces
• Libraries
• Contracts
Smart Contract
• Type declarations
• State variables
• Events
• Functions
• All Ethereum contracts have an individual address in the EVM
blockchain. They also support inheritance, meaning one Ethereum
contract can inherit elements from others.
Simple Smart Contract
• pragma solidity ^0.4.7;
contract Simple {
uint stateVar;
function set(uint x) public {
stateVar = x;
}
function get() public view returns (uint) {
return stateVar;
}
}
Counter Smart Contract
pragma solidity ^0.4.16;
contract HelloWorld {

uint counter = 5; //state variable we assigned earlier


function add() public { //increases counter by 1
counter++;
}

function subtract() public { //decreases counter by 1


counter--;
} function getCounter() public constant returns (uint) {
return counter;
}
}
A Simple Smart Contract

pragma solidity ^0.4.21;


contract Hello {
string public message;
function Hello(string initialMessage) public
{
message = initialMessage;
}
function setMessage(string newMessage) public
{
message = newMessage;
}
}
A "Hello World" program in Solidity
• pragma solidity ^0.6.0;
• contract HelloWorld
• {
• function helloWorld() external pure returns (string memory) {
• return "Hello, World!";
• }
• }
Value Types in Solidity

The following types are also called value types because variables of these types will
always be passed by value.
1. Boolean: The possible values are constants i.e., true or false (Keyword: Bool)
2. Integers: Signed and unsigned integers of various sizes. (Keyword: int/uint)
contract MySample
{
uint x =50;
}
3. Address: Holds a 20-byte value (size of an Ethereum address). Address types
also have members and serve as a base for all contracts.
Keyword: address
• 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 (x.balance < 10 && myAddress.balance > = 10)
x.transfer(10);
4. Strings: String literals are written with either double or single-quotes “foo” or
‘bar’.
string language = "Solidity";
Storage Locations in Solidity
• Storage: where all the contract state variables reside. Every contract has
its own storage and it is persistent between function calls.
• Memory: hold temporary values and gets erased between (external)
function calls and is cheaper to use.
• Stack: hold small local variables and is almost free to use, but can only
hold a limited amount of values
Operators

Solidity has four types of


operators
Arithmetic Operators
 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;
Incremental & Bitwise Operators
2. Incremental operators in solidity: a++, ++a, a+=1, a=a+1
• Rules applicable to other programming languages are similar in solidity
also.
3. Bitwise Operators:
(Bitwise OR) ‘|’
(Bitwise And) ‘&’
(Bitwise negation) ‘~’
(Bitwise right shift) ‘>>’
(Bitwise left shift) ‘<<‘
Logical Operators
Logical operators in Solidity:
• ! (logical negation)
• && (logical and)
• || (logical or)
• ==(equality)
• != (not equal)
Reserved Keywords
Solidity - Comments

• 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.
Solidity - Variables

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.
State Variable

pragma solidity ^0.5.0;


contract SolidityTest
{
uint storedData; // State variable
SolidityTest() public
{
storedData = 10; // Using State variable
}
}
Local Variable

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
}

}
Solidity - Special Variables

block.difficulty (uint)-current block difficulty.


block.gaslimit (uint)-Current block gaslimit.
block.number (uint)- Current block number.
block.timestamp-Current block timestamp
gasleft() returns (uint256)-Remaining gas.
msg.data (bytes calldata)-Complete calldata.
msg.sender (address payable)-Sender of the message
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
URL: https://www.blockchain.com/explorer/api/q
Global Variables
Solidity - Variable Scope

Scope of local variables is limited to function in which they are defined


but State variables can have different types of scopes.
• public − Public functions/ Variables can be used both externally and
internally.
Variable Scope
• internal − Internal functions/ Variables can only be used internally or by
derived contracts.
• private − Private functions/ Variables can only be used internally and not
even by derived contracts.
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 result; //access the state variable
}
}
Solidity - if statement

if (expression)
{
Statement(s) to be executed if expression is true
}
if...else statement

if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Solidity - if...else if... statement.

if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
Solidity - While Loop

while (expression)
{
Statement(s) to be executed if expression is true
}
Solidity - do...while loop

do {
Statement(s) to be executed;
} while (expression);
Solidity - For Loop

for (initialization; test condition; iteration statement)


{
Statement(s) to be executed if test condition is true
}
Solidity - Functions

The basic syntax is shown here.


function function-name(parameter-list) scope returns()
{
//statements
}
pragma solidity ^0.5.0;
contract Test {
function getResult() public view returns(uint)
{
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return result;
}
}
View Functions in Solidity

View functions can read contract storage variables but cannot modify them. They provide a way to
retrieve information from the contract state without changing it.
pragma solidity ^0.8.0;

contract ViewExample {
uint private data;

function setData(uint _data) public {


data = _data;
}

function getData() public view returns (uint) {


return data;
}
}
Pure Functions in Solidity

Pure functions do not read or modify the state of the contract. Use pure functions for mathematical
calculations, conversions, and any logic that doesn't depend on external state.

pragma solidity ^0.8.0;

contract PureExample {
function add(uint a, uint b) public pure returns (uint) {
return a + b;
}
}
• View Functions: Ensure that they will not modify the state. A function
can be declared as view.
• Pure Functions: Ensure that they not read or modify the state. A function
can be declared as pure.
pragma solidity ^0.5.0;
contract Test {
function getResult() public pure returns(uint product, uint sum){
uint a = 1;
uint b = 2;
product = a * b;
sum = a + b;
}
}
The return Statement

pragma solidity ^0.5.0;


contract Test {
function getResult() public view returns(uint product, uint sum)
{
uint a = 1; // local variable
uint b = 2;
product = a * b;
sum = a + b;
}
}
Solidity - Function Overloading

You can have multiple definitions for the same function name in the same
scope.

The definition of the function must differ from each other by the types
and/or the number of arguments in the argument list.
pragma solidity ^0.5.0;
contract Test {
function getSum(uint a, uint b) public pure returns(uint){
return a + b;
}
function getSum(uint a, uint b, uint c) public pure returns(uint){
return a + b + c;
}
function callSumWithTwoArguments() public pure returns(uint){
return getSum(1,2);
}
function callSumWithThreeArguments() public pure returns(uint){
return getSum(1,2,3);
}
}
Solidity - Arrays

• Array is a data structure, which stores a fixed-size sequential collection of


elements of the same type.
• All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last
element.
• In Solidity, an array can be of compile-time fixed size or of dynamic size.
Declaring Arrays

Syntax:
type arrayName [ arraySize ];
Example: uint balance[10];
To declare an array of dynamic size in Solidity, the programmer specifies the
type of the elements as follows −
type[] arrayName;
Initializing Arrays

uint balance[3] = [1, 2, 3];

uint balance[] = [1, 2, 3];

balance[2] = 5;
Creating dynamic memory arrays

Dynamic memory arrays are created using new keyword.


uint size = 3;
uint balance[] = new uint[](size);

Accessing Array Elements:


uint salary = balance[2];
Solidity Arrays

pragma solidity ^0.5.0;


contract Types {
uint[] data = [10, 20, 30, 40, 50];
int[] data1;
function dynamic_array() public returns( uint[] memory, int[] memory)
{
data1= [int(-60), 70, -80, 90, -100, -120, 140];
return (data, data1);
}
}
Array Operations
pragma solidity ^0.5.0;
contract Types {
uint[6] data;
function array_example( ) public returns (uint[6] memory)
{
data = [uint(10), 20, 30, 40, 50, 60];
return data;
}
function array_element( ) public returns (uint)
{
uint x = data[2];
return x;
}
}
Push operation
pragma solidity ^0.5.0;
contract Types {
uint[] data = [10, 20, 30, 40, 50];
function array_push( ) public returns(uint[] memory)
{
data.push(60);
data.push(70);
data.push(80);
}
function getAllElements() public view returns (uint[] memory) {
return data;
}
}
Pop operation
pragma solidity ^0.5.0;
contract Types {
uint[] data = [10, 20, 30, 40, 50];
function array_pop( ) public returns(uint[] memory){
data.pop();
return data;
}
}
Solidity Program to illustrate Dynamic Memory Arrays

pragma solidity ^0.8.0;


contract DynamicArrayExample {
uint[] public dynamicArray;

function addElement(uint _element) public {


dynamicArray.push(_element);
}

function getArrayLength() public view returns (uint) {


return dynamicArray.length;
}

function removeLastElement() public {


require(dynamicArray.length > 0, "Array is empty");
dynamicArray.pop();
}
function getAllElements() public view returns (uint[] memory) {
return dynamicArray;
}
}
Solidity - Structs

• To define a Struct, you must use the struct keyword.


• The struct keyword defines a new data type, with more than one member.
• The format of the struct statement is as follows −
struct struct_name
{
type1 type_name_1;
type2 type_name_2;
type3 type_name_3;
}
Struct Example
struct Book {
string title;
string author;
uint book_id;
}
pragma solidity ^0.5.0;
contract test {
struct Book {
string title;
string author;
uint book_id;
}
Book book;
function setBook() public {
book = Book('Learn Java', ‘SR', 1);
}
function getBookId() public view returns (uint) {
return book.book_id;
}
}
• pragma solidity ^0.4.18;
• contract Courses {
• struct Instructor {
• uint age;
• string fName;
• string lName;
• }
• }
• Here, we have a struct of Instructor, which will store their name, first name and
last name.
• It would also be handy if we could reference each instructor by their Ethereum
address. That's where we'll create a mapping.
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 used to associate the unique Ethereum address with the
associated value type.
Syntax:
mapping(key => value) <access specifier> <name>;
Mapping Example
pragma solidity ^0.8.0;
contract SimpleMappingExample {
// Define a mapping to store the balance of each address
mapping(address => uint) public addressToBalance;

// Function to set the balance for a specific address


function setBalance(address _address, uint _balance) public {
addressToBalance[_address] = _balance;
}

// Function to get the balance of a specific address


function getBalance(address _address) public view returns (uint) {
return addressToBalance[_address];
}
}
Solidity - Mathematical Functions

Solidity provides inbuilt mathematical functions as well.


Following are heavily used methods −

addmod(uint x, uint y, uint k) returns (uint)


mulmod(uint x, uint y, uint k) returns (uint)
pragma solidity ^0.5.0;
contract Test {
function callAddMod() public pure returns(uint){
return addmod(4, 5, 3);
}
function callMulMod() public pure returns(uint){
return mulmod(4, 5, 3);
}
}
Solidity - Cryptographic Functions

Solidity provides inbuilt cryptographic functions as well. Following are


important methods:
1) keccak256(bytes memory) returns (bytes32)
2) sha256(bytes memory) returns (bytes32)
3) ripemd160(bytes memory) returns (bytes20)
pragma solidity ^0.5.0;
contract Test {
function callKeccak256() public pure returns(bytes32 result)
{
return keccak256("ABC");
}
}
Solidity - Inheritance

Inheritance is a way to extend functionality of a contract.

A derived contract can access all non-private members including internal


methods and state variables.
Function overriding is allowed provided function signature remains same.
We can call a super contract's function using super keyword or using super
contract name.
pragma solidity ^0.5.0;
contract C {
uint private data;
uint public info;
constructor() public {
info = 10;
}
function increment(uint a) private pure returns(uint) { return a + 1; }
function updateData(uint a) public { data = a; }
function getData() public view returns(uint) { return data; }
function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
Derived Contract
contract E is C {
uint private result;
C c = new C();
function getComputedResult() public {
result = compute(3, 5);
}
function getResult() public view returns(uint) { return result; }
function getData() public view returns(uint) { return c.info(); }

You might also like