SlideShare a Scribd company logo
1 of 52
ZeroLAB
ZeroLab
Blockchain Solution Designer Course
in collaboration with Bocconi University
Part 4 of 6
ZeroLAB
ZeroLAB
Welcome back!
In the last session, we got to know more about smart contract – a
powerful component which help blockchain become programmable.
We hope you have had a good learning experiences so far!
In this session, we will learn about another powerful and crucial
component of blockchain technology which ensures blockchain
network function as it is expected. The component is consensus
protocol.
INTRO
ZeroLAB
Consensus
Protocol
> A deep dive into the backbone of the blockchain
technology
By Dr. Alessio Bonti & Jason Pham
ZeroLAB
• Introduction
• Definition
• Consensus protocols
• Controversy & conclusion
AGENDA
ZeroLAB
Introduction
How can blockchain be owned and governed
by everyone?
ZeroLAB
ZeroLAB
As we learned in lesson 1
and 2, blockchain network
is decentralized and that is
why people want it.
Consensus protocol was
said to help the blockchain
network secure and
moving forward. And,
blockchain is owned and
governed by everyone
LESSON REWIND
Decen-
tralization
Trustless
Environment
Data
Availability &
Integrity
Network
Persistance
Optimized
Resource
Accessibility
ZeroLAB
ZeroLAB
Blockchain nodes run in
decentralized manners. Thus,
there is no central entity
ensuring network
consistency and security.
But the absence of a central
party is preferable as it
provides transparency and
lack of ownership, meaning
data is accessible, verifiable
and auditable to everyone.
THE NEED
However, there must be something
that:
▪ Controls the decentralized system
to make sure “bad nodes” cannot
manipulate it.
▪ Ensures the blockchain network is
functional even there are some
faults or malicious actions that may
compromise it. This is called fault-
tolerant.
▪ Decides what is true. Any updates
of on-chain data need to be
validated.
ZeroLAB
ZeroLAB
The term consensus, in
computer science, was
defined before the
introduction of blockchain.
Its utilization was mainly
mentioned in distributed
systems where participants
need to agree on one
single state for the entire
system. This is referred to as
“reaching consensus”.
THE CONSENSUS
ZeroLAB
ZeroLAB
Consensus is placed at the
core of blockchain system.
In blockchain, it is referred
to as the mechanism
ensuring the common
state of the system is
correctly derived by all
nodes and decentralization
is maintained.
BLOCKCHAIN CONSENSUS
ZeroLAB
ZeroLAB
Blockchain consensus usually
functions based on incentive
and punishment scheme. In
other words, blockchain system
rewards honest behaviours,
which keep the system secure
and consistent, and punish
those with malicious ambition
to manipulate the system state.
In short, blockchain consensus
implements “strict rules
without rulers”.
BLOCKCHAIN CONSENSUS
ZeroLAB
Some prominent
consensus
protocols
ZeroLAB
ZeroLAB
As the blockchain technology is thriving to
make enormous impacts. Multiple types
consensus protocols were introduced. The
principles of any consensus protocols
can be comprehended by answering the
following questions:
▪ Who can change the past, and how can
the past be changed?
▪ Who can change the future, and how
can the future be changed?
▪ What cost has to be paid for making
changes?
▪ How decentralized is the power to
make changes?
▪ Who and how will know if something
has changed?
CONSENSUS PROTOCOLS
ZeroLAB
ZeroLAB
The proof of work (PoW) was created for the original
blockchain Bitcoin as a consensus algorithm. PoW is an
important part of Bitcoin to stabilize the difficulties for
mining.
Mining is a process which requires nodes to solve a
“cryptographic puzzle” to derive a block. In PoW, the
reward for discovering a legitimate block is a certain
amount of cryptocurrency (e.g., bitcoins, ethers). In
contrary, miners will lose the money for a huge amount
of electricity they invested in solving the cryptographic
puzzle, if they propose a “sketchy block”.
PROOF OF WORK (PoW)
ZeroLAB
ZeroLAB
PROOF OF WORK (PoW)
Pros
▪ Security
▪ Decentralization
▪ Double spending prevention
Cons
▪ Excessive energy consumption.
▪ Low transaction speed.
Bitcoin and Ethereum are the
biggest blockchains using PoW.
Miners
Block
Crypto-
graphic
puzzle
Proof of Work
Broadcast new
block
Verified block
Restart
Transaction
ZeroLAB
ZeroLAB
The proof of stake (PoS) was proposed as the successor
of PoW to solve the problems that are known in PoW. A
core difference in PoS is that nodes do not have to do
mining, they need to stake and attest instead.
Staking is the process when a node nominate itself as
validator in the PoS protocol by depositing a certain
amount of cryptocurrency via a special transaction.
Attesting is referred to as the action that the validators
take to decide whether a block is valid.
PROOF OF STAKE (PoS)
ZeroLAB
ZeroLAB
▪ The blockchain maintains a list of validators.
▪ Any users who deposit some ether can self nominate as a
validator by staking.
▪ Validators are randomly appointed to propose and attest
on the next valid block.
▪ Each validator’s vote is weighted by its stake.
▪ A validator may lose deposit when staking on rejected
block.
▪ A validator may also gain reward for proposing and
staking on block that is accepted by the majority.
PROOF OF STAKE (PoS)
Pros
▪ Energy saving
▪ Higher transaction speed
▪ Higher finality
Cons
▪ Less security
▪ Less decentralization
Algorand, Tezos and Polkadot are
examples of blockchains using PoS
https://developer.algorand.org/docs/get-
started/basics/why_algorand/#proof-of-stake-versus-proof-
of-work
ZeroLAB
ZeroLAB
There are still more consensus
protocols in the industry:
▪ Proof of Authority
▪ Proof of Elapsed Time
▪ Proof of Capacity
▪ Byzantine Fault Tolerant Protocol
▪ And more…
Those protocols were not
elaborated because either they are
not widely adopted, or they are
not used in public blockchain.
CONSENSUS PROTOCOLS
ZeroLAB
ZeroLAB
There is no one-solution-fits-all
consensus algorithm, at least
for the moment. There are
always trade-offs whether it is
security, cost, decentralization
or finality.
Therefore, the answer to
which consensus algorithm
is “better” lies under your
needs, your goals and your
solution.
CONTROVERSY & CONCLUSION
ZeroLAB
Time to build
Our exploration about consensus protocol is over, it is
time for practical activities.
ZeroLAB
ZeroLAB
We already made it through
two thirds of the journey!
Let’s keep it going.
This practical session will
show you how to write,
deploy and test a smart
contract.
PRACTICAL JOURNEY
Topics
1. Create and fund your account
with testnet funds.
2. Setup your development
environment.
3. Connect account to a Dapp.
4. Write a simple smart contract,
deploy and test.
5. Upload images to IPFS through a
Dapp.
6. Create NFT on the Dapp and
transfer using your wallet.
ZeroLAB
Practical 4
Write, deploy and test a simple smart contract
ZeroLAB
ZeroLAB
Clone the
pyteal-prac
repo into the
zerolab-prac
folder by
running the
following
commands
CLONE PYTEAL-PRAC
// Change directory to zerolab-prac
cd zerolab-prac
// Check directory content
ls
// Remove pyteal-prac directory if there is one
rm –rf pyteal-prac
// Clone the pyteal-prac repo
git clone https://github.com/jasonhtpham/pyteal-
prac.git
// Change directory to pyteal-prac
cd pyteal-prac
ZeroLAB
ZeroLAB
Check the
content of the
cloned repo
and launch
VS Code to
edit the
smart
contracts
code
LAUNCH VS CODE
// Check directory content
ls
// Launch VS Code with the current directory
code .
ZeroLAB
ZeroLAB
In Algorand smart contracts:
▪ The ApprovalProgram is responsible for
processing all application calls to the contract.
This program is responsible for implementing
most of the logic of an application.
▪ The ClearStateProgram is used to handle
accounts using the clear call to remove the smart
contract from their balance record. This program
will pass or fail the same way the
ApprovalProgram does.
APPROVAL AND CLEARSTATE PROGRAM IN ALGORAND
ZeroLAB
ZeroLAB
UPDATE SMART CONTRACT CODE
Update the simple_approval.py file to build a set_number smart contract
ZeroLAB
ZeroLAB
This piece of
code tells the
smart
contract to
run the
on_create
sequence
when it is
initialized.
UPDATE SC CODE
# TODO1: The function to call when the smart contract is
initialized
[Txn.application_id() == Int(0), on_create],
ZeroLAB
ZeroLAB
This piece of
code defines
the on_create
sequence
that set 0 as
the initial
value of the
“number”
global state.
UPDATE SC CODE
# TODO2: This sequence will be executed when the smart
contract is initialized.
on_create = Seq([
App.globalPut(Bytes("number"), Int(0)),
Return(Int(1)),
])
ZeroLAB
ZeroLAB
This piece of
code takes the
first
transaction
argument as
the name of
the sequence
called by the
users.
If the user asks
for the
“set_number”,
then executes
the
set_number
sequence
UPDATE VS CODE
# TODO3: Determine which function to call based on the
transaction argument
called_function = Txn.application_args[0]
# TODO3: Based on called_function, call the relevant
function
handle_noop = Cond(
[called_function == Bytes("set_number"),
set_number]
)
ZeroLAB
ZeroLAB
This piece of
code defines
the
set_number
sequence that
set the second
transaction
argument
passed by the
user as the
new value of
the “number”
global state.
UPDATE SC CODE
# TODO4: The sequence to set the global variable number
to provided value
set_number = Seq([
# Take the 2nd transaction argument and store it in
the "number" global variable
App.globalPut(Bytes("number"),
Btoi(Txn.application_args[1])),
Return(Int(1)),
])
ZeroLAB
ZeroLAB
simple_clear.py
file which, in
this case, does
not have any
logic as we do
not have to
worry about
this part.
CLEAR STATE
from pyteal import *
def clear_state_program():
program = Seq([
Return(Int(1))
])
return program
with open("simple_clear.teal", "w") as f:
compiled = compileTeal(clear_state_program(),
mode=Mode.Application, version=2)
f.write(compiled)
ZeroLAB
ZeroLAB
Install the
pyteal
module to
compile the
smart
contract. In
the VS Code
terminal, run
the following
commands.
COMPILE SC
// Install pip, type ‘y’ and hit ‘Enter’ when
prompted
sudo apt install python3-pip
// Install pyteal module
pip install pyteal
// Compile smart contract
python3 simple_approval.py
ZeroLAB
ZeroLAB
COMPILE SC
After compiling, we will have simple_approval.teal and simple_clear.teal
files created. We will use these files to deploy the smart contract.
ZeroLAB
ZeroLAB
Now, we start
the sandbox
to get us
ready to
deploy the
compiled
smart
contract. This
may take 5 –
10 minutes.
START SANDBOX
// Change directory to sandbox/
cd ../sandbox/
// Start the sandbox (this may take a few minutes)
./sandbox up testnet -v
ZeroLAB
ZeroLAB
After the
sandbox is up
and running,
we create a
test wallet and
import our
account from
the Pera Algo
Wallet by
providing your
Account 1’s 25
words
mnemonic
IMPORT ACCOUNT
// Go inside the algod container
./sandbox enter algod
// Change directory to data/
cd /data
// Create a new wallet called test
goal wallet new test
// Import our Account 1 from Pera Algo Wallet
goal account import
If you did not save your 25 words mnemonic, open Pera Algo Wallet app,
choose Account 1 > More > View Passphrase
ZeroLAB
ZeroLAB
Copy your
Account 1
address and
store it in
MY_ACCOUNT
and run the
“goal app
create”
command to
deploy the
smart contract.
DEPLOY SC
// Create a variable called MY_ACCOUNT
export MY_ACCOUNT = <your account address>
// Deploy the smart contract using teal files
goal app create --creator $MY_ACCOUNT --approval-
prog simple_approval.teal --clear-prog
simple_clear.teal --global-ints 1 --global-
byteslices 0 --local-ints 0 --local-byteslices 0
ZeroLAB
ZeroLAB
DEPLOYED SMART CONTRACT
After deploying, we are provided with an app index. Make sure we keep
this app index somewhere for later use.
ZeroLAB
ZeroLAB
Now we need a
frontend to
provide a user
interface to set
a number. This
front end is
built on top of
our Wallet
Connect Dapp
in the previous
practical
session.
CLONE THE DAPP
// Change directory to zerolab-prac
cd zerolab-prac
// Clone the pyteal-prac repo
git clone https://github.com/jasonhtpham/set-number-
dapp.git
// Change directory to pyteal-prac
cd set-number-dapp
// Launch VS Code with the current directory
code .
ZeroLAB
ZeroLAB
INSTALL PACKAGES AND RUN THE DAPP
In the VS Code termimal, run “npm i” to install packages (this may take a
few minutes) > Run “npm start” to launch the app.
ZeroLAB
ZeroLAB
INCOMPLETE DAPP
The Set Number Dapp requires you to connect to an account to function
properly. Go ahead and connect the Dapp to your account via Pera
Algo Wallet like what we did in the last session.
ZeroLAB
ZeroLAB
INCOMPLETE DAPP
At this stage, the set number function is not working as we have not
implemented it and not connected to the smart contract yet. So, the
current number is not available.
ZeroLAB
Let’s implement
the set number
function
ZeroLAB
ZeroLAB
UPDATE DAPP
In VS Code, navigate and open a file named SetNumber.js. Then, copy the
following provided pieces of code in there under the relevant // TODO.
ZeroLAB
ZeroLAB
This code will
create an
Algorand client
instance and
store your app
index in the
appIndex
variable to be
used later.
SET NUMBER FUNCTION
// TODO1: Connect to the algorand node
const client = new algosdk.Algodv2('', 'https://testnet-
api.algonode.cloud', 443);
// TODO1: Provide the app ID on testnet
const appIndex = <your appId>;
Take you app index from the previous step and replace <your appId> with it.
ZeroLAB
ZeroLAB
This piece of
code will use
the Algorand
client instance
to get the
current first
global state
value, which is
the “number”
variable in our
created
contract.
SET NUMBER FUNCTION
// TODO2: Use the Algorand client to get the current number from the smart
contract
const getCurrentNumber = useCallback(async () => {
try {
setLoading(true);
const app = await client.getApplicationByID(appIndex).do();
if (!!app.params['global-state'][0].value.uint) {
setCurrentNumber(app.params['global-state'][0].value.uint);
setLoading(false);
} else {
setCurrentNumber(0);
setLoading(false);
}
} catch (e) {
setLoading(false);
console.error('There was an error connecting to the algorand node: ', e)
}
}, []);
useEffect(() => {
getCurrentNumber();
}, [getCurrentNumber]);
ZeroLAB
ZeroLAB
This piece of
code takes the
entered
number from
the user and
send it as the
parameter to
set the new
value to the
“number”
global state of
our smart
contract.
SET NUMBER FUNCTION
// TODO3: Use the Algorand client to set the current number to the new number
const setNumber = async () => {
try {
setLoading(true);
const numberToSet = parseInt(document.getElementById('number-to-set').value);
const suggestedParams = await client.getTransactionParams().do();
const appArgs = [new Uint8Array(Buffer.from("set_number")), encodeUint64(numberToSet)];
const transaction = algosdk.makeApplicationNoOpTxn(
props.account,
suggestedParams,
appIndex,
appArgs
);
const transactionDetails = [{ txn: transaction, signers: [props.account] }];
const signedTx = await props.wallet.signTransaction([transactionDetails]);
const { txId } = await client.sendRawTransaction(signedTx).do();
const result = await waitForConfirmation(client, txId, 2);
alert(`Result: ${JSON.stringify(result)}`);
getCurrentNumber();
} catch (e) {
setLoading(false);
console.error(`There was an error calling the counter app: ${e}`);
}
}
ZeroLAB
ZeroLAB
SAVE CHANGES
After finish updating, press Ctrl + S or ⌘ Command + S to save changes.
Now the Set Number App is connected to the smart contract.
ZeroLAB
ZeroLAB
TEST DAPP
Enter a number > Set new number > You will get a popup in your Pera
Algo Wallet.
ZeroLAB
ZeroLAB
APPROVE TRANSACTION
In Pera Algo Wallet, Confirm > Accept > Wait for the result on the
browser running your Set Number Dapp.
ZeroLAB
ZeroLAB
TRANSACTION RESULT
After a few seconds, the transaction result is returned and the number is
updated!
ZeroLAB
ZeroLAB
TRANSACTION DETAILS
Transaction details can be verified via Pera Algo Wallet, choose Account
1 > History > App Call (with your application ID) > Open in AlgoExplorer.
ZeroLAB
ZeroLAB
TRANSACTION DETAILS
On your browser, go to AlgoExplorer (https://testnet.algoexplorer.io/) >
Search for your application (smart contract) > Application Global State
> Verify the current number.
ZeroLAB
We have created our first Dapp. Although it is a very
simple one, but we have learned how to write smart
contract, deploy and connect it to a frontend
component. We hope you enjoyed the activity.
In the next practical session, we will look at a tool
which provides us with decentralized file storage.
PRACTICAL 3

More Related Content

Similar to 4-ZeroLab_consensus-1908.pptx

Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...
Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...
Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...Marnusharris
 
BlockChain for the Banker
BlockChain for the BankerBlockChain for the Banker
BlockChain for the BankerBohdan Szymanik
 
Comprehensive Guide regarding Blockchain Technology - Develop Blockchain App
Comprehensive Guide regarding Blockchain Technology - Develop Blockchain AppComprehensive Guide regarding Blockchain Technology - Develop Blockchain App
Comprehensive Guide regarding Blockchain Technology - Develop Blockchain AppBlocktech Brew
 
Scaling Enterprise Blockchain (Summer 2018)
Scaling Enterprise Blockchain (Summer 2018)Scaling Enterprise Blockchain (Summer 2018)
Scaling Enterprise Blockchain (Summer 2018)Rob Bailey
 
Introducing flow the new blockchain for open worlds
Introducing flow  the new blockchain for open worldsIntroducing flow  the new blockchain for open worlds
Introducing flow the new blockchain for open worldsBlockchain Council
 
Abhishek jaiswal blockchain
Abhishek jaiswal blockchainAbhishek jaiswal blockchain
Abhishek jaiswal blockchainAbhishek Jaiswal
 
Blockchain Technology Developments in Government 3.0
Blockchain Technology Developments in Government 3.0Blockchain Technology Developments in Government 3.0
Blockchain Technology Developments in Government 3.0samossummit
 
Blockchain on Azure
Blockchain on AzureBlockchain on Azure
Blockchain on AzureNuri Cankaya
 
3daysblcourseockchainbigdata
3daysblcourseockchainbigdata3daysblcourseockchainbigdata
3daysblcourseockchainbigdataAnne Starr
 
Getting Started with Blockchain Development: The Complete Guide
Getting Started with Blockchain Development: The Complete GuideGetting Started with Blockchain Development: The Complete Guide
Getting Started with Blockchain Development: The Complete GuideBpointerTechnologies
 
Blockchain technology
Blockchain technologyBlockchain technology
Blockchain technologyAayt Bahaa
 
How to Build Your Own Blockchain
How to Build Your Own BlockchainHow to Build Your Own Blockchain
How to Build Your Own BlockchainLeonid Beder
 
Interledger DvP Settlement on Amazon Managed Blockchain
Interledger DvP Settlement on Amazon Managed BlockchainInterledger DvP Settlement on Amazon Managed Blockchain
Interledger DvP Settlement on Amazon Managed BlockchainAmazon Web Services
 
Proof of Stake(PoS) Blockchain Development
Proof of Stake(PoS) Blockchain DevelopmentProof of Stake(PoS) Blockchain Development
Proof of Stake(PoS) Blockchain DevelopmentMobiloitte Technologies
 
Blockchain for Enterprises
Blockchain for EnterprisesBlockchain for Enterprises
Blockchain for EnterprisesHimanshu Pandey
 

Similar to 4-ZeroLab_consensus-1908.pptx (20)

Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...
Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...
Create Blockchain Projects on Solana Blockchain with Solana Blockchain Develo...
 
Blockchain ppt
Blockchain pptBlockchain ppt
Blockchain ppt
 
BlockChain for the Banker
BlockChain for the BankerBlockChain for the Banker
BlockChain for the Banker
 
Ivy Block - technicals.pdf
Ivy Block - technicals.pdfIvy Block - technicals.pdf
Ivy Block - technicals.pdf
 
Comprehensive Guide regarding Blockchain Technology - Develop Blockchain App
Comprehensive Guide regarding Blockchain Technology - Develop Blockchain AppComprehensive Guide regarding Blockchain Technology - Develop Blockchain App
Comprehensive Guide regarding Blockchain Technology - Develop Blockchain App
 
Blockchain
BlockchainBlockchain
Blockchain
 
Scaling Enterprise Blockchain (Summer 2018)
Scaling Enterprise Blockchain (Summer 2018)Scaling Enterprise Blockchain (Summer 2018)
Scaling Enterprise Blockchain (Summer 2018)
 
Introducing flow the new blockchain for open worlds
Introducing flow  the new blockchain for open worldsIntroducing flow  the new blockchain for open worlds
Introducing flow the new blockchain for open worlds
 
Abhishek jaiswal blockchain
Abhishek jaiswal blockchainAbhishek jaiswal blockchain
Abhishek jaiswal blockchain
 
Blockchain Technology Developments in Government 3.0
Blockchain Technology Developments in Government 3.0Blockchain Technology Developments in Government 3.0
Blockchain Technology Developments in Government 3.0
 
Blockchain on Azure
Blockchain on AzureBlockchain on Azure
Blockchain on Azure
 
3daysblcourseockchainbigdata
3daysblcourseockchainbigdata3daysblcourseockchainbigdata
3daysblcourseockchainbigdata
 
Getting Started with Blockchain Development: The Complete Guide
Getting Started with Blockchain Development: The Complete GuideGetting Started with Blockchain Development: The Complete Guide
Getting Started with Blockchain Development: The Complete Guide
 
Blockchain technology
Blockchain technologyBlockchain technology
Blockchain technology
 
"Creating a Competitive Edge Using Blockchain Technology"
"Creating a Competitive Edge Using Blockchain Technology""Creating a Competitive Edge Using Blockchain Technology"
"Creating a Competitive Edge Using Blockchain Technology"
 
How to Build Your Own Blockchain
How to Build Your Own BlockchainHow to Build Your Own Blockchain
How to Build Your Own Blockchain
 
Interledger DvP Settlement on Amazon Managed Blockchain
Interledger DvP Settlement on Amazon Managed BlockchainInterledger DvP Settlement on Amazon Managed Blockchain
Interledger DvP Settlement on Amazon Managed Blockchain
 
Blockchain Breakout Session Tech Coast Conference Jacksonville
Blockchain Breakout Session Tech Coast Conference JacksonvilleBlockchain Breakout Session Tech Coast Conference Jacksonville
Blockchain Breakout Session Tech Coast Conference Jacksonville
 
Proof of Stake(PoS) Blockchain Development
Proof of Stake(PoS) Blockchain DevelopmentProof of Stake(PoS) Blockchain Development
Proof of Stake(PoS) Blockchain Development
 
Blockchain for Enterprises
Blockchain for EnterprisesBlockchain for Enterprises
Blockchain for Enterprises
 

More from ClaudioTebaldi2

BocAlg_LAB_Barcelona.pdf
BocAlg_LAB_Barcelona.pdfBocAlg_LAB_Barcelona.pdf
BocAlg_LAB_Barcelona.pdfClaudioTebaldi2
 
Andrea Bonaceto @Bocconi - Copia.pdf
Andrea Bonaceto @Bocconi - Copia.pdfAndrea Bonaceto @Bocconi - Copia.pdf
Andrea Bonaceto @Bocconi - Copia.pdfClaudioTebaldi2
 
4_capponi - AMBocconi.pdf
4_capponi - AMBocconi.pdf4_capponi - AMBocconi.pdf
4_capponi - AMBocconi.pdfClaudioTebaldi2
 
3_halaburda_tokens-platforms_A.pdf
3_halaburda_tokens-platforms_A.pdf3_halaburda_tokens-platforms_A.pdf
3_halaburda_tokens-platforms_A.pdfClaudioTebaldi2
 
1_accenture_digital assets.pdf
1_accenture_digital assets.pdf1_accenture_digital assets.pdf
1_accenture_digital assets.pdfClaudioTebaldi2
 
6-ZeroLab_decentralized_applications-2008.pptx
6-ZeroLab_decentralized_applications-2008.pptx6-ZeroLab_decentralized_applications-2008.pptx
6-ZeroLab_decentralized_applications-2008.pptxClaudioTebaldi2
 
5-ZeroLab_blockchain_token-1908.pptx
5-ZeroLab_blockchain_token-1908.pptx5-ZeroLab_blockchain_token-1908.pptx
5-ZeroLab_blockchain_token-1908.pptxClaudioTebaldi2
 
1-ZeroLab_blockchain_101-1608.pptx
1-ZeroLab_blockchain_101-1608.pptx1-ZeroLab_blockchain_101-1608.pptx
1-ZeroLab_blockchain_101-1608.pptxClaudioTebaldi2
 

More from ClaudioTebaldi2 (12)

BocAlg_LAB_Barcelona.pdf
BocAlg_LAB_Barcelona.pdfBocAlg_LAB_Barcelona.pdf
BocAlg_LAB_Barcelona.pdf
 
Andrea Bonaceto @Bocconi - Copia.pdf
Andrea Bonaceto @Bocconi - Copia.pdfAndrea Bonaceto @Bocconi - Copia.pdf
Andrea Bonaceto @Bocconi - Copia.pdf
 
8_borri.pdf
8_borri.pdf8_borri.pdf
8_borri.pdf
 
6_payne.pdf
6_payne.pdf6_payne.pdf
6_payne.pdf
 
5_Schoenleber - Y.pdf
5_Schoenleber - Y.pdf5_Schoenleber - Y.pdf
5_Schoenleber - Y.pdf
 
4_capponi - AMBocconi.pdf
4_capponi - AMBocconi.pdf4_capponi - AMBocconi.pdf
4_capponi - AMBocconi.pdf
 
3_halaburda_tokens-platforms_A.pdf
3_halaburda_tokens-platforms_A.pdf3_halaburda_tokens-platforms_A.pdf
3_halaburda_tokens-platforms_A.pdf
 
2_bonti_blockchain.pdf
2_bonti_blockchain.pdf2_bonti_blockchain.pdf
2_bonti_blockchain.pdf
 
1_accenture_digital assets.pdf
1_accenture_digital assets.pdf1_accenture_digital assets.pdf
1_accenture_digital assets.pdf
 
6-ZeroLab_decentralized_applications-2008.pptx
6-ZeroLab_decentralized_applications-2008.pptx6-ZeroLab_decentralized_applications-2008.pptx
6-ZeroLab_decentralized_applications-2008.pptx
 
5-ZeroLab_blockchain_token-1908.pptx
5-ZeroLab_blockchain_token-1908.pptx5-ZeroLab_blockchain_token-1908.pptx
5-ZeroLab_blockchain_token-1908.pptx
 
1-ZeroLab_blockchain_101-1608.pptx
1-ZeroLab_blockchain_101-1608.pptx1-ZeroLab_blockchain_101-1608.pptx
1-ZeroLab_blockchain_101-1608.pptx
 

Recently uploaded

JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Recently uploaded (20)

JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

4-ZeroLab_consensus-1908.pptx

  • 1. ZeroLAB ZeroLab Blockchain Solution Designer Course in collaboration with Bocconi University Part 4 of 6
  • 2. ZeroLAB ZeroLAB Welcome back! In the last session, we got to know more about smart contract – a powerful component which help blockchain become programmable. We hope you have had a good learning experiences so far! In this session, we will learn about another powerful and crucial component of blockchain technology which ensures blockchain network function as it is expected. The component is consensus protocol. INTRO
  • 3. ZeroLAB Consensus Protocol > A deep dive into the backbone of the blockchain technology By Dr. Alessio Bonti & Jason Pham
  • 4. ZeroLAB • Introduction • Definition • Consensus protocols • Controversy & conclusion AGENDA
  • 5. ZeroLAB Introduction How can blockchain be owned and governed by everyone?
  • 6. ZeroLAB ZeroLAB As we learned in lesson 1 and 2, blockchain network is decentralized and that is why people want it. Consensus protocol was said to help the blockchain network secure and moving forward. And, blockchain is owned and governed by everyone LESSON REWIND Decen- tralization Trustless Environment Data Availability & Integrity Network Persistance Optimized Resource Accessibility
  • 7. ZeroLAB ZeroLAB Blockchain nodes run in decentralized manners. Thus, there is no central entity ensuring network consistency and security. But the absence of a central party is preferable as it provides transparency and lack of ownership, meaning data is accessible, verifiable and auditable to everyone. THE NEED However, there must be something that: ▪ Controls the decentralized system to make sure “bad nodes” cannot manipulate it. ▪ Ensures the blockchain network is functional even there are some faults or malicious actions that may compromise it. This is called fault- tolerant. ▪ Decides what is true. Any updates of on-chain data need to be validated.
  • 8. ZeroLAB ZeroLAB The term consensus, in computer science, was defined before the introduction of blockchain. Its utilization was mainly mentioned in distributed systems where participants need to agree on one single state for the entire system. This is referred to as “reaching consensus”. THE CONSENSUS
  • 9. ZeroLAB ZeroLAB Consensus is placed at the core of blockchain system. In blockchain, it is referred to as the mechanism ensuring the common state of the system is correctly derived by all nodes and decentralization is maintained. BLOCKCHAIN CONSENSUS
  • 10. ZeroLAB ZeroLAB Blockchain consensus usually functions based on incentive and punishment scheme. In other words, blockchain system rewards honest behaviours, which keep the system secure and consistent, and punish those with malicious ambition to manipulate the system state. In short, blockchain consensus implements “strict rules without rulers”. BLOCKCHAIN CONSENSUS
  • 12. ZeroLAB ZeroLAB As the blockchain technology is thriving to make enormous impacts. Multiple types consensus protocols were introduced. The principles of any consensus protocols can be comprehended by answering the following questions: ▪ Who can change the past, and how can the past be changed? ▪ Who can change the future, and how can the future be changed? ▪ What cost has to be paid for making changes? ▪ How decentralized is the power to make changes? ▪ Who and how will know if something has changed? CONSENSUS PROTOCOLS
  • 13. ZeroLAB ZeroLAB The proof of work (PoW) was created for the original blockchain Bitcoin as a consensus algorithm. PoW is an important part of Bitcoin to stabilize the difficulties for mining. Mining is a process which requires nodes to solve a “cryptographic puzzle” to derive a block. In PoW, the reward for discovering a legitimate block is a certain amount of cryptocurrency (e.g., bitcoins, ethers). In contrary, miners will lose the money for a huge amount of electricity they invested in solving the cryptographic puzzle, if they propose a “sketchy block”. PROOF OF WORK (PoW)
  • 14. ZeroLAB ZeroLAB PROOF OF WORK (PoW) Pros ▪ Security ▪ Decentralization ▪ Double spending prevention Cons ▪ Excessive energy consumption. ▪ Low transaction speed. Bitcoin and Ethereum are the biggest blockchains using PoW. Miners Block Crypto- graphic puzzle Proof of Work Broadcast new block Verified block Restart Transaction
  • 15. ZeroLAB ZeroLAB The proof of stake (PoS) was proposed as the successor of PoW to solve the problems that are known in PoW. A core difference in PoS is that nodes do not have to do mining, they need to stake and attest instead. Staking is the process when a node nominate itself as validator in the PoS protocol by depositing a certain amount of cryptocurrency via a special transaction. Attesting is referred to as the action that the validators take to decide whether a block is valid. PROOF OF STAKE (PoS)
  • 16. ZeroLAB ZeroLAB ▪ The blockchain maintains a list of validators. ▪ Any users who deposit some ether can self nominate as a validator by staking. ▪ Validators are randomly appointed to propose and attest on the next valid block. ▪ Each validator’s vote is weighted by its stake. ▪ A validator may lose deposit when staking on rejected block. ▪ A validator may also gain reward for proposing and staking on block that is accepted by the majority. PROOF OF STAKE (PoS) Pros ▪ Energy saving ▪ Higher transaction speed ▪ Higher finality Cons ▪ Less security ▪ Less decentralization Algorand, Tezos and Polkadot are examples of blockchains using PoS https://developer.algorand.org/docs/get- started/basics/why_algorand/#proof-of-stake-versus-proof- of-work
  • 17. ZeroLAB ZeroLAB There are still more consensus protocols in the industry: ▪ Proof of Authority ▪ Proof of Elapsed Time ▪ Proof of Capacity ▪ Byzantine Fault Tolerant Protocol ▪ And more… Those protocols were not elaborated because either they are not widely adopted, or they are not used in public blockchain. CONSENSUS PROTOCOLS
  • 18. ZeroLAB ZeroLAB There is no one-solution-fits-all consensus algorithm, at least for the moment. There are always trade-offs whether it is security, cost, decentralization or finality. Therefore, the answer to which consensus algorithm is “better” lies under your needs, your goals and your solution. CONTROVERSY & CONCLUSION
  • 19. ZeroLAB Time to build Our exploration about consensus protocol is over, it is time for practical activities.
  • 20. ZeroLAB ZeroLAB We already made it through two thirds of the journey! Let’s keep it going. This practical session will show you how to write, deploy and test a smart contract. PRACTICAL JOURNEY Topics 1. Create and fund your account with testnet funds. 2. Setup your development environment. 3. Connect account to a Dapp. 4. Write a simple smart contract, deploy and test. 5. Upload images to IPFS through a Dapp. 6. Create NFT on the Dapp and transfer using your wallet.
  • 21. ZeroLAB Practical 4 Write, deploy and test a simple smart contract
  • 22. ZeroLAB ZeroLAB Clone the pyteal-prac repo into the zerolab-prac folder by running the following commands CLONE PYTEAL-PRAC // Change directory to zerolab-prac cd zerolab-prac // Check directory content ls // Remove pyteal-prac directory if there is one rm –rf pyteal-prac // Clone the pyteal-prac repo git clone https://github.com/jasonhtpham/pyteal- prac.git // Change directory to pyteal-prac cd pyteal-prac
  • 23. ZeroLAB ZeroLAB Check the content of the cloned repo and launch VS Code to edit the smart contracts code LAUNCH VS CODE // Check directory content ls // Launch VS Code with the current directory code .
  • 24. ZeroLAB ZeroLAB In Algorand smart contracts: ▪ The ApprovalProgram is responsible for processing all application calls to the contract. This program is responsible for implementing most of the logic of an application. ▪ The ClearStateProgram is used to handle accounts using the clear call to remove the smart contract from their balance record. This program will pass or fail the same way the ApprovalProgram does. APPROVAL AND CLEARSTATE PROGRAM IN ALGORAND
  • 25. ZeroLAB ZeroLAB UPDATE SMART CONTRACT CODE Update the simple_approval.py file to build a set_number smart contract
  • 26. ZeroLAB ZeroLAB This piece of code tells the smart contract to run the on_create sequence when it is initialized. UPDATE SC CODE # TODO1: The function to call when the smart contract is initialized [Txn.application_id() == Int(0), on_create],
  • 27. ZeroLAB ZeroLAB This piece of code defines the on_create sequence that set 0 as the initial value of the “number” global state. UPDATE SC CODE # TODO2: This sequence will be executed when the smart contract is initialized. on_create = Seq([ App.globalPut(Bytes("number"), Int(0)), Return(Int(1)), ])
  • 28. ZeroLAB ZeroLAB This piece of code takes the first transaction argument as the name of the sequence called by the users. If the user asks for the “set_number”, then executes the set_number sequence UPDATE VS CODE # TODO3: Determine which function to call based on the transaction argument called_function = Txn.application_args[0] # TODO3: Based on called_function, call the relevant function handle_noop = Cond( [called_function == Bytes("set_number"), set_number] )
  • 29. ZeroLAB ZeroLAB This piece of code defines the set_number sequence that set the second transaction argument passed by the user as the new value of the “number” global state. UPDATE SC CODE # TODO4: The sequence to set the global variable number to provided value set_number = Seq([ # Take the 2nd transaction argument and store it in the "number" global variable App.globalPut(Bytes("number"), Btoi(Txn.application_args[1])), Return(Int(1)), ])
  • 30. ZeroLAB ZeroLAB simple_clear.py file which, in this case, does not have any logic as we do not have to worry about this part. CLEAR STATE from pyteal import * def clear_state_program(): program = Seq([ Return(Int(1)) ]) return program with open("simple_clear.teal", "w") as f: compiled = compileTeal(clear_state_program(), mode=Mode.Application, version=2) f.write(compiled)
  • 31. ZeroLAB ZeroLAB Install the pyteal module to compile the smart contract. In the VS Code terminal, run the following commands. COMPILE SC // Install pip, type ‘y’ and hit ‘Enter’ when prompted sudo apt install python3-pip // Install pyteal module pip install pyteal // Compile smart contract python3 simple_approval.py
  • 32. ZeroLAB ZeroLAB COMPILE SC After compiling, we will have simple_approval.teal and simple_clear.teal files created. We will use these files to deploy the smart contract.
  • 33. ZeroLAB ZeroLAB Now, we start the sandbox to get us ready to deploy the compiled smart contract. This may take 5 – 10 minutes. START SANDBOX // Change directory to sandbox/ cd ../sandbox/ // Start the sandbox (this may take a few minutes) ./sandbox up testnet -v
  • 34. ZeroLAB ZeroLAB After the sandbox is up and running, we create a test wallet and import our account from the Pera Algo Wallet by providing your Account 1’s 25 words mnemonic IMPORT ACCOUNT // Go inside the algod container ./sandbox enter algod // Change directory to data/ cd /data // Create a new wallet called test goal wallet new test // Import our Account 1 from Pera Algo Wallet goal account import If you did not save your 25 words mnemonic, open Pera Algo Wallet app, choose Account 1 > More > View Passphrase
  • 35. ZeroLAB ZeroLAB Copy your Account 1 address and store it in MY_ACCOUNT and run the “goal app create” command to deploy the smart contract. DEPLOY SC // Create a variable called MY_ACCOUNT export MY_ACCOUNT = <your account address> // Deploy the smart contract using teal files goal app create --creator $MY_ACCOUNT --approval- prog simple_approval.teal --clear-prog simple_clear.teal --global-ints 1 --global- byteslices 0 --local-ints 0 --local-byteslices 0
  • 36. ZeroLAB ZeroLAB DEPLOYED SMART CONTRACT After deploying, we are provided with an app index. Make sure we keep this app index somewhere for later use.
  • 37. ZeroLAB ZeroLAB Now we need a frontend to provide a user interface to set a number. This front end is built on top of our Wallet Connect Dapp in the previous practical session. CLONE THE DAPP // Change directory to zerolab-prac cd zerolab-prac // Clone the pyteal-prac repo git clone https://github.com/jasonhtpham/set-number- dapp.git // Change directory to pyteal-prac cd set-number-dapp // Launch VS Code with the current directory code .
  • 38. ZeroLAB ZeroLAB INSTALL PACKAGES AND RUN THE DAPP In the VS Code termimal, run “npm i” to install packages (this may take a few minutes) > Run “npm start” to launch the app.
  • 39. ZeroLAB ZeroLAB INCOMPLETE DAPP The Set Number Dapp requires you to connect to an account to function properly. Go ahead and connect the Dapp to your account via Pera Algo Wallet like what we did in the last session.
  • 40. ZeroLAB ZeroLAB INCOMPLETE DAPP At this stage, the set number function is not working as we have not implemented it and not connected to the smart contract yet. So, the current number is not available.
  • 42. ZeroLAB ZeroLAB UPDATE DAPP In VS Code, navigate and open a file named SetNumber.js. Then, copy the following provided pieces of code in there under the relevant // TODO.
  • 43. ZeroLAB ZeroLAB This code will create an Algorand client instance and store your app index in the appIndex variable to be used later. SET NUMBER FUNCTION // TODO1: Connect to the algorand node const client = new algosdk.Algodv2('', 'https://testnet- api.algonode.cloud', 443); // TODO1: Provide the app ID on testnet const appIndex = <your appId>; Take you app index from the previous step and replace <your appId> with it.
  • 44. ZeroLAB ZeroLAB This piece of code will use the Algorand client instance to get the current first global state value, which is the “number” variable in our created contract. SET NUMBER FUNCTION // TODO2: Use the Algorand client to get the current number from the smart contract const getCurrentNumber = useCallback(async () => { try { setLoading(true); const app = await client.getApplicationByID(appIndex).do(); if (!!app.params['global-state'][0].value.uint) { setCurrentNumber(app.params['global-state'][0].value.uint); setLoading(false); } else { setCurrentNumber(0); setLoading(false); } } catch (e) { setLoading(false); console.error('There was an error connecting to the algorand node: ', e) } }, []); useEffect(() => { getCurrentNumber(); }, [getCurrentNumber]);
  • 45. ZeroLAB ZeroLAB This piece of code takes the entered number from the user and send it as the parameter to set the new value to the “number” global state of our smart contract. SET NUMBER FUNCTION // TODO3: Use the Algorand client to set the current number to the new number const setNumber = async () => { try { setLoading(true); const numberToSet = parseInt(document.getElementById('number-to-set').value); const suggestedParams = await client.getTransactionParams().do(); const appArgs = [new Uint8Array(Buffer.from("set_number")), encodeUint64(numberToSet)]; const transaction = algosdk.makeApplicationNoOpTxn( props.account, suggestedParams, appIndex, appArgs ); const transactionDetails = [{ txn: transaction, signers: [props.account] }]; const signedTx = await props.wallet.signTransaction([transactionDetails]); const { txId } = await client.sendRawTransaction(signedTx).do(); const result = await waitForConfirmation(client, txId, 2); alert(`Result: ${JSON.stringify(result)}`); getCurrentNumber(); } catch (e) { setLoading(false); console.error(`There was an error calling the counter app: ${e}`); } }
  • 46. ZeroLAB ZeroLAB SAVE CHANGES After finish updating, press Ctrl + S or ⌘ Command + S to save changes. Now the Set Number App is connected to the smart contract.
  • 47. ZeroLAB ZeroLAB TEST DAPP Enter a number > Set new number > You will get a popup in your Pera Algo Wallet.
  • 48. ZeroLAB ZeroLAB APPROVE TRANSACTION In Pera Algo Wallet, Confirm > Accept > Wait for the result on the browser running your Set Number Dapp.
  • 49. ZeroLAB ZeroLAB TRANSACTION RESULT After a few seconds, the transaction result is returned and the number is updated!
  • 50. ZeroLAB ZeroLAB TRANSACTION DETAILS Transaction details can be verified via Pera Algo Wallet, choose Account 1 > History > App Call (with your application ID) > Open in AlgoExplorer.
  • 51. ZeroLAB ZeroLAB TRANSACTION DETAILS On your browser, go to AlgoExplorer (https://testnet.algoexplorer.io/) > Search for your application (smart contract) > Application Global State > Verify the current number.
  • 52. ZeroLAB We have created our first Dapp. Although it is a very simple one, but we have learned how to write smart contract, deploy and connect it to a frontend component. We hope you enjoyed the activity. In the next practical session, we will look at a tool which provides us with decentralized file storage. PRACTICAL 3