KEMBAR78
Chapter 3 | PDF | Constructor (Object Oriented Programming) | Programming
0% found this document useful (0 votes)
7 views161 pages

Chapter 3

The document provides an overview of public blockchains, specifically focusing on Ethereum, its architecture, components, and consensus mechanisms. It details the characteristics of public blockchains, the transition from proof-of-work to proof-of-stake in Ethereum, and the roles of miners, nodes, and various layers in the Ethereum ecosystem. Additionally, it explains the functionalities of Ether, gas fees, and the workflow involved in deploying smart contracts on the Ethereum platform.

Uploaded by

TANUSH BIDKAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views161 pages

Chapter 3

The document provides an overview of public blockchains, specifically focusing on Ethereum, its architecture, components, and consensus mechanisms. It details the characteristics of public blockchains, the transition from proof-of-work to proof-of-stake in Ethereum, and the roles of miners, nodes, and various layers in the Ethereum ecosystem. Additionally, it explains the functionalities of Ether, gas fees, and the workflow involved in deploying smart contracts on the Ethereum platform.

Uploaded by

TANUSH BIDKAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161

M O DUL E - 3

PUBL I C B L O CKCHAI N
PUBLIC BLOCKCHAIN
• Not owned by a single organization

• Application: Bitcoin
• Algorithms: Proof of Work, Proof of stake

2
Characteristics
• Anyone can download and add nodes to the system

• Fully Decentralized
PUBLIC BLOCKCHAIN

Nodes remain
The network is
anonymous through Details of users are
open and
cryptographic unknown
transparent to all
protocols
3

The network type is Security is based


decentralized and on consensus
has zero point of protocols and hash
failure functions
PUBLIC BLOCKCHAIN
• One does not need any permission to:
• Read/ Access a transaction

• Initiate a transaction

• Participate in the consensus process to create a block

4
KEY CHARACTERISTICS
Characteristics Public Blockchain

Users Anonymous; but web tracking and cookies pose a risk to privacy

Access Open and transparent to all

Network Type Decentralized; zero points of failure

Operation Anyone can read or initiate or receive transactions


5
Anyone can be a node and take part in the consensus process to
Verification
validate transactions and create a block
Immutability Secured by hashing

Organization Type Public

Security based on consensus protocols and hash functions, Higher the


Security
security, lower the performance
KEY CHARACTERISTICS

Characteristics Public Blockchain


Energy consumption very high
Limited ; as the network grows , the node requirements of bandwidth, storage
Scalability
and computational power exponentially increases
Incentivization Incentivizes miners to grow the network

Consensus Mechanism PoW, PoS


6
Trust Trust free system, trust is enforced via cryptographic proof

Transaction speed slow, takes about ten minutes for creating a block
BLOCKCHAIN L AY E R S
• Three different blockchain layers in blockchain helps to understand the
relationship between blockchain, cryptocurrency, protocols and tokens
• Layer 1: Technology Layer

• Layer 2: Protocol/Coin
7
• Layer 3: Token
BLOCKCHAIN L AY E R S
• Layer 1: Technology
• Blockchain is the technology behind various cryptocurrencies

• Layer 2: Protocol/Coin
• It defines the different coins and also describes the protocols of different currencies 8

• Protocol in blockchain defines various consensus mechanism, signature mechanisms, public key
usages, cryptography related rules.

• Layer 3: Token
• Tokens are the idea behind what people are building and serve as the symbol of underlying contract
ETHEREUM

9
ETHEREUM

10
ETHEREUM
• The first iteration of the Ethereum blockchain was used for running, hosting
smart contracts and proof-of-work mining

• The initial launch gave the opportunity to set up their mining apparatuses and
11
start building on the network.

• Since Ethereum’s initial launch, the blockchain has taken on many other
updates as part of the blockchain’s progression, such as updates called
Byzantium, Constantinople and the Beacon Chain.
ETHEREUM
• For example, Beacon Chain, launched the transition of the Ethereum blockchain
to Ethereum 2.0 (Eth2) — a shift from a proof-of-work (PoW) to a proof-of-stake
(PoS) consensus mechanism.

12
• Byzantium and Constantinople each brought a number of changes to the
Ethereum blockchain, including a mining payout reduction down to three ETH
from five (after Byzantium and preparation for the PoS transition during
Constantinople).
ETHEREUM
• A significant change to the Ethereum blockchain is the shift over to PoS initiated to
scale the blockchain.
• Numerous projects have built applications on the Ethereum blockchain over the
years. Still, the network struggled when traffic notably increased, such as the days of
CryptoKitties — digital collectible cats underpinned by the Ethereum blockchain in
2017.
• In 2020 and 2021, decentralized finance (DeFi) projects built on Ethereum received
significant attention, bringing Ethereum’s scalability issues to the forefront as high
network fees plagued participants.
• Ethereum’s transition to Eth2 and PoS aims to bring scalability to the well-known
blockchain, although the shift occurs in stages.
Miner and Mining Node

Ethereum Virtual Machine

Ether

ETHEREUM Gas
14
COMPONENTS Transactions

Accounts

Swarm and Whisper

Ethash
MINER AND MINING NODE
• A miner is responsible for writing a transaction to the Ethereum series

• Every miner needs to have a backup of these transactions

• Data is not stored directly on the blockchain.

• Data is stored in a distributed hash table like IPFS (Interplanetary File System)
15
• IPFS give back a hash or content address for all of the content and help to
retrieve the file easily from the data storage system
• Hash points of the data stored are in the blockchain
MINER AND MINING NODE
Two types of nodes:
• Mining Nodes and

• Ethereum Virtual Machines

16
MINER AND MINING NODE

• Generally there are no dedicated EVM nodes

• Instead all nodes function as miner node in addition to EVM node

• Mining nodes are part of the same network where EVM is hosted
17
• Each mining node maintains its version of Ethereum ledger

• Miners job is to ensure that their ledger is always upgraded with the latest
blocks
• EVM has a unique code attached to it called as Smart Contract
MINER AND MINING NODE

18
ETHEREUM VIRTUAL MACHINE

19
ETHEREUM VIRTUAL MACHINE (EVM)

• Those nodes which do not want to mine but functions as a support for the
implementation of the smart contracts are called as EVM
• By default the node utilizes port number 30303 to communicate among
themselves
• It does not need access to ledgers, however it contains only limited information 20
regarding the current transaction
• EVM additionally hosts the smart contracts

• Computation is accomplished via a stack based byte-code terminology


ETHER

21
ETHER

• It is a type of cryptocurrency used in Ethereum

• To set up a smart contract using the Ethereum platform, the contract author
needs to pay in the form of Ether
• 1 ETH is almost equal to 2681.52 USD (as on Septemeber 2024)
22
• Every task onto Ethereum that modifies its state costs Ether

• Miners who are successful in writing and generating new block at the chain are
rewarded with Ethers
• Ethereum comes with a metric system of denominations

• The smallest denomination is named as Wei


ETHER

23
ETHER
Growth of Ether

24
GAS

It is an internal currency of Ethereum

The execution and resource utilization costs are


predetermined in Ethereum in terms of Gas units
25

This is also known as the gas cost

Consumers need to pay the gas fees to


guarantee implementation of the transactions
TRANSACTIONS

• Ethereum stores transactions within blocks

• A contract is simply a set of agreements between parties

• Ethereum helps in executing a transaction

26
ACCOUNTS
• Accounts are primary building blocks for Ethereum ecosystem

• Two kinds of accounts are supported


• External Account
• Contract Account

27
ACCOUNTS
• Components of account
• Nonce
• Balance
• Storage Root
• Code Hash
28
ACCOUNTS
• Components of account
• Nonce:
• External Accounts: It is the number of transactions delivered out of that account
• Contract Accounts: It the number of transactions generated from this account

• Balance: Total balance of the accounts in Wei


• Storage Root: It has the main root node of Merkle Patricia Tree (used
in Ethereum)
• Code Hash:
• External Accounts: This field is not applicable. Code hash will have the empty
string
• Contract Accounts: It is the Hash code of EVM code of a particular account
ACCOUNTS

• Components of account
• Code Hash:
• External Accounts: This field is not applicable. Code hash will have the empty
string
• Contract Accounts: It is the Hash code of EVM code of a particular account
S WA R M A N D W H I S P E R
• Swarm is a peer to peer document sharing platform
• File records are divided into small chunks, dispersed and stored with volunteers
• Function: calculate, store, communicate
• The nodes which saves and also performs the functions on the small
chunks are all paid with ETH from people using the information 31

• Whisper is an encrypted messaging protocol that enable nodes to send out


messages directly to each other in a secure way that additionally hides the
sender and recipient identity from third party snoopers
ETHASH
• It is PoW algorithm that is modified variant of a precursor algorithm
called Dagger-Hashimoto
• Together with Ethash, the outcome in the hashing process has to
result in a hash value that is below a particular threshold
32
• This notion is called as Difficulty

• In case the rate at which blocks are found rises, the system will
automatically boost the difficulty
• This means that it will diminish the system threshold thereby reducing
the number of valid hashes with the capacity to be detected
ETHASH
• When the amount of exposed block declines, the system
threshold increases to create a higher number of hash values
which are available
• Ethash is predicted over a sizeable, randomly created data
33
collection termed as Directed Acyclic Graph (DAG)
• DAG is upgraded for every 30,000 blocks

• The DAG will be the last to rise while the blockchain grows
ETHASH

34
ETHASH
Steps of Ethash Algorithm

• A calculated seed is created using the block headers up to the point where mining
begins.
• This seed is then used to calculate and generate a 16 MB pseudorandom cache.

• This cache is then used to generate a data set of more than 4 GB (the DAG). This
data set is semi-permanent and is updated every 30,000 blocks. In this way, the
DAG varies for each "mining season".
ETHASH
Steps of Ethash Algorithm

• Once the DAG is generated, mining begins. This process takes random values from
the DAG and combines them using the data supplied by the network and the
transactions to be verified.
• Finally, verification is done with a process that regenerates specific parts of the
dataset using the cache memory, speeding up this process.
ETHASH
• This operation is the one currently running, and corresponds to version number 23
of the algorithm.
• Throughout the process the Keccak-256 and Keccak-512 functions are used, an
algorithm from which the SHA-3 standard was derived.

• Why so many revisions and changes?


These updates respond to problem resolutions, vulnerabilities, optimizations and
modifications to make work more complex for ASICs and more user-friendly. GPU, which is
where the Ethereum community usually makes its biggest mining life.
MINING IN ETHEREUM

• Mining Principle in Ethereum is different from that of a bitcoin

• All miners gather the transactions from the transaction pool

• The miner constructs a new block and adds all transactions to it

• Before adding the transactions, they are assessed to check if any tranaction is not yet written
within a block that is obtained from different miners 38

• If such transactions are detected then it is dropped

• The miner will then add his coin based tranaction to get the reward of mining the block

• The aim of miners will always be to build on the block header and perform the subsequent task
MINING IN ETHEREUM

39
CONTENTS OF A BLOCK HEADER

• Parent Hash (Previous block Hash): The miner identifies the hash of the previous block. The
last block will become the parent to the current block and its hash will be added to the block
header

• LogsBloom: It is a Bloom Filter (data structure) that consists of log information


40

• Transaction, state and receipt hash: All transactions, states and receipts are hashed and
Merkle Tree concept is applied. Ethereum saves three separate trees for all three items

• Nonce: It is a key to create a block in the blockchain database. It is a random number that can
be used just once in the cryptographic communication. Adding a nonce to a transaction identifier
makes it additionally unique thus reducing the chance of duplicate transaction
CONTENTS OF A BLOCK HEADER

• Timestamp (Current UNIX time): It changes every second. When the timestamp changes, the
data changes. When the data changes, its resultant also changes. The miner's computer should
keep incrementing the nonce until it finds the right one as per the algorithm. The computer needs
to generate millions of hashes per second to generate the one that will have the same number of
starting zeros as defined
41

• Ommer Block: It is a block whose parent corresponds to the current block's parent's parent.
Mined blocks that do not make it to the main chain are called as Orphaned Blocks. The aim of
Ommers is to help miners to add these Orphaned blocks significantly. The Ommers need to be
valid which means it should be within the sixth generation or smaller of the present block. After
six children, orphaned blocks can no longer be retrieved
CONTENTS OF A BLOCK HEADER

• MixHash: It is a hash which when together with all nonce demonstrates that a block has enough
computation. Miners generate a mixhash until the outcome is below the desired target hash.
After the output meets the condition, this nonce is deemed valid and the block may be added to
the blockchain series

42
• Difficulty: It decides the complexity of the challenge awarded to miners of a particular block.
The gas limit of the block decides the most gas allowed for the block. This supports in
ascertaining the no. of transactions that might be a part of the block

• Number: It refers to the sequential number of a block on the chain


ARCHITECTURE OF ETHEREUM

43
• Layers:

Layer 0: Consensus Layer


ARCHITECTURE Layer 1: Economic Layer 44
OF ETHEREUM Layer 2: Blockchain Services
Layer 3: Inter Operability
Layer 4: Browsers
Layer 5: DApps
ARCHITECTURE OF ETHEREUM
• Layer 0: Consensus Layer: Since there is no server, there is need for consensus

• Layer 1: Economic Layer: Tokens are used for encouraging each node either to do the
computation or perform storage operation (AWS or Google Cloud is used)

45
• Layer 2: Blockchain Services: Smart contracts are used for decentralized computations and
IPFS (interplanetary file system) is used for decentralized storage and content delivery
ARCHITECTURE OF ETHEREUM

• Layer 3: Interoperability: There is a need for a universal wrapper which acts around all
currencies.

 The exchange protocol helps in transfer and transmit of values between different tokens.

 It can be considered as a stack of decentralized APIs that uses the tokens.


46
 We can pay the top API with any token and in turn it pays to all other APIs and the
tokens
ARCHITECTURE OF ETHEREUM
• Layer 4: Browsers: It is used to access the decentralized applications.

 The mainstream browsers such as Chrome, Firefox, Opera would accept these decentralized
protocols natively

 Some browsers are made for decentralized applications like Mist, Omni Wallet and Maelstrom

47
• Layer 5: DApps: To build the DApps, applications level constructs are added

 These decentralized apps do not depend on any existing specific party

 A community of people share the ownership of some piece of the software


WORKFLOW OF ETHEREUM

48
WORKFLOW OF ETHEREUM

Solidity is the native coding language of Ethereum

It creates a .sol file as an outcome

To compile this file, Solidity Compiler (SOLC) is used


49

For deployment: Bytecode invokes Web3js

Once it is deployed, it returns the Contract and the Application Binary Interface (ABI)

When the contract is initiated, it can invoke contract methods and signs and pass them to
Ether to perform the Operation
• To run Ethereum:
WORKFLOW OF ETHEREUM
 Download the client and connect to the ethereal network

 The client is the gateway into the Ethereum network

 After connecting, we can run smart contracts, mine new blocks

• Currently, there are six main implementations (clients) of the Ethereum protocol, written in six
different languages: 50

1. Parity, written in Rust

2. Geth, written in Go

3. cpp-ethereum, written in C++

4. pyethereum, written in Python

5. Mantis, written in Scala

6. Harmony, written in Java


1. Download the
2. Write the solidity code
Ethereum Node

WORKFLOW
FOR 3. Compile it using a
4. Deploy the smart
contract code to the
framework like a truffle
DEPLOYING network

SMART
CONTRACTS
5. Call the deployed
contract using
Web3js (Web3js is the
front-end client that
speaks to the Ethereum
blockchain)
C O M PA R I S I O N O F B I T C O I N A N D E T H E R E U M
Similarities:

1. Both Bitcoin and Ethereum are based on the concept of a peer-driven network without a
central authority controlling the blockchain.

2. Both use a cryptographically secured public ledger which is used to validate and store
transactions that occur on the network.

3. Bitcoin and Ethereum both are highly secure crypto technologies.


52
4. Users of both Ethereum and Bitcoin can access their crypto tokens from a secure digital
wallet.

5. Both cryptocurrencies have seen a tremendous rise in value, leading to the question of
whether to invest in Ethereum vs Bitcoin for monetary gain.

6. Both bitcoins (BTC) and Ether (ETH) can be bought, sold, traded, or exchanged for goods as
a virtual currency.
C O M PA R I S I O N O F B I T C O I N A N D E T H E R E U M
Differences

1. The main difference between Bitcoin and Ethereum is in their overall applications. Bitcoin was
created to function solely as a digital currency and store of value, similar to currencies we use in
the real world. Ethereum has a much wider influence on the overall blockchain technology
landscape. While it can also be used as a cryptocurrency, like Bitcoin, it also has other uses for
developing business applications that are faster and more secure across various industries.
Ethereum is also continuously being updated, expanded, and reworked by the open-source
community.

2. Ether transactions are much faster than Bitcoin transactions and are completed in a matter of
seconds instead of minutes.

3. They use different encryption algorithms. Ethereum uses ethash while Bitcoin uses SHA-256.
BITCOIN VS ETHEREUM

54
TYPES OF TEST NETWORK USED IN ETHEREUM

• An Ethereum testnet is a collection of nodes that are used to test the Ethereum protocol.

• Tests are run on the testnets to ensure that the protocol is working as expected.

• Writing smart contracts and deploying them on the mainnet is a much more expensive operation
55
than writing tests and deploying them on the testnet. This is because we have to pay gas fees
before we can deploy our smart contracts on the mainnet, and these gas fees cost real money.

• Testnets provide free cryptocurrency we can use to pay for gas fees. Since this free
cryptocurrency has no value, we can’t use it in the mainnet.

• We should test our smart contracts on a testnet before deploying them on the mainnet.
TYPES OF TEST NETWORK USED IN ETHEREUM

• There are three testnets currently in use, and each behaves similarly to the production
blockchain (where your real Ether and tokens reside).

• Developers may have a personal preference or favorite testnet, and projects typically develop on
only one of them.
 Ropsten:
 A proof-of-work blockchain that most closely resembles Ethereum.
56
 We can easily mine faux-Ether.

 Kovan:
 A proof-of-authority blockchain, started by the Parity team.
 Ether can’t be mined; it has to be requested

 Rinkeby:
 A proof-of-authority blockchain, started by the Geth team.

 Ether can’t be mined; ; it has to be requested


ROOPSTEN

• Ropsten was created by the Ethereum Foundation

• The Ropsten testnet, is now deprecated. It is an Ethereum-based test blockchain used by


Ethereum developers to test protocol upgrades before deploying applications on the Ethereum
mainnet.

• Miners on the Ropsten test network had a financial incentive to maintain the testnet itself, given
its resemblance to the mainnet at the time. 57

• The testnet provided helpful information about certain issues faced on the mainnet, such as the
relationship between gas prices and uncle block rates.

• It was also useful for decentralized application development as Ropsten provided realistic back-
end and front-end performance tests.
K O VA N

• Kovan Testnet is a testing environment designed to help developers experiment with


decentralized applications (dApps) without having to use real ETH or interact with mainnet
Optimism or Ethereum.

• Kovan Testnet is deployed on the Ethereum and Optimism L2 networks and uses the same
technology as the main network, but with a few key differences.

• One of the main differences is that Kovan Testnet uses "test Ether" (KETH) instead of real Ether, 58
which can be freely obtained from various testnet faucet services.

• This allows developers to experiment with dApps and test various functionalities without worrying
about the financial risks associated with using real cryptocurrency.
RINKEBY

• It is a fork from the Ethereum mainnet and includes pre-authorized nodes, which help in avoiding
spam attacks alongside improving performance.
• Developers could use the Rinkeby faucet to obtain free ETH on the testnet for verifying the
functionalities of smart contracts without losing access to real financial assets.
• The free ETH available on Rinkeby testnet is worthless, and you cannot mine ETH in the testnet.
Only the authorized nodes could create new blocks, thereby implying that no other nodes could
receive mining rewards.
59
• Rinkeby testnet offers support for popular node clients, such as Geth, OpenEthereum, Besu and
Nethermind.
• It uses the Proof of Authority consensus mechanism. Rather than associating staking privileges
with monetary value, Proof of Authority allocates staking privileges according to validator’s
identity.
• The primary advantages of Proof of Authority include high performance alongside assurance of
fault tolerance. Presently, the Geth team maintains the Proof of Authority consensus protocol.
CONNECTING TO A TESTNET

• Ethereum addresses & private keys that work on Ethereum, work on each testnet

• Before proceeding, it is recommended to create a new wallet specifically for use on testnets;

60
T R A N S F E R I N G E T H E R S U S I N G M E TA M A S K

Connecting to a testnet

• Metamask is a browser plugin that hold an Ethereum wallet and connects the computer with the
Ethereum network.

• Metamask can connect and network with other providers who offer free ethers (i.e., test
ethers) to accounts created in wallets of Metamask.

• For instance, an account created in Metamask can be connected with an external network 61

named Ropsten Test Network, which can then inject free ethers (ETH) to a corresponding
account.
ETHEREUM FRAMEWORKS

• Smart contract development frameworks make engineers’ lives easier by allowing them to deploy
and test their smart contracts.

• The framework needs to:


• Deploy to a local blockchain
• Have quick and effective testing
62
• Deploy a smart contract, using Chainlink, to the Kovan Testnet.
ETHEREUM FRAMEWORKS

• Truffle — Most popular smart contract development, testing, and deployment framework. The Truffle
suite includes Truffle, Ganache, and Drizzle.
• Embark — Framework for DApp development

• OpenZeppelin — Provides a complete suite of security products and audit services to build, manage,
and inspect all aspects of software development and operations for decentralized applications.
• Waffle — Framework for advanced smart contract development and testing, small, flexible, fast (based
on ethers.js) 63
• Dapp — Framework for DApp development, successor to DApple

• Populus — The Ethereum development framework with the most cute animal pictures

• Etherlime — ethers.js based framework for Dapp deployment

• Parasol — Agile smart contract development environment with testing, INFURA deployment,
automatic contract documentation and more. It features a a flexible and unopinionated design with
unlimited customizability
• 0xcert — JavaScript framework for building decentralized applications
TRUFFLE

• Truffle is a widely used tool for developing and testing smart contracts on Ethereum.

• It offers a testing framework that simplifies the development process for Ethereum developers.
Truffle has three components: Truffle, Ganache, and Drizzle, and it supports JavaScript.

• Truffle is simple and user friendly with a lot of trusted users.

• To install Truffle you need to have Node, NPM and Python. You can install Truffle via NPM with
64
the command ‘npm install -g truffle
TRUFFLE

Features:

• Truffle provides better smart contract management.

• Automated contract testing is available

• Truffle supports package management.

• Truffle has an interactive console for effective communication. 65

• It offers tight integration with other Ethereum development tools.


TRUFFLE

Use cases

• Building and deploying smart contracts on the Ethereum blockchain

• Developing and testing smart contracts locally before deploying them to the blockchain

• Automating contract testing and deployment

• Managing and interacting with multiple development networks and testnets


66
• Creating and managing digital assets, such as tokens

• Building decentralized autonomous organizations (DAOs)


TRUFFLE
Advantages:

• Truffle is more popular than other frameworks such as Hardhat and has an active community
support.

• The migration feature of Truffle is similar to deploying, which makes it easier for developers to
deploy their contracts.

• Truffle uses web3.js, which is the first JavaScript API for Ethereum and is widely used.
67
• It has a beginner-friendly setup, which makes it easy for developers to get started.

• User-friendly interface with a comprehensive suite of developer tools, including smart contract
development, testing and debugging

• Write tests in Solidity, JavaScript and TypeScript and use Drizzle front-end libraries for dApp UI

• Layer 2 support - develop on EVM and JSON-RPC compatible blockchains such as Optimism,
Polygon, Arbitrum and Avalanche
TRUFFLE

Disadvantages:

• Truffle can be slower than Hardhat in some cases, which may affect the speed of the
development process.

• Testing and debugging in Truffle can be difficult compared to the Hardhat framework.

68
EMBARK

• Embark is a popular framework for developing decentralized applications. It streamlines the


development process by providing a set of tools and functionalities. Embark is not for smart
contract deployment and testing, but rather for front-end development and an end-to-end suite of
tools.

• Embark provides tools and libraries (web3.js, IPFS, EmbarkJS, Embark-testrpc) for developing,
69
launching and maintaining dApps.

• Additional features of Embark include automatic contract deployment and a user interface for
integration with other APIs.

• Embark is a sound choice for first time Ethereum dApp developers.


EMBARK

Features:

• With Embark, developers can build advanced decentralized applications.

• Embark has a Web UI dashboard that gives an overview of all processes controlled by Embark.

• Cockpit’s explorer can be used to review any smart contract easily.


70
• Embark has service monitoring and real-time deployment.
EMBARK

Use Cases

• Building and deploying smart contracts on the Ethereum blockchain

• Building front-end user interfaces for dApps using JavaScript frameworks such as AngularJS and
ReactJS
71
• Developing and testing smart contracts locally before deploying them to the blockchain

• Integrating dApps with web3 wallets and other blockchain-related tools

• Automating deployment and management of smart contracts and dApps.


EMBARK

Advantages:

• By using Embark, developers can manage various types of chains like private net, testnet, etc.

• Embark has a dashboard that tracks information such as the state of contracts.

• User-friendly interface. Comes with Cockpit - web-based tools to facilitate the development and
debugging of dApps
72
• Multiple libraries, storage and integration with IPFS, Whisper and Swarm

• Respected debugging and testing environment. Extensive plug-in customization options for full
dApp development
EMBARK

Disadvantages:

• Errors may occur while installing Embark.

• Steep learning curve

• Reliance on JavaScript

• Limited Github community and not as popular in web3 as other frameworks such as Truffle
73
OPENZEPPELIN

• OpenZeppelin is a secure framework that provides tools for writing, testing, and deploying
decentralized applications (dApps) on Ethereum. It offers built-in upgradable smart contracts and
uses Solidity programming language for developing smart contracts. The ERC20 library is also
included in OpenZeppelin, which makes it easier for developers to create token contracts that track
fungible tokens.

74

Features:

• OpenZeppelin focuses on security and provides top-notch security features for smart contracts.

• It has a modular approach and is an open-source platform with an active community of developers.

• OpenZeppelin has created standards like ERC20, which simplifies the process of creating token
contracts that track fungible tokens.

• It allows for editing and upgrading of contracts.


OPENZEPPELIN

Use Cases

• Building decentralized applications on Ethereum

• Creating and managing digital assets such as ERC-721, ERC-1155 and ERC-20 tokens

• Implementing smart contract security best practices

• Building decentralized autonomous organizations 75

• Creating and managing digital identities on the blockchain


OPENZEPPELIN

Advantages:

• OpenZeppelin provides upgradeable contracts, which enables developers to improve and update
their contracts as required.

• It provides high-end security, reliability, and risk management features for contracts.

• OpenZeppelin provides security inspection based on the developer’s request and applies
security precautions to verify whether the ‘dApp’ is secure or not. 76

• It offers implementation and suggestions after pinpointing possible errors in the code.

• OpenZeppelin starter kits are a great way to build your first dApp - reuse community vetted code,
upgrade and test smart contracts and create UI

• Widely used open source framework with an active GitHub community and documentation

• Extensive and trusted audit service - smart contracts will conform to established standards
OPENZEPPELIN

Disadvantages:

• The drawback of upgradeable contracts is the privileged role that is in charge of handling this
upgrade, which may raise security concerns.

• Reliance on Solidity

• Steep learning curve


77
• Needs to be used in conjunction with other frameworks such as Truffle and Embark for the
complete dApp development process
H A R D H AT

Hardhat is a JavaScript-based framework for developers to test, compile, deploy, and debug
decentralized applications based on the Ethereum blockchain. Hardhat uses the Ethers.js library to
interact with the Ethereum Blockchain and its ecosystem. Hardhat assists developers in managing
tasks inherent to developing decentralized applications and smart contracts. Hardhat has an in-built
Ethereum network designed for development and focuses on high-end debugging to provide
developers with the necessary tools to understand where the application fails.
78
H A R D H AT

Features:

• Hardhat has a flexible and customizable design.

• Ether is the default library for Hardhat.

• Hardhat can easily deploy contracts, run tests, and debug Solidity code.

• Hardhat is used for Solidity debugging, providing stack traces, console logs, and error 79
messages.

• Hardhat is designed for professionals.


H A R D H AT

Use Cases:

• Developing and testing smart contracts on a local development network

• Automating smart contract testing and deployment

• Debugging and troubleshooting smart contract issues

• Simulating and testing different network conditions, such as high network latency or low gas
80
prices

• Creating and managing multiple development networks for different stages of the development
process

• Interacting with smart contracts through a user-friendly command line interface (CLI)
H A R D H AT

Advantages:

• Hardhat is popular with over 15k users on GitHub, ensuring that community support is easily
available.

• Hardhat provides console.log for faster debugging.

• Hardhat allows users to build their scripts and plugins.


81
• Hardhat supports typescript.

• Intuitive debugging and testing environment. Developers get stack traces, console.log and
explicit error messages when transactions fail

• Test and deploy dApps via JavaScript, Rust and TypeScript integration

• Active community and trusted by some of the biggest names in web3 - Yearn, Uniswap,
Decentraland, Chainlink
H A R D H AT

Disadvantages:

• Limited documentation for experienced developers, with a focus primarily on beginners.

• Steep learning curve and limited documentation compared to Truffle

• Limited support for front-end frameworks for dApp UI design

• Designed more for experienced web3 dApp developers


82
SMART CONTRACTS
SMART CONTRACTS: SIMPLE TO COMPLEX

Distributed
Smart Right Multi-party Distributed Distributed Distributed
Digital Value Basic Smart Autonomous
and Smart Autonomous Autonomous Autonomous
Exchange Contract Business
Obligation Contract Organization Government Society
Units

Different
Unit of a Self-driving state govt. Group of
corporation trucks make Code their settlers from
Consumer
Sending of issues its point-to- own self different
buys digital Agreement Seller lends
bitcoins own bonds point enforcing areas
content between buyer funds
between and buyers deliveries, governance establish
stream from Landlord to buy a
family monitor pay local toll services and self-
a common and Tenant house
members payments and buy local create enforcing
platform
via shared gas for the their own trade
ledger truck revenue agreements
streams

Simple
Complex
Based on the applications:

TYPES OF
SMART
CONTRACTS
• Smart contracts with various legal contract
templates

• They just execute the contracts as per the


templates used
SMART
LEGAL
CONTRACT
S
• Run on P2P networks

• Unlimited number of participants from the market

DAPPS
(DECENTRA • Blockchain enabled websites
LIZED
A P P L I C AT I O
NS) • Covers from end to end (both front end and
back end)
• It is an organization represented by logic
encoded as a transparent program controlled by
DAO shareholders and not influenced by a central
(DISTRIBUT authority
ED
AUTONOMO
• The financial transaction records and program
US
O R G A N I Z AT logic are maintained on a blockchain
ION)
• Use of blockchain to manage and access data
from IoT devices leads to better security

• Due to decentralized authority, single point


failure cannot happen
SMART
CONTRACTI
NG
DEVICES
• All contract could consist of :
State Variables
Functions
STRUCTURE Function Modifiers
OF A SMART
Events
CONTRACT
Struct Types
Enum Types.

• We can use other contracts using inheritance.


• State Variables: State variables are stored in
contract storage.
S TAT E
VA R I A B L E S
• Functions are like a few lines of code that can
F U N C T I O N perform
S something within the contract.
• Function modifiers are like a function that checks
FUNCTION
the validation rules before executing the main
MODIFIER
S function.
• Struct is custom defined data types that consists
of several variables declared in it.
STRUCT
TYPES
• Events are functions that rises up after
EVENTS compilation of function execution if event code
written there
• Enum is used to create custom types and it has fix
ENUMS the set of values
For Deployment

SMART
USING ANY TEST USING GETH AND USING SMART CONTRACT
NETWORK, METAMASK SOLIDITY COMPILER ON IN DAPP CONTRACT
AND REMIX TEST-NETWORKS
APPROACH
ES
BENEFITS OF SMART CONTRACTS

• Speed and real-time updates

• Accuracy

• Lower execution risk

• Fewer intermediaries

• Lower cost
L I M I TAT I O N S O F S M A R T C O N T R A C T S

Difficult to Possibility
Third party
change of loopholes
BASIC SOLIDITY PROGRAM

pragma solidity >=0.7.0 <0.9.0;


contract BasicProgram{
string public s1= "Blockchain";
100

To see the output:


Compile->Deploy->Deployed Contracts->click on s1
Output: 0:string: Blockchain
CONSTRUCTOR
• 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


101
defined constructor.

pragma solidity ^0.8.16;


contract Constructorprog{
string public name;
CONSTRUCTOR

102
In Solidity a function is generally defined by using the function
keyword, followed by the name of the function which is unique
and does not match with any of the reserved keywords.

A function can also have a list of parameters containing the


name and data type of the parameter.

The return value of a function is optional but in solidity, the


return type of the function is defined at the time of declaration.

FUNCTI
To invoke a function somewhere later in the Contract,we need to
ONS
write the name of that function
103
FUNCTIONS

104
PURE FUNCTIONS
• A function that doesn’t read or modify the variables of the state is called a pure
function.

•It can only use local variables that are declared in the function and the arguments
that are passed to the function to compute or return a value.

105
PURE FUNCTIONS
•If the pure function is doing any of the following, the compiler will consider them as
reading state variables and will throw a warning:

•Reading state variables


•Accessing balance or address
•Invoking a function that is not pure
•Accessing a global variable, message, or block 106
•Using certain opcodes in inline assembly
PURE FUNCTIONS
•If the pure function is doing any of the following, the compiler will consider them as
modifying state variables and will throw a warning.

•Modifying or over-writing state variables


•Creating new contracts
•Invoking a function that is not pure or view
•Emitting events 107
•Using certain opcodes in inline assembly
•Using selfdestruct
•Using low-level function calls
•Sending Ether along with function calls
F U N C T I O N S - PA R A M E T E R S
pragma solidity ^0.8.16;
contract funparam{
function subtract(int a, int b)
public pure returns(int)
{
return a-b;
} 108
function mod(int a, int b) public
pure returns(int)
{
return a%b;
}
}
VIEW FUNCTIONS
 View functions ensure that they will not modify the state.

 A function can be declared as view.


• Modifying state variables.
• Emitting events.
• Creating other contracts.
• Using selfdestruct. 109
• Sending Ether via calls.
• Calling any function which is not marked view or pure.
• Using low-level calls.
• Using inline assembly containing certain opcodes.
VIEW FUNCTIONS
pragma solidity ^0.8.0;
contract viewfunc1 {
// declare a state variable
uint number1 = 10;

// creating a view function


// it returns sum of two numbers that are passed
110
as parameter
// and the state variable number1
function getSum(uint number2, uint number3)
public view returns(uint) {
uint sum = number1 + number2 + number3;
return sum;
}
}
VISIBILITY QUALIFIERS
• Public: - public functions are visible from internal and external contracts. - Can
be called inside a contract or outside contract - Default is public - It is visible to
public, so security concern.

• Private: - private functions are visible inside the same contract - Can be called
inside a contract, Not able to call from an outside contract

• Internal: - Similar to private functions, and visible to contract hierarchy - Can be 111
called inside a contract and Contracts that inherit from it.

• External:
• external functions are visible to public functions.
• Can be called outside contract only.
BASIC SOLIDITY PROGRAM

pragma solidity >=0.7.0 <0.9.0;


contract BasicProgram{
string public s1= "Blockchain";
112

To see the output:


Compile->Deploy->Deployed Contracts->click on s1
Output: 0:string: Blockchain
CONSTRUCTOR
• 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


113
defined constructor.

pragma solidity ^0.8.16;


contract Constructorprog{
string public name;
CONSTRUCTOR

114
In Solidity a function is generally defined by using the function
keyword, followed by the name of the function which is unique
and does not match with any of the reserved keywords.

A function can also have a list of parameters containing the


name and data type of the parameter.

The return value of a function is optional but in solidity, the


return type of the function is defined at the time of declaration.

FUNCTI
To invoke a function somewhere later in the Contract,we need to
ONS
write the name of that function
115
FUNCTIONS

116
PURE FUNCTIONS
• A function that doesn’t read or modify the variables of the state is called a pure
function.

•It can only use local variables that are declared in the function and the arguments
that are passed to the function to compute or return a value.

117
PURE FUNCTIONS
•If the pure function is doing any of the following, the compiler will consider them as
reading state variables and will throw a warning:

•Reading state variables


•Accessing balance or address
•Invoking a function that is not pure
•Accessing a global variable, message, or block 118
•Using certain opcodes in inline assembly
PURE FUNCTIONS
•If the pure function is doing any of the following, the compiler will consider them as
modifying state variables and will throw a warning.

•Modifying or over-writing state variables


•Creating new contracts
•Invoking a function that is not pure or view
•Emitting events 119
•Using certain opcodes in inline assembly
•Using selfdestruct
•Using low-level function calls
•Sending Ether along with function calls
F U N C T I O N S - PA R A M E T E R S
pragma solidity ^0.8.16;
contract funparam{
function subtract(int a, int b)
public pure returns(int)
{
return a-b;
} 120
function mod(int a, int b) public
pure returns(int)
{
return a%b;
}
}
VIEW FUNCTIONS
 View functions ensure that they will not modify the state.

 A function can be declared as view.


• Modifying state variables.
• Emitting events.
• Creating other contracts.
• Using selfdestruct. 121
• Sending Ether via calls.
• Calling any function which is not marked view or pure.
• Using low-level calls.
• Using inline assembly containing certain opcodes.
VIEW FUNCTIONS
pragma solidity ^0.8.0;
contract viewfunc1 {
// declare a state variable
uint number1 = 10;

// creating a view function


// it returns sum of two numbers that are passed
122
as parameter
// and the state variable number1
function getSum(uint number2, uint number3)
public view returns(uint) {
uint sum = number1 + number2 + number3;
return sum;
}
}
VISIBILITY QUALIFIERS
• Public: - public functions are visible from internal and external contracts. - Can
be called inside a contract or outside contract - Default is public - It is visible to
public, so security concern.

• Private: - private functions are visible inside the same contract - Can be called
inside a contract, Not able to call from an outside contract

• Internal: - Similar to private functions, and visible to contract hierarchy - Can be 123
called inside a contract and Contracts that inherit from it.

• External:
• external functions are visible to public functions.
• Can be called outside contract only.
VISIBILITY QUALIFIERS

 Public: - public functions are visible from internal and external contracts. - Can
be called inside a contract or outside contract - Default is public - It is visible to
public, so security concern.

 Private: - private functions are visible inside the same contract - Can be
called inside a contract, Not able to call from an outside contract
124

 Internal: - Similar to private functions, and visible to contract hierarchy - Can


be called inside a contract and Contracts that inherit from it.

 External:
 external functions are visible to public functions.
 Can be called outside contract only.
PUBLIC

pragma solidity ^0.8.16;


contract funparam{
function subtract(int a, int b)
public pure returns(int)
{
return a-b;
} 125
function mod(int a, int b) public
pure returns(int)
{
return a%b;
}
}
P R I VAT E

pragma solidity ^0.8.16;


contract privfunc{
function result1(int a, int b) private pure
returns(int)
{
return a+b;
} 126
function result2(int a, int b) public pure
returns(int)
{
return a-b;
}
}
INTERNAL

pragma solidity ^0.8.16;


contract internalfunc{
function result1(int a, int b) internal pure returns(int)
{
return a+b; 127
}
}
EXTERNAL
pragma solidity ^0.8.16;
contract externalfunc{
function res1(int a, int b) internal pure returns(int)
{
return a+b;
}
function res2(int a, int b) external pure returns(int)
{ 128
return a-b;
}
}
DIFFERENCES
PUBLIC PRIVATE INTERNAL EXTERNAL

They are part of the They are only visible Those functions and They are part of the
contract interface and for the contract they are state variables can only contract interface i.e.
can be either called defined in and not in be accessed internally they can be called from
internally or via derived contracts. i.e. from within the other contracts and via
messages. current contract or transactions 129
contracts deriving from
it
ACTIVITY QUALIFIERS

Constant: - Can only read state variables and return back to the caller but can't
modify any variable. It can invoke an event, create another contract and call
other functions
130

View:- It indicates that a function will not modify the storage state in any way

Pure:- It can neither make changes to state variables nor read them. It can't make
any calculations that use any state variables as its components

Payable: - It can accept Ether from a caller. The call will fail in case Ether is not
provided by a sender.
A D D R E S S A N D A D D R E S S PAYA B L E

131
ADDRESS
pragma solidity ^0.8.16;
contract addrs{
string role;
uint public age;
address owner;
constructor() public{ 132

role="trainer";
age=25;
owner=msg.sender;
}
function getrole() public view returns (string memory){
return role;
}
ADDRESS
• Before changing role After changing role

133
A D D R E S S PAYA B L E
pragma solidity ^0.8.16; function buyTickets(uint amount)
// without fallback public payable{

contract if (msg.value !=(amount*price)||


amount > tickets){
addrspaybl{
revert();

address payable owner; }


purchasers[msg.sender] =
uint public tickets; purchasers[msg.sender]+amount;
134
uint constant price=1 ether; tickets-=amount;
mapping (address=> uint) public if(tickets==0)
purchasers;
{
constructor() public{ selfdestruct(owner);
owner=msg.sender; }
tickets=5; }
} }
function() external payable{
A D D R E S S PAYA B L E
pragma solidity ^0.8.16; function buyTickets(uint amount) public payable{
// with fallback if (msg.value !=(amount*price)|| amount >
contract addrspaybl{ tickets){
address payable owner; revert();

uint public tickets; }

uint constant price=1 ether; purchasers[msg.sender] =


purchasers[msg.sender]+amount;
mapping (address=> uint) public purchasers; tickets-=amount; 135
constructor() public{ if(tickets==0)
owner=payable(msg.sender); {
tickets=5; selfdestruct(owner);
} }
fallback() external payable{ }
buyTickets(1); }
}
A D D R E S S PAYA B L E
• Before Deploying do not set any VALUE (by default it is 0)

136
A D D R E S S PAYA B L E
• VALUE=0 click on buyTickets, amount=1, click on transact

137
A D D R E S S PAYA B L E
• VALUE=1 click on buyTickets, amount=1, click on transact,

138

click on tickets

VALUE BECOMES =0 and Tickets=4


A D D R E S S PAYA B L E
• VALUE=0 click on buyTickets, amount=1, click on transact,

139

Set some ether VALUE


A D D R E S S PAYA B L E
• VALUE=5 click on buyTickets, amount=5, click on transact,

140
A D D R E S S PAYA B L E
• VALUE=4 click on buyTickets, amount=4, click on transact,

141
• Bytes: 8 bit signed integers

• The byteBdata
Y T Etype
S AisNused
D EtoNstore
U M Sdata in binary format
BYTES

• pragma solidity ^0.8.7;

• contract bytesprogram{

• bytes1 public a="z";


• }
ENUMS

 Techniques to create user defined Data Types

 Used to provide names for integral constant


ENUMS
• pragma solidity ^0.8.16;

• contract test {

• enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }


• FreshJuiceSize choice;
• FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;

function setLarge() public {


• choice = FreshJuiceSize.LARGE;
• }
• function getChoice() public view returns (FreshJuiceSize) {
• return choice;
• }
• function getDefaultChoice() public pure returns (uint) {
A R R AY S : F I X E D A N D D Y N A M I C

Fixed-size: Size is known in advance

Dynamic: Size is not known in advance


F I X E D - S I Z E A R R AY

pragma solidity ^0.8.7;


contract fixarr1{
uint[4] data1_fixed_size;
function addelements() public
returns(
int[3] memory, uint[4]
memory){
int[3] memory
data=[int(200), 150, -10];
data1_fixed_size=[uint(100)
,101,201,99];
return (data,
data1_fixed_size);
}
}
D Y N A M I C - S I Z E A R R AY

pragma solidity ^0.8.7;


contract dynamicarr1{
uint[] data=[11, 99, 500];
int[] data1_dynamic_arr;
function addelements() public
returns(
uint[] memory, int[]
memory){
data1_dynamic_arr=[i
nt(-100),101,201,99,407];
return (data,
data1_dynamic_arr);
}
}
S P E C I A L D Y N A M I C - S I Z E A R R AY

 Bytes array: It can hold any number of bytes


 String array: It is dynamic array of UTF-8 data (variable-
width character encoding)
 Struct: Define own datatype by creating a struct
LENGTH OF A STRING
pragma solidity ^0.8.7;
contract lenofstring {
function find_length(string memory s)
public pure returns ( uint256) {
return bytes(s).length;
}
}
I N H E R I TA N C E

• It is a method of extending a program’s functionality by separating the code, reducing


dependency and increasing the re-usability of existing code
I N H E R I TA N C E

• Single

• Multilevel
I N H E R I TA N C E

• Hierarchical

• Multiple
pragma solidity ^0.8.7;
contract concert{
address payable owner;
uint public tickets;
uint constant price=1 ether;
mapping(adrees => uint) public purchasers;
constructor(uint t) public{
owner=msg.sender;
tickets=t;
}
function() external payble{
butTickets(1);
}
function() buyTickets(uint amount) public payable{
if (msg.value!=(amount*price)) || amount > tickets} {
revert();
}
purchasers[msg.sender]+=amount;
tickets-=amount;
if (tickets==0){
selfdestruct(owner);
}
}
function website() public returns (string memory);
interface Refundable{
function refund(uint numTickets) external returns (bool);
}
contract AbstractConcert is concert(10), Refundable{
function refund(uint numTickets) public returns (bool){
if (purchasers[msg.sender] < numTickets) {
return False;
}
msg.sender.transfer(numTickets*price);
purchasers[msg.sender]-=numTickets;
tickets+=numTickets;
return true;
}
function website() public returns (string memory){
return "http://AbstractConcert.com"
}
}
ERROR HANDLING

• Errors can happen if it is triggered due to failure in business logic with one of the
keywords
pragma solidity ^0.8.7;

contract errorprogram1{

function TestRevert() pure external{

revert("Revert error");

function TestRequire() pure external{

require(true==false,'Require error');

function TestAssert() pure external{

assert(true==false);

}
CASE STUDY ON VOTING CONTRACT

You might also like