BCSE324L - FOUNDATIONS OF BLOCKCHAIN TECHNOLOGY
Module 3: SMART CONTRACTS
Dr. Senthil Prakash P.N.
Assistant Professor Senior Grade 1,
School of Computer Science and Engineering,
Vellore Institute of Technology,
Chennai – 600127
Smart Contracts
• Ethereum's core innovation in 2013 was to allow developers to write small chunks of code,
known as smart contracts, that could be deployed to the Ethereum blockchain network to
run independently in the network.
• The Ethereum Virtual Machine or EVM is the runtime environment for smart contracts in
Ethereum.
• In Ethereum, smart contracts are written in Solidity, a high-level programming language
designed to run on the Ethereum Virtual Machine.
• A smart contract is a program that defines a set of rules, or "contract" that automatically
executes the encoded rules when called by a user on the blockchain.
Smart Contracts
Ethereum Virtual Machine
Components of EVM
Anatomy of Smart Contracts
Anatomy of Smart Contracts
State:
• The smart contract state is the data owned by the smart contract and stored on the chain.
The state is a collection of key/value pairs. Each key and value are byte arrays of arbitrary
size.
• The smart contract also owns an account on the chain, stored as part of the chain state.
• The smart contract program can access its state and account through an interface layer
called the Sandbox. Only the smart contract program can change its data state and spend
from its account. Tokens can be sent to the smart contract account by any user through his
wallet or by another smart contract.
Anatomy of Smart Contracts
Entry Points:
• Each smart contract has a program with a collection of entry points. An entry point is a
function through which we can invoke the execution of the statements defined in it. There
are two types of entry points:
• Full entry points (or simply entry points): These functions can modify (mutate) the smart
contract's state.
• View entry points (or views): These are read-only functions and they are used only to
retrieve the information from the smart contract state. They cannot modify the state, i.e.,
they are read-only calls.
Anatomy of Smart Contracts
Function Modifiers:
Functions exist to get / set information based on calls initiated by external transactions. In
particular, a smart contract can never run unless initiated by an external transaction.
Access modifiers include:
• public: Can be accessed by all functions or callers
• external: Can be accessed only by external callers, not internal functions
• internal: Can be accessed only by this contract, or contracts deriving from it
• private: Can be accessed only from this contract
Anatomy of Smart Contracts
Function Modifiers:
Functions exist to get/set information based on calls initiated by external transactions. In
particular, a smart contract can never run unless initiated by an external transaction.
Other modifiers include:
• view: This guarantees that the function will not modify the state of the contract's data
(or data in storage).
• pure: This guarantees that the function with neither read nor modify the state of the
contract's data.
• payable: Functions declared payable can send and receive ether into their contracts.
Anatomy of Smart Contracts
Events:
• Events are a way to log and notify external entities (such as user interfaces or other smart
contracts) about specific occurrences within a smart contract. They serve as a mechanism
for emitting and recording data onto the blockchain, making it transparent and easily
accessible.
• While both functions and events accept arguments and can be called, functions modify
smart contracts directly while events have the role of informing services outside of the
blockchain to let users know that something has happened.
Anatomy of Smart Contracts
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract RealEstate{
function listPropertyForSale(uint pid, uint argprice, string argname) public{
struct Property{
Property memory newprop=
uint price;
Property({price:argprice, owner:[Link],name:argname,forsale:true});
address owner;
properties[pid]=newprop;
string name;
}
bool forsale;
}
mapping (uint=>Property) public properties;
Gas Fees in Ethereum
• Gas refers to the unit that measures the amount of computational effort required to execute
specific operations on the Ethereum network.
• Since each Ethereum transaction requires computational resources to execute, those
resources have to be paid for to ensure Ethereum is not vulnerable to spam and cannot get
stuck in infinite computational loops. Payment for computation is made in the form of a gas
fee.
Gas Fees = Gas Limit X (Base fee + Priority fee) EIP 1559
• Gas fees have to be paid in Ethereum's native currency, ether (ETH).
Gas Fees in Ethereum
Gas Fees = Gas Limit X (Base fee + Priority fee)
• Gas prices are usually quoted in gwei, which is a denomination of ETH.
• Each gwei is equal to one-billionth of an ETH (0.000000001 ETH or 10-9 ETH).
1 gwei = 0.000000001 ETH = 10-9 ETH
1 wei = 0.000000000000000001 ETH = 10-18 ETH = 10-9 gwei
For transferring 1 ETH from one account to another account,
Total fee = 21,000 * (10 + 2)
= 252,000 gwei (0.000252 ETH).
Gas Fees in Ethereum
Gas limit for different transactions
Life cycle of Smart Contract
• The life cycle of Smart Contracts in the Blockchain Ecosystem involves four Stages. Unlike a
blockchain’s lifecycle that begins with defining the issue, you want to solve with your
blockchain product and ends with a blockchain that resolves the issue, a smart contract on
the blockchain undergoes different phases.
Phases in the life cycle of smart
contract
Life cycle of Smart Contract
Create:
• Contract reiteration and negotiation constitute a significant part of the first phase. First, the
parties must agree on the contract’s overall content and goals. This can be done online or
offline.
• Once the contents of the smart contract have been finalized, they must be converted into
code. The following tasks are done in this phase:
➢Negotiation of multiple parties.
➢Smart contract’s design, implementation, and validation.
Life cycle of Smart Contract
Freeze:
• Validation of the transactions on a blockchain is done by a set of computers across the
network called nodes (miners). A small fee must be paid to the miners in exchange for this
service to keep the ecosystem from being flooded with smart contracts.
• The smart contract and its participants become open to the public on the public ledger
during the ‘freeze’ phase. Digital assets of both involved parties in the smart contracts are
locked via freezing the corresponding digital wallets.
• Nodes operate as a governance board that verifies whether the preconditions for smart
contract execution have been satisfied.
Life cycle of Smart Contract
Execute:
• Participating nodes read contracts that are stored on the distributed ledger. The integrity of
a smart contract is verified by the authenticating nodes, and the code is executed by the
smart contract’s interference engine (or by the compiler).
• The smart contract's execution generates a new set of transactions and a new state for the
smart contract.
• The set of findings and the new state information are entered into the distributed ledger
and verified using the consensus mechanism.
Life cycle of Smart Contract
Finalize:
• The resulting transactions and updated state information are put in the distributed ledger
and confirmed using the consensus process after the smart contract has been performed.
• The previously committed digital assets are transferred (assets are unfrozen), and the
contract is completed to confirm all transactions.
• The digital asserts of the involved parties are unfrozen, and the final state of the contract is
considered finalized.
Design Patterns of Smart Contract
• Smart contract design patterns are essential to building secure and efficient blockchain
applications. By following established design patterns, developers can ensure their smart
contracts are reliable, scalable, and easier to maintain.
• Using design patterns in your smart contract development offers several benefits:
➢Efficiency: Design patterns promote efficient code by providing tested solutions to
common problems.
➢Security: Patterns help avoid common vulnerabilities by following best practices.
➢Maintainability: Reusable patterns make your codebase more maintainable and easier
to understand.
➢Scalability: Patterns facilitate modular development, making it easier to scale our app.
Design Patterns of Smart Contract
• The following are the common smart contract design patterns:
➢ Factory Pattern
➢ Singleton Pattern
➢ State Machine Pattern
➢ Oracle Pattern
➢ Proxy Pattern
➢ Checks-Effects-Interactions
Design Patterns of Smart Contract
Factory Pattern:
• A smart contract that creates and deploys other smart contracts.
• If you want to create multiple instances of the same contract and you’re looking for a way to
keep track of them and make their management easier, this is a useful pattern.
• The disadvantage here is that any single address can only have at most have 1 instance
registered in the factory contract state, although all instances will continue to exist in the
blockchain and could eventually be tracked down.
Singleton Pattern:
• This design pattern ensures that an entity can only be instantiated once.
Design Patterns of Smart Contract
State Machine Pattern:
• A smart contract that represents a state machine with a finite set of states and transitions
between them. It’s valuable for contracts with complex state changes.
• Use the State Machine pattern when
➢ a smart contract has to transition several stages during its life cycle.
➢ functions of a smart contract should only be accessible during certain stages.
➢ stage transitions should be clearly defined and not preventable for all participants
Design Patterns of Smart Contract
Oracle Pattern:
• Contracts on the blockchain itself are not able to communicate with the outside world,
meaning they cannot pull information from sources like the internet.
• But for many contracts, information about external events is necessary to fulfill their core
purpose, especially since the industry is looking for more complex use cases.
• A smart contract that serves data from an external source.
• Use the Oracle pattern when
➢ rely on information that can not be provided from within the blockchain.
➢ trust the provider of the necessary information.
Design Patterns of Smart Contract
Proxy Pattern:
• A smart contract that allows upgrades and maintenance—within certain parameters—for
another one, without affecting its state and providing an interface for its access.
• Mutability in Ethereum is hard to achieve, but necessary. It allows developers to adapt to a
changing environment and to react to bugs and other errors. To overcome the limitations
introduced by the immutability of contract code, a contract can be split up into modules,
which are then virtually upgradeable.
• This is vital for maintaining a smart contracts functionality while fixing bugs or adding
features.
Design Patterns of Smart Contract
Check-Effects-Interactions Pattern:
• This design pattern determines the order in which certain types of statements must be
called within smart contract functions.
• The Ethereum Virtual Machine does not allow for concurrency. When calling an external
address, for example when transferring ether to another account, the calling contract is also
transferring the control flow to the external entity. This external entity is now in charge of
the control flow and can execute any inherent code, in case it is another contract.
• Use the Checks Effects Interactions pattern when
➢ it cannot be avoided to hand over control flow to an external entity.
➢ you want to guard your functions against re-entrancy attacks.
Design Patterns of Smart Contract
Re-entrancy attacks
Smart Contracts in Health Care
• India's healthcare industry is growing at a steady rate and it has reached around $372
Billion in 2022.
• Health care coordination becomes more complex as chronic conditions in the aging
population continue to rise. In many instances, the technology available to healthcare
providers is not adequate to capture all the aspects of the care being provided.
• The result is a rugged transfer of information between parties that ultimately reduces the
quality of care being provided to the patients.
• This is largely due to providers having legacy system, lack of integration with non-vendor-
specific technologies, paper based medical records.
Smart Contracts in Health Care
Payer – Provider – Patient Model:
Smart Contracts in Health Care
• Blockchain technology has the potential to transform health care, placing the patient
at the center of the health care ecosystem and increasing the security, privacy, and
interoperability of health data.
• This technology could provide a new model for health information exchanges (HIE)
by making electronic medical records more efficient, disintermediated, and secure.
Smart Contracts in Health Care
During Initial Patient visit
Smart Contracts in Health Care
Patient undergoing some lab testing ordered by physician
Smart Contracts in Health Care
Patient being referred to a specialist
Smart Contracts in Health Care
Hot Switching:
• Hot Switching is a design principle enabled by the blockchain to create networks where
components cab be swapped out, while the system as a whole is running with minimal
latency in operations.
• IT infrastructure in hospitals should have very stable minimum downtime but hot switching
can enable isolated system upgrades without disruptions and gradually transition from the
legacy systems that are still active to be compatible with the blockchain.
• Two early implementation of Hot Switching are lightning network and pluggable consensus.
Smart Contracts in Health Care
Physicians Credentialing:
• Credentialing is the process of organizing and verifying a physician’s professional records.
• Any physicians who joins an health care organization must have their credentials verified.
• Adoption of blockchain enables the credentialing to be maintained as canonical entity,
independent from a health care organization.
• When needed, a physician can simply update his association with a new hospital using
smart contract and this smart contract ensures the validation.
Dapps
All the best . . .