0% found this document useful (0 votes)
6 views86 pages

Week 3

Uploaded by

mzmindykkyan
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)
6 views86 pages

Week 3

Uploaded by

mzmindykkyan
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/ 86

CSIT6000Q-Blockchain &

Smart Contracts
Week – 3
Pritom Rajkhowa
Consensus Model

Consen Model
sus

This is a procedure we are going to use to make sure that everyone


agrees on something
Block Creator 1

Block Creator 2

Block Creator 3
Bob paid Alice LD20
{Signature}

Bob paid Eve LD20


Block Creator 1 {Signature}

Eve paid Alice LD30


{Signature}

Block Creator 2

Block Creator 3
Previous Hash

Bob paid Alice LD20


{Signature}

Bob paid Eve LD20


Block Creator 1 {Signature}

Eve paid Alice LD30


{Signature}

7567454092

Block Creator 2
SHA256

Block Creator 3
Block Creator 1

Block Creator 2

Block Creator 3
Previous Hash

Reword LD10

Bob paid Alice LD20


{Signature}

Bob paid Eve LD20


Block Creator 1 {Signature}

Eve paid Alice LD30


{Signature}

7567454092

Block Creator 2
SHA256

Block Creator 3
Conflicting Transaction
TRUST CENTRAL
AUTHORITY
COMPUTATION
WORK
Eve want to fraud
Bob with fake
transaction

Transaction

85665780
Eve want to fraud
Bob with fake
transaction

Transaction

85665780
Proof of Work

According to the Ethereum Foundation, the current Proof-of-Work system


consumes roughly 5.13 gigawatts on a continuous basis
According to Digiconomist, Bitcoin miners alone uses about 54 TWh of electricity,
enough to power 5 million households in the US or even power the entire country of
New Zealand or Hungary.
Proof of Stake
Proof of Stake
Validator
Chance

Stake
Validator
How to create a MetaMask Wallet

MetaMask is a cryptocurrency wallet used to interact with the Ethereum


blockchain. It can be accessed through an app or through a browser extension.
Step 1: Download MetaMask wallet

Go to https://metamask.io/ and click


on “Download”. Choose your preferred
browser or mobile application and
install the MetaMask extension.

MetaMask supports iOS, Android


native apps along with
Chrome, Firefox, Brave and Edge
browser extensions.
Step 2: MetaMask wallet installation

Click on the MetaMask extension You can either import an existent


and click on “Get Started”. wallet using the seed phrase or create
a new one.
Step 4: Create a strong password for your wallet.
Step 5: Securely store the seed phrase for your wallet

Click on “Click here to reveal secret words” to show the seed phrase.
• MetaMask requires that you store your seed phrase in a safe place. It is the only way to recover your funds
should your device crash or your browser reset. We recommend you write it down. The most common
method is to write your 12-word phrase on a piece of paper and store it safely in a place where only you
have access. Note: if you lose your seed phrase, MetaMask can’t help you recover your wallet and your
funds will be lost forever.
• Never share your seed phrase or your private key to anyone or any site, unless you want them to have full
control over your funds.

Click on “Next”.
Step 6: Seed phrase confirmation

Confirm your secret backup phrase by clicking on each word in the order in which the words were presented
on the previous screen. Click on “Confirm” to proceed.
Congratulations! Your MetaMask wallet has been set up successfully.

You can now access your wallet by clicking on the MetaMask icon at the top-right-end corner of your preferred browser.
Blockchain Demo:
https://andersbrownworth.com/blockchain/hash

https://andersbrownworth.com/blockchain/block

https://andersbrownworth.com/blockchain/blockchain

https://andersbrownworth.com/blockchain/distributed

https://andersbrownworth.com/blockchain/tokens

https://andersbrownworth.com/blockchain/public-private-keys/keys
Elliptic Curve Digital Signature Algorithm
https://eth-converter.com/
How Blockchain works

User Requested
Transaction is Transaction will be validated
User Once the transaction is verified by Transaction Is
Broadcasted to by any node in this Network
Requests A multiple Nodes in the Blockchain completed
Blockchain through some algorithms and
transaction peer-to-peer network then new block gets added to
smart contract chain and replicated across all the
network
nodes
Ethereum Blockchain framework
Ethereum is a decentralized platform that runs smart
contracts: applications that run exactly as programmed
without any possibility of downtime, censorship, fraud or
third-party interference.
Smart Contract
Agreements are written as Smart Contracts.

Smart Contracts are business logic

Transactions are validated against Smart Contract

Digitized and codified rules of transaction between


accounts

In Ethereum world smart contracts are written in


language called Solidity and deployed into Ethereum
network
Smart Contract

A option contract between A triggering event like an Regulator can the


parties written as code expiration date and strike blockchain to understand
into the blockchain. The price is hit and executes the activity in the market
individual involves are itself according to coded while maintaining the
anonymous, but contract terms . privacy of individual actor
are in public ledger. positions.
How smart contract works
https://financesonline.com/what-is-a-smart-contract/
Smart Contract: Where you can use Smart
Contract

Financial derivatives
Insurance premiums
Breach contracts
Property law
Credit enforcement
Financial services
Legal processes
Crowdfunding agreements
And more
What Is Solidity?
Solidity is a type of object-oriented
programming language. This
programing language is developed
specifically for smart contracts. This
type of language is widely used in
creating smart contracts features in
blockchain platforms. It’s influenced
by C++, JavaScript and Python.
Solidity also uses Ethereum Virtual
Machine to function properly.
Ethereum

Ethereum is an open-source blockchain


platform that offers smart contract facilities.
Solidity was first introduced as a new type of
programing language for the Ethereum
platform.

Ether is the primary token for the platform.


This platform is dedicated to developers for
helping them develop and deploy
decentralized applications.
Smart Contracts
Smart contracts are a type of automated digital
contract. Here, parties within the contract will set
up specific rules and based on that rules, the
contracts will get executed.

Developers use the Solidity programming


language to develop smart contracts. Using
Solidity, you can program the contracts to do any
type of task.
Ethereum Virtual Machine
Ethereum Virtual Machine is a crucial
part of understanding Solidity. EVM
offers a runtime environment for smart
contracts. Using EVM, smart contracts
can execute their core objectives with
higher security.

It’s also very effective in preventing DOS


or Denial-of Service attacks. EVM comes
with a specific set of codes or
instructions to run specific tasks within
the execution environment.
Understanding the Solidity
Syntax
Pragma: In Solidity, a pragma language will specify how the compiler
will process any type of input. Typically, the first line of code in Solidity
based smart contracts contains the pragma.

Contract: uintstoredData component within the code will denote the


Solidity contract. This part will contain all the data and code needed for
locating a particular address within the blockchain.

File Importing: Solidity offers similar support for file import systems like
JavaScript.
Value Types in Solidity
• Variables are only locations that are reserved for storing values.
Thus, users can reserve any amount of memory for a certain
variable.

• Solidity comes with a vast list of value types, such as Boolean,


double floating-point, integers, character, etc.

• The operating system will be responsible for allocating the memory


and selecting the data to store for a particular variable.
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.
Primitive Data Types
Unsigned and signed fixed-point numbers varying in sizes
8 bits to 256 bits Unsigned integer
8 bits to 256 bits Signed integer
Boolean Signed
fixed-point number
Unsigned fixed-point number
Data types
• bool
• uint/int
• bytes
• address
• mapping
• enum
• struct
• bytes/String
Global Varibles
Solidity : A Deep Dive into its
Mechanism
Upgrading Contracts
Solidity offers the option to create contracts that can be upgradeable.
As blockchain is immutable, once a contract is established, it can’t be
altered.

However, Solidity allows contracts to interact with one another and call
a contract to perform a specific logic.
Import
The import keyword helps import other Solidity files and we can access its code
within the current Solidity file and code. This helps us write modular Solidity code.

The syntax for using import is as follows:

import <filename> ;

File names can be fully explicit or implicit paths:

Import 'CommonLibrary.sol';
What is a Contract in Solidity?

The contract is similar to classes in java. It is a collection of contract


functions and their data(state) that is stored in the ethereum
blockchain network.
Syntax of a contract code:
Solidity Compilation Process
Comments
There are the following three types of comment in Solidity:
Single-line comments
Multiline comments
Ethereum Natural Specification (Natspec)

Single-line comments are denoted by a double forward slash //,


Multiline comments are denoted using /* and */.
Natspec has two formats: ///
Constants

Constants are variables that cannot be modified.


Their value is hard coded and using constants can save gas cost.
Immutable

Immutable variables are like constants. Values of immutable variables can be set inside the constructor but cannot be
modified afterwards.
Reading and Writing to a State Variable

To write or update a state variable you need to send a transaction.


On the other hand, you can read state variables, for free, without any transaction fee.
Ether and Wei

Transactions are paid with ether.


Similar to how one dollar is equal to 100 cent, one ether is equal to 1018 wei.
Gas
How much ether do you need to pay for a transaction?
You pay gas spent * gas price amount of ether, where
• gas is a unit of computation
• gas spent is the total amount of gas used in a transaction
• gas price is how much ether you are willing to pay per gas
Transactions with higher gas price have higher priority to be included in a block.
Unspent gas will be refunded.

Gas Limit
There are 2 upper bounds to the amount of gas you can spend
• gas limit (max amount of gas you're willing to use for your transaction, set by you)
• block gas limit (max amount of gas allowed in a block, set by the network)
If / Else
Solidity supports conditional statements if, else if and else.
For and While Loop
Solidity supports for, while, and do while loops.
Don't write loops that are unbounded as this can hit the gas limit, causing your
transaction to fail.
For the reason above, while and do while loops are rarely used.
Mapping

Maps are created with the syntax mapping(keyType => valueType).

The keyType can be any built-in value type, bytes, string, or any contract.

valueType can be any type including another mapping or an array.

Mappings are not iterable.


Mapping
Array
Array can have a compile-time fixed size or a dynamic size.

Declaring Arrays
To declare an array of fixed size in Solidity, the programmer specifies the type of
the elements and the number of elements required by an array as follows −
type arrayName [ arraySize ];

This is called a single-dimension array. The arraySize must be an integer constant


greater than zero and type can be any valid Solidity data type. For example, to
declare a 10-element array called balance of type uint, use this statement −

uint balance[10];

To declare an array of dynamic size in Solidity, the programmer specifies the type of the elements as follows −
type[] arrayName;
Array
Initializing Arrays
You can initialize Solidity array elements either one by one or using a single
statement as follows −
uint balance[3] = [1, 2, 3];

The number of values between braces [ ] can not be larger than the number of
elements that we declare for the array between square brackets [ ]. Following
is an example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization
is created. Therefore, if you write −
uint balance[] = [1, 2, 3];

You will create exactly the same array as you did in the previous example.
balance[2] = 5;

The above statement assigns element number 3rd in the array a value of 5.
Creating dynamic memory arrays
Dynamic memory arrays are created using new keyword.
uint size = 3;
uint balance[] = new uint[](size);

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example −
uint salary = balance[2];

The above statement will take 3rd element from the array and assign the value to salary
variable. Following is an example, which will use all the above-mentioned three concepts
viz. declaration, assignment and accessing arrays −

Members
• length − length returns the size of the array. length can be used to change the size of
dynamic array be setting it.
• push − push allows to append an element to a dynamic storage array at the end. It returns
the new length of the array.
Enum

Solidity supports enumerables and they


are useful to model choice and keep For example, if we consider an
track of state. Enums can be declared application for a fresh juice shop, it
outside of a contract. Enums restrict a would be possible to restrict the glass
variable to have one of only a few size to small, medium, and large. This
predefined values. The values in this would make sure that it would not allow
enumerated list are called enums. With anyone to order any size other than
the use of enums it is possible to reduce small, medium, or large.
the number of bugs in your code.
Structure
You can define your own type by creating a struct.
They are useful for grouping together related data.
Structs can be declared outside of a contract and imported in another contract.

Struct types are used to represent a record. Suppose you want to keep track of yourbooks in a library.

You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Struct

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 −
Structure Example
Data Locations - Storage, Memory
and Calldata

Variables are declared as


either storage, memory or calldata to explicitly specify the
location of the data.
• storage - variable is a state variable (store on blockchain)
• memory - variable is in memory and it exists while a function
is being called
• calldata - special data location that contains function
arguments
Function

There are several ways to return outputs from a function.


Public functions cannot accept certain data types as inputs or outputs

View and Pure Functions

• Getter functions can be declared view or pure.


• View function declares that no state will be changed.
• Pure function declares that no state variable will be changed or read.
Function Modifier

Modifiers are code that can be run before and / or after a function call.
Modifiers can be used to:
• Restrict access
• Validate inputs
• Guard against reentrancy hack
Events

Events allow logging to the Ethereum blockchain. Some use cases for
events are:
• Listening for events and updating user interface
• A cheap form of storage
Constructor

A constructor is an optional function that is executed upon


contract creation.
Inheritance

• Solidity supports multiple inheritance. Contracts can inherit other


contract by using the is keyword.
• Function that is going to be overridden by a child contract must be
declared as virtual.
• Function that is going to override a parent function must use the
keyword override.
• Order of inheritance is important.
• You have to list the parent contracts in the order from “most base-
like” to “most derived”.
Shadowing Inherited State Variables

Unlike functions, state variables cannot be overridden by re-declaring it


in the child contract.
Visibility

Functions and state variables have to declare whether they are accessible by other contracts.
Functions can be declared as
• public - any contract and account can call
• private - only inside the contract that defines the function
• internal- only inside contract that inherits an internal function
• external - only other contracts and accounts can call
State variables can be declared as public, private, or internal but not external.
Function Visibility Specifier in Solidity

Function in Solidity is a set of code that performs a specific task. The function
provides reusability of code in smart contracts. In Solidity, functions are defined
using the function keyword. The syntax of the function definition in Solidity is:

Function visibility in Solidity defines the visibility of the function to other functions
within the contract, or in other contracts. Function visibility helps to identify where in
the contract or in other contracts, functions can be used. It is specified by the developer
of the smart contract. The default variable visibility in Solidity is internal. The default
function visibility in Solidity is public.
How do Function Visibility Modifiers and Inheritance Work
Together?
Calling Parent Contracts

Parent contracts can be called directly, or by using the keyword super.


Interface

You can interact with other contracts by declaring


an Interface.
Interface
• cannot have any functions implemented
• can inherit from other interfaces
• all declared functions must be external
• cannot declare a constructor
• cannot declare state variables

You might also like