Chapter 3
Chapter 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
• Initiate a transaction
4
KEY CHARACTERISTICS
Characteristics Public Blockchain
Users Anonymous; but web tracking and cookies pose a risk to privacy
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
Ether
ETHEREUM Gas
14
COMPONENTS Transactions
Accounts
Ethash
MINER AND MINING NODE
• A miner is responsible for writing a transaction to the Ethereum series
• 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
16
MINER AND MINING 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
21
ETHER
• 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
23
ETHER
Growth of Ether
24
GAS
26
ACCOUNTS
• Accounts are primary building blocks for Ethereum ecosystem
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
• 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
• 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.
• 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
• 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
• 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
43
• Layers:
• 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.
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
48
WORKFLOW OF ETHEREUM
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
• Currently, there are six main implementations (clients) of the Ethereum protocol, written in six
different languages: 50
2. Geth, written in Go
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.
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.
• 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 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.
• 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
• 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.
• 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:
Use cases
• Developing and testing smart contracts locally before deploying them to the blockchain
• 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 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.
Features:
• Embark has a Web UI dashboard that gives an overview of all processes controlled by Embark.
Use Cases
• 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
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:
• 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.
Use Cases
• Creating and managing digital assets such as ERC-721, ERC-1155 and ERC-20 tokens
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
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 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.
Use Cases:
• 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.
• 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:
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
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
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
• Accuracy
• 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
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.
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:
• 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
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.
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:
• 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
External:
external functions are visible to public functions.
Can be called outside contract only.
PUBLIC
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{
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
139
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
• contract bytesprogram{
• contract test {
• 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{
revert("Revert error");
require(true==false,'Require error');
assert(true==false);
}
CASE STUDY ON VOTING CONTRACT