SlideShare a Scribd company logo
1 of 51
ZeroLAB
ZeroLab
Blockchain Solution Designer Course
in collaboration with Bocconi University
Part 3 of 6
ZeroLAB
ZeroLAB
Welcome back!
In the last session, we have explored more essential concepts in blockchain.We hope you have learned some new
knowledge over the past two sessions!
In this session, we will learn about smart contract. This is an utmost important concept whichleverages the growth of
blockchain technology.
I N T R O
ZeroLAB
Smart Contract
> A deep dive into the crucial component of
blockchain
By Dr. Alessio Bonti & Jason Pham
ZeroLAB
• Introduction
• Definition
• Smart contract lifecycle
• Smart contract security
• Developmentbest practices
A G E N D A
ZeroLAB
Introduction
“Smart contracts are neither smart nor legal contracts”
Andreas M. Antonopoulos
aantonop.com
Gavin Wood
gavwood.com
ZeroLAB
What is a smart contract?
ZeroLAB
ZeroLAB
Blockchain smart contract is a computational program on blockchain thatcan be
executed based on defined logics. This program is usually immutably deployed and
deterministically executed in a blockchain virtual machine‘s context.
D E F I N I T I O N
Immutability Determinism Blockchain Context
ZeroLAB
ZeroLAB
Most blockchain smart contracts cannot be
updated or modified after deploying.
However, they can be deleted.
I M M U T A B I L I T Y
Example
Alice deploys a smart contract Aand finds outit has some
errors.However, she cannot update smart contract A
because it is immutable.
Therefore, she has to write an updatedversion of smart
contract Aand deploysit as a new smart contract B. Alicecan
also delete smart contract A.
ZeroLAB
ZeroLAB
Given the same inputs and contexts, the
outputs producedby a smart contract are
always similar regardless who the callers are.
D E T E R M I N I S M
Example
Aliceand Bob call the Guess Number smart contract with
their guesses for a chance to win a bounty.The possible
outputs of their calls are understood to be either “Correct”
or “Incorrect”and the process ofdetermining the output is
also known by bothAliceand Bob as well as any other
participants of the game.
ZeroLAB
ZeroLAB
Smart contract execution is limited within
the blockchain network context as it only
has access to on-chain data, their own state
anddata from the invoking transaction.
B L O C K C H A I N C O N T E X T
Example
A smart contract cannot provide Alicewith the ability to get
the weather data as this data is not providedby the
blockchaincontext. Accountdata is, however, available
such as:balance, transactions, smart contracts, because they
are stored and tracked within the blockchain network
context.
ZeroLAB
Smart Contract Lifecycle
The process of a smart contract form being developed to being executed by users
ZeroLAB
ZeroLAB
Smart contracts are usually written in high-
level language the type of which is
characterized by their relevant blockchain
network. In order for a smart contract to be
deployed, it has to be compiled into a low-
level code that the blockchain virtual machine
can understand.
S M A R T C O N T R A C T L I F E C Y C L E
Blockchains Languages
Ethereum Solidity / Serpent / Vyper
Algorand PyTeal / Reach
Hyperledger Fabric Javascript / Go / Java
Ethereum
Despite a number of languages were introduced, Solidity is the most
popular andadopted by Ethereum developers.
Algorand
There are two languages tobuildsmartcontracts on Algorand- Python
and Reach. WhilePython can be used with the support from PyTeal
library.Reach isa new JavaScript-alikelanguage allowingsecure and
simplesmart contractsdevelopment.
Hyperledger Fabric
Smart contractsin Hyperledger Fabricare written in either JavaScript,
Golang or Java.
ZeroLAB
ZeroLAB
S M A R T C O N T R A C T L I F E C Y C L E
After being compiled from a high-level language code, the smart contract can be deployed on
the blockchain platform via a special transaction called contract creation.
A unique identifier will be returned from that transaction. It can be used to interact with the
deployed contract.
ZeroLAB
ZeroLAB
S M A R T C O N T R A C T L I F E C Y C L E
A smart contract:
 only runwhen theyaretriggered by a
transaction.
 never run in the background by itself.
 is able to call another contract which can
further call another contract.
Butthe first contract call is always made by a
transaction from anexternal entity (users).
ZeroLAB
Important notes about smart
contracts
ZeroLAB
ZeroLAB
I M P O R T A N T N O T E S
No creator privilege
Unless clearly programmed in thesmart
contract, the creator does not have any
specialcontrol over their smart contract.
Synchronous execution
Smart contracts in thesame flow never run
simultaneously.One is executed after
another.
ZeroLAB
Security & Best Practices
Security and best practices in developing smartcontracts.
ZeroLAB
ZeroLAB
Security is themost crucial aspect in smart contracts
developing. Ifa smart contract is exploited, the cost
might be extremely expensive.
Therefore, it is suggested to ensure the following criteria
when building smart contracts:
 Minimalism
 Reuse code
 Code quality
 Auditability
 Test coverage
S E C U R I T Y & B E S T P R A C T I C E S
ZeroLAB
ZeroLAB
Complication is not goodfor security. Bugs
and errors are less likely to occur if the code is
simple, short and only does one thing.
Always try to keep the code as simple as
possible to avoid unwanted effects which may
lead to security loopholes. Simpler means
more secure.
MINIMALISM
ZeroLAB
ZeroLAB
Avoid reinventing the wheel. Developers are
encouraged to use existing libraries or contracts if
they can. This helps reduce the risk of havinga
security weakness in newly created contracts.
Those smart contracts that are already used and
tested by others are way more secure than thenew
ones. So,reuse code to reduce risk.
REUSE CODE
ZeroLAB
ZeroLAB
Mistakes in smart contract code are expensive.
It is not similar to other general programming.
Therefore, developers need to follow
rigorous engineering discipline. A deployed
smart contract must not contains any security
loopholes.
CODE QUALITY
ZeroLAB
ZeroLAB
Smart contract code should be clear and easy to
understand. It is easier to spot errors when the
code is well-structured. As smart contracts are
publicly viewable, developers can benefit from
the collective wisdom ofother developers.
However, this is usually onlytrue for code that is
well-organized, easy to follow and adhere to the
conventions.
A U D I T A B I L I T Y
ZeroLAB
ZeroLAB
Everything should be tested. As smart contracts
can be executed by anyone withany input, it should
notbe assumed that inputs are well formatted and
free of malicious ambition. Therefore, developers
shouldtest all expected parameters to ensure
they are legitimate before proceeding to any
code execution.
T E S T C O V E R A G E
ZeroLAB
Time to build
The theory part about smart contract is over, it is time for practical activities.
ZeroLAB
ZeroLAB
This practical session marks the half way of the
training.
This third practical session will show you how
to connect a blockchain account to a web
application.
P R A C T I C A L J O U R N E Y
Topics
1. Create and fundyour 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 3
Connect blockchain account to a decentralized application (Dapp)
ZeroLAB
ZeroLAB
Wewill start interacting with the webfrontend codefrom this practical.
A web frontend is acomponentthat providesuser friendly interfaceto our decentralizedapplication(Dapp).It allows users to
interactwith our Dappjust likeany other conventionalweb apps.
Wewill useReactframeworkto buildour web frontend. Moredetails aboutReactis out ofour lessonscope. You arenot
requiredto knowReactto follow our practical.So, youcan leaveit to us!
I N T R O D U C T I O N
ZeroLAB
ZeroLAB
Inthis practical session we will need toinstall 2 things:
 Visual Studio Code (VS Code): a code editor software to write and modify code.
 NodeJS: a runtime environmentto execute JavaScript code.
Besides, we need:
 The PeraAlgo Walletthat is holdingour accounts created from the first practical session.
 Andthe Wallet Connection application codebase from GitHub.
R E Q U I R E M E N T S
ZeroLAB
ZeroLAB
D O W N L O A D V S C O D E
Go tohttps://code.visualstudio.com/ to download Visual Studio Code. This may take a few minutes.
ZeroLAB
ZeroLAB
I N S T A L L V S C O D E
Clickon the downloaded file > Select “I accept the agreement” > Follow the rest of the process with all default choices.
ZeroLAB
ZeroLAB
Launch the Ubuntu 20.04 subsystem that
we set up in the last lesson (Mac users
launch your terminal), then run the following
commands.
C L O N E T H E R E P O
// Change to zerolab-prac
directory
cd zerolab-prac
// Clone the connect-wallet
repo
git clone
https://github.com/jasonhtpha
m/connect-wallet.git
// List files and directories
in the current directory
ls
ZeroLAB
ZeroLAB
Stillin the terminal,
we install NodeJS by
runningthe
following commands
I N S T A L L N O D E J S
// Download installation script and execute
curl -sL https://deb.nodesource.com/setup_16.x |
sudo -E bash –
// Install NodeJS and npm
sudo apt install nodejs
// Verify NodeJS and npm are installed
node –v
npm -v
// install the development tools, type y when asked
sudo apt install build-essential
Screenshotsof installationinthe next slide…
ZeroLAB
ZeroLAB
I N S T A L L N O D E J S
ZeroLAB
ZeroLAB
Now, we gointo the
connect-wallet
folder to setup the
application
I N S T A L L P A C K A G E S
// Get in to the connect-wallet folder
cd connect-wallet/
// Check the content of the folder
ls
// Install necessary packages using npm command
npm i
ZeroLAB
ZeroLAB
We can go ahead
and launch VS Code
to open the current
folder so we can
have a look at the
code
L A U N C H V S C O D E
// Launch VS Code
code . &
ZeroLAB
If you encounter this error, just close the terminal and launch it
again. Then retry to launch the VS Code.
T R O U B L E S H O O T I N G
ZeroLAB
ZeroLAB
We can now launch the
app from the Terminal
in VS Code
L A U N C H A P P
ZeroLAB
ZeroLAB
In the VS Code
Terminal, run the
following command to
launch the app
L A U N C H A P P
// Launch app with npm command
npm start
ZeroLAB
ZeroLAB
L A U N C H A P P
At this stagethe appdoes not doanything, thebutton does nottrigger anything whenyou clickit.
ZeroLAB
ZeroLAB
U P D A T E A P P
We will start updating the appto enable it to connect to our account.Open the VS Code> Navigate to the file called
WalletConnect.js (Details on screenshot)
ZeroLAB
Update app using provided
code
You should copy the provided pieces of code and paste them under the relevant //
TODO comments in your code.
ZeroLAB
ZeroLAB
This part of codewill
give us the tools to
connect to Pera Algo
Wallet and get
accounts information.
U P D A T E A P P
// TODO1: Create the PeraWallet instance
const peraWallet = new PeraWalletConnect();
// TODO1: Connect to an algorand node
const client = new algosdk.Algodv2('', 'https://testnet-
api.algonode.cloud', 443);
Copy andpaste this intoyour VS Code under the relevant comment.
ZeroLAB
ZeroLAB
This function will be
triggered when we
click the “Connect to
Pera Wallet” button. It
will provide the way to
connect our account
from Pera Algo Wallet
to our app.
U P D A T E A P P
// TODO2: Handle the connect to PeraWallet button click
const handleConnectWalletClick = () => {
peraWallet.connect().then((newAccounts) => {
// setup the disconnect event listener
peraWallet.connector?.on('disconnect',
handleDisconnectWalletClick);
setAccountAddress(newAccounts[0]);
});
}
ZeroLAB
ZeroLAB
This function will be
triggered when we
click the
“Disconnect” button.
It will disconnect our
account from Pera Algo
Wallet to our app.
U P D A T E A P P
// TODO3: Handle the disconnect from PeraWallet button
click
const handleDisconnectWalletClick = () => {
peraWallet.disconnect();
setAccountAddress(null);
setAccountInfo(null);
}
ZeroLAB
ZeroLAB
This piece of code will
retrieve the
connected account
information on
Algorand Testnet. The
information including
account balance, assets,
etc. But we will only
show the balance.
U P D A T E A P P
// TODO4: Get account info when the account address is
set
useEffect(() => {
if (accountAddress) {
client.accountInformation(accountAddress).do().then
((accountInfo) => {
setAccountInfo(accountInfo);
}).catch((err) => {
console.log(err);
});
}
}, [accountAddress]);
ZeroLAB
ZeroLAB
This piece of code will
automatically
connect to your
account if you
previously connected to
the app.
U P D A T E A P P
// TODO5: Auto reconnect to wallet if wallet is connected
useEffect(() => {
// reconnect to session when the component is mounted
peraWallet.reconnectSession().then((accounts) => {
// Setup disconnect event listener
peraWallet.connector?.on('disconnect',
handleDisconnectWalletClick);
if (accounts.length) {
setAccountAddress(accounts[0]);
}
})
}, []);
ZeroLAB
ZeroLAB
C O N N E C T A C C O U N T T O A P P
After you save all the changes in your code (Ctrl + S or  command + S), your app is able to connect to your account
now.
ZeroLAB
ZeroLAB
C O N N E C T A C C O U N T T O A P P
From your PeraAlgo Wallet app > Tap Scan QR > Scan the QR code on the app.
ZeroLAB
ZeroLAB
C O N N E C T A C C O U N T T O A P P
Tap Select Account > Choose Account 1 > Tap Connect.
ZeroLAB
ZeroLAB
C O N N E C T A C C O U N T T O A P P
Your accountis connectedto the Wallet Connection app!!!!!!
ZeroLAB
We have done enabling the web frontend to connectto our account via Pera Algo
Wallet, which willallow us to do more on the web frontend later.
In the next practical session, we will write, deploy and test a simple smart contract.
P R A C T I C A L 3

More Related Content

Similar to 3-ZeroLab_smart_contract-2008.pptx

Hyperledger Fabric and Tools
Hyperledger Fabric and ToolsHyperledger Fabric and Tools
Hyperledger Fabric and ToolsRihusoft
 
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
 
Want to know the best answer to how to buy algorand in Canada checkout netcoins!
Want to know the best answer to how to buy algorand in Canada checkout netcoins!Want to know the best answer to how to buy algorand in Canada checkout netcoins!
Want to know the best answer to how to buy algorand in Canada checkout netcoins!Bitcoin Wallet Canada
 
Top 8 blockchain based smart contract platforms
Top 8 blockchain based smart contract platformsTop 8 blockchain based smart contract platforms
Top 8 blockchain based smart contract platformsBlockchain Council
 
Hyperledger Fabric in a Nutshell
Hyperledger Fabric in a NutshellHyperledger Fabric in a Nutshell
Hyperledger Fabric in a NutshellDaniel Chan
 
Eris Industries - American Banker presentation deck.
Eris Industries - American Banker presentation deck. Eris Industries - American Banker presentation deck.
Eris Industries - American Banker presentation deck. Preston Byrne
 
Prominent Blockchain Programming Languages to consider while building Blockch...
Prominent Blockchain Programming Languages to consider while building Blockch...Prominent Blockchain Programming Languages to consider while building Blockch...
Prominent Blockchain Programming Languages to consider while building Blockch...Shelly Megan
 
How to Create Your Own Bondly Clone A Step-by-Step Guide.pdf
How to Create Your Own Bondly Clone A Step-by-Step Guide.pdfHow to Create Your Own Bondly Clone A Step-by-Step Guide.pdf
How to Create Your Own Bondly Clone A Step-by-Step Guide.pdfTurnkeytown
 
zkFold - Zero Knowledge Smart Contracts on Cardano
zkFold - Zero Knowledge Smart Contracts on CardanozkFold - Zero Knowledge Smart Contracts on Cardano
zkFold - Zero Knowledge Smart Contracts on CardanoBharat Mallapur
 
Smart Cards & Devices Forum 2012 - Smart Phones Security
Smart Cards & Devices Forum 2012 - Smart Phones SecuritySmart Cards & Devices Forum 2012 - Smart Phones Security
Smart Cards & Devices Forum 2012 - Smart Phones SecurityOKsystem
 
What is DecenPool Passive Earning.docx
What is DecenPool Passive Earning.docxWhat is DecenPool Passive Earning.docx
What is DecenPool Passive Earning.docxOliverMurray3
 

Similar to 3-ZeroLab_smart_contract-2008.pptx (20)

Hyperledger
HyperledgerHyperledger
Hyperledger
 
Hyperledger Fabric and Tools
Hyperledger Fabric and ToolsHyperledger Fabric and Tools
Hyperledger Fabric and Tools
 
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
 
Want to know the best answer to how to buy algorand in Canada checkout netcoins!
Want to know the best answer to how to buy algorand in Canada checkout netcoins!Want to know the best answer to how to buy algorand in Canada checkout netcoins!
Want to know the best answer to how to buy algorand in Canada checkout netcoins!
 
Decentralized App Blockchain
Decentralized App BlockchainDecentralized App Blockchain
Decentralized App Blockchain
 
Ivy Block - technicals.pdf
Ivy Block - technicals.pdfIvy Block - technicals.pdf
Ivy Block - technicals.pdf
 
Dao - Mobiloitte
Dao - MobiloitteDao - Mobiloitte
Dao - Mobiloitte
 
Top 8 blockchain based smart contract platforms
Top 8 blockchain based smart contract platformsTop 8 blockchain based smart contract platforms
Top 8 blockchain based smart contract platforms
 
Fluence.sh
Fluence.sh Fluence.sh
Fluence.sh
 
Hyperledger Fabric in a Nutshell
Hyperledger Fabric in a NutshellHyperledger Fabric in a Nutshell
Hyperledger Fabric in a Nutshell
 
Eris Industries - American Banker presentation deck.
Eris Industries - American Banker presentation deck. Eris Industries - American Banker presentation deck.
Eris Industries - American Banker presentation deck.
 
Prominent Blockchain Programming Languages to consider while building Blockch...
Prominent Blockchain Programming Languages to consider while building Blockch...Prominent Blockchain Programming Languages to consider while building Blockch...
Prominent Blockchain Programming Languages to consider while building Blockch...
 
How to Create Your Own Bondly Clone A Step-by-Step Guide.pdf
How to Create Your Own Bondly Clone A Step-by-Step Guide.pdfHow to Create Your Own Bondly Clone A Step-by-Step Guide.pdf
How to Create Your Own Bondly Clone A Step-by-Step Guide.pdf
 
zkFold - Zero Knowledge Smart Contracts on Cardano
zkFold - Zero Knowledge Smart Contracts on CardanozkFold - Zero Knowledge Smart Contracts on Cardano
zkFold - Zero Knowledge Smart Contracts on Cardano
 
Web3-Guide.pdf
Web3-Guide.pdfWeb3-Guide.pdf
Web3-Guide.pdf
 
Smart Cards & Devices Forum 2012 - Smart Phones Security
Smart Cards & Devices Forum 2012 - Smart Phones SecuritySmart Cards & Devices Forum 2012 - Smart Phones Security
Smart Cards & Devices Forum 2012 - Smart Phones Security
 
What are DApps.pdf
What are DApps.pdfWhat are DApps.pdf
What are DApps.pdf
 
How to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contractHow to design, code, deploy and execute a smart contract
How to design, code, deploy and execute a smart contract
 
Hyperledger: Market, Technology & Community Update
Hyperledger: Market, Technology & Community UpdateHyperledger: Market, Technology & Community Update
Hyperledger: Market, Technology & Community Update
 
What is DecenPool Passive Earning.docx
What is DecenPool Passive Earning.docxWhat is DecenPool Passive Earning.docx
What is DecenPool Passive Earning.docx
 

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
 
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 (11)

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

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 

Recently uploaded (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

3-ZeroLab_smart_contract-2008.pptx

  • 1. ZeroLAB ZeroLab Blockchain Solution Designer Course in collaboration with Bocconi University Part 3 of 6
  • 2. ZeroLAB ZeroLAB Welcome back! In the last session, we have explored more essential concepts in blockchain.We hope you have learned some new knowledge over the past two sessions! In this session, we will learn about smart contract. This is an utmost important concept whichleverages the growth of blockchain technology. I N T R O
  • 3. ZeroLAB Smart Contract > A deep dive into the crucial component of blockchain By Dr. Alessio Bonti & Jason Pham
  • 4. ZeroLAB • Introduction • Definition • Smart contract lifecycle • Smart contract security • Developmentbest practices A G E N D A
  • 5. ZeroLAB Introduction “Smart contracts are neither smart nor legal contracts” Andreas M. Antonopoulos aantonop.com Gavin Wood gavwood.com
  • 6. ZeroLAB What is a smart contract?
  • 7. ZeroLAB ZeroLAB Blockchain smart contract is a computational program on blockchain thatcan be executed based on defined logics. This program is usually immutably deployed and deterministically executed in a blockchain virtual machine‘s context. D E F I N I T I O N Immutability Determinism Blockchain Context
  • 8. ZeroLAB ZeroLAB Most blockchain smart contracts cannot be updated or modified after deploying. However, they can be deleted. I M M U T A B I L I T Y Example Alice deploys a smart contract Aand finds outit has some errors.However, she cannot update smart contract A because it is immutable. Therefore, she has to write an updatedversion of smart contract Aand deploysit as a new smart contract B. Alicecan also delete smart contract A.
  • 9. ZeroLAB ZeroLAB Given the same inputs and contexts, the outputs producedby a smart contract are always similar regardless who the callers are. D E T E R M I N I S M Example Aliceand Bob call the Guess Number smart contract with their guesses for a chance to win a bounty.The possible outputs of their calls are understood to be either “Correct” or “Incorrect”and the process ofdetermining the output is also known by bothAliceand Bob as well as any other participants of the game.
  • 10. ZeroLAB ZeroLAB Smart contract execution is limited within the blockchain network context as it only has access to on-chain data, their own state anddata from the invoking transaction. B L O C K C H A I N C O N T E X T Example A smart contract cannot provide Alicewith the ability to get the weather data as this data is not providedby the blockchaincontext. Accountdata is, however, available such as:balance, transactions, smart contracts, because they are stored and tracked within the blockchain network context.
  • 11. ZeroLAB Smart Contract Lifecycle The process of a smart contract form being developed to being executed by users
  • 12. ZeroLAB ZeroLAB Smart contracts are usually written in high- level language the type of which is characterized by their relevant blockchain network. In order for a smart contract to be deployed, it has to be compiled into a low- level code that the blockchain virtual machine can understand. S M A R T C O N T R A C T L I F E C Y C L E Blockchains Languages Ethereum Solidity / Serpent / Vyper Algorand PyTeal / Reach Hyperledger Fabric Javascript / Go / Java Ethereum Despite a number of languages were introduced, Solidity is the most popular andadopted by Ethereum developers. Algorand There are two languages tobuildsmartcontracts on Algorand- Python and Reach. WhilePython can be used with the support from PyTeal library.Reach isa new JavaScript-alikelanguage allowingsecure and simplesmart contractsdevelopment. Hyperledger Fabric Smart contractsin Hyperledger Fabricare written in either JavaScript, Golang or Java.
  • 13. ZeroLAB ZeroLAB S M A R T C O N T R A C T L I F E C Y C L E After being compiled from a high-level language code, the smart contract can be deployed on the blockchain platform via a special transaction called contract creation. A unique identifier will be returned from that transaction. It can be used to interact with the deployed contract.
  • 14. ZeroLAB ZeroLAB S M A R T C O N T R A C T L I F E C Y C L E A smart contract:  only runwhen theyaretriggered by a transaction.  never run in the background by itself.  is able to call another contract which can further call another contract. Butthe first contract call is always made by a transaction from anexternal entity (users).
  • 15. ZeroLAB Important notes about smart contracts
  • 16. ZeroLAB ZeroLAB I M P O R T A N T N O T E S No creator privilege Unless clearly programmed in thesmart contract, the creator does not have any specialcontrol over their smart contract. Synchronous execution Smart contracts in thesame flow never run simultaneously.One is executed after another.
  • 17. ZeroLAB Security & Best Practices Security and best practices in developing smartcontracts.
  • 18. ZeroLAB ZeroLAB Security is themost crucial aspect in smart contracts developing. Ifa smart contract is exploited, the cost might be extremely expensive. Therefore, it is suggested to ensure the following criteria when building smart contracts:  Minimalism  Reuse code  Code quality  Auditability  Test coverage S E C U R I T Y & B E S T P R A C T I C E S
  • 19. ZeroLAB ZeroLAB Complication is not goodfor security. Bugs and errors are less likely to occur if the code is simple, short and only does one thing. Always try to keep the code as simple as possible to avoid unwanted effects which may lead to security loopholes. Simpler means more secure. MINIMALISM
  • 20. ZeroLAB ZeroLAB Avoid reinventing the wheel. Developers are encouraged to use existing libraries or contracts if they can. This helps reduce the risk of havinga security weakness in newly created contracts. Those smart contracts that are already used and tested by others are way more secure than thenew ones. So,reuse code to reduce risk. REUSE CODE
  • 21. ZeroLAB ZeroLAB Mistakes in smart contract code are expensive. It is not similar to other general programming. Therefore, developers need to follow rigorous engineering discipline. A deployed smart contract must not contains any security loopholes. CODE QUALITY
  • 22. ZeroLAB ZeroLAB Smart contract code should be clear and easy to understand. It is easier to spot errors when the code is well-structured. As smart contracts are publicly viewable, developers can benefit from the collective wisdom ofother developers. However, this is usually onlytrue for code that is well-organized, easy to follow and adhere to the conventions. A U D I T A B I L I T Y
  • 23. ZeroLAB ZeroLAB Everything should be tested. As smart contracts can be executed by anyone withany input, it should notbe assumed that inputs are well formatted and free of malicious ambition. Therefore, developers shouldtest all expected parameters to ensure they are legitimate before proceeding to any code execution. T E S T C O V E R A G E
  • 24. ZeroLAB Time to build The theory part about smart contract is over, it is time for practical activities.
  • 25. ZeroLAB ZeroLAB This practical session marks the half way of the training. This third practical session will show you how to connect a blockchain account to a web application. P R A C T I C A L J O U R N E Y Topics 1. Create and fundyour 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.
  • 26. ZeroLAB Practical 3 Connect blockchain account to a decentralized application (Dapp)
  • 27. ZeroLAB ZeroLAB Wewill start interacting with the webfrontend codefrom this practical. A web frontend is acomponentthat providesuser friendly interfaceto our decentralizedapplication(Dapp).It allows users to interactwith our Dappjust likeany other conventionalweb apps. Wewill useReactframeworkto buildour web frontend. Moredetails aboutReactis out ofour lessonscope. You arenot requiredto knowReactto follow our practical.So, youcan leaveit to us! I N T R O D U C T I O N
  • 28. ZeroLAB ZeroLAB Inthis practical session we will need toinstall 2 things:  Visual Studio Code (VS Code): a code editor software to write and modify code.  NodeJS: a runtime environmentto execute JavaScript code. Besides, we need:  The PeraAlgo Walletthat is holdingour accounts created from the first practical session.  Andthe Wallet Connection application codebase from GitHub. R E Q U I R E M E N T S
  • 29. ZeroLAB ZeroLAB D O W N L O A D V S C O D E Go tohttps://code.visualstudio.com/ to download Visual Studio Code. This may take a few minutes.
  • 30. ZeroLAB ZeroLAB I N S T A L L V S C O D E Clickon the downloaded file > Select “I accept the agreement” > Follow the rest of the process with all default choices.
  • 31. ZeroLAB ZeroLAB Launch the Ubuntu 20.04 subsystem that we set up in the last lesson (Mac users launch your terminal), then run the following commands. C L O N E T H E R E P O // Change to zerolab-prac directory cd zerolab-prac // Clone the connect-wallet repo git clone https://github.com/jasonhtpha m/connect-wallet.git // List files and directories in the current directory ls
  • 32. ZeroLAB ZeroLAB Stillin the terminal, we install NodeJS by runningthe following commands I N S T A L L N O D E J S // Download installation script and execute curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash – // Install NodeJS and npm sudo apt install nodejs // Verify NodeJS and npm are installed node –v npm -v // install the development tools, type y when asked sudo apt install build-essential Screenshotsof installationinthe next slide…
  • 33. ZeroLAB ZeroLAB I N S T A L L N O D E J S
  • 34. ZeroLAB ZeroLAB Now, we gointo the connect-wallet folder to setup the application I N S T A L L P A C K A G E S // Get in to the connect-wallet folder cd connect-wallet/ // Check the content of the folder ls // Install necessary packages using npm command npm i
  • 35. ZeroLAB ZeroLAB We can go ahead and launch VS Code to open the current folder so we can have a look at the code L A U N C H V S C O D E // Launch VS Code code . &
  • 36. ZeroLAB If you encounter this error, just close the terminal and launch it again. Then retry to launch the VS Code. T R O U B L E S H O O T I N G
  • 37. ZeroLAB ZeroLAB We can now launch the app from the Terminal in VS Code L A U N C H A P P
  • 38. ZeroLAB ZeroLAB In the VS Code Terminal, run the following command to launch the app L A U N C H A P P // Launch app with npm command npm start
  • 39. ZeroLAB ZeroLAB L A U N C H A P P At this stagethe appdoes not doanything, thebutton does nottrigger anything whenyou clickit.
  • 40. ZeroLAB ZeroLAB U P D A T E A P P We will start updating the appto enable it to connect to our account.Open the VS Code> Navigate to the file called WalletConnect.js (Details on screenshot)
  • 41. ZeroLAB Update app using provided code You should copy the provided pieces of code and paste them under the relevant // TODO comments in your code.
  • 42. ZeroLAB ZeroLAB This part of codewill give us the tools to connect to Pera Algo Wallet and get accounts information. U P D A T E A P P // TODO1: Create the PeraWallet instance const peraWallet = new PeraWalletConnect(); // TODO1: Connect to an algorand node const client = new algosdk.Algodv2('', 'https://testnet- api.algonode.cloud', 443); Copy andpaste this intoyour VS Code under the relevant comment.
  • 43. ZeroLAB ZeroLAB This function will be triggered when we click the “Connect to Pera Wallet” button. It will provide the way to connect our account from Pera Algo Wallet to our app. U P D A T E A P P // TODO2: Handle the connect to PeraWallet button click const handleConnectWalletClick = () => { peraWallet.connect().then((newAccounts) => { // setup the disconnect event listener peraWallet.connector?.on('disconnect', handleDisconnectWalletClick); setAccountAddress(newAccounts[0]); }); }
  • 44. ZeroLAB ZeroLAB This function will be triggered when we click the “Disconnect” button. It will disconnect our account from Pera Algo Wallet to our app. U P D A T E A P P // TODO3: Handle the disconnect from PeraWallet button click const handleDisconnectWalletClick = () => { peraWallet.disconnect(); setAccountAddress(null); setAccountInfo(null); }
  • 45. ZeroLAB ZeroLAB This piece of code will retrieve the connected account information on Algorand Testnet. The information including account balance, assets, etc. But we will only show the balance. U P D A T E A P P // TODO4: Get account info when the account address is set useEffect(() => { if (accountAddress) { client.accountInformation(accountAddress).do().then ((accountInfo) => { setAccountInfo(accountInfo); }).catch((err) => { console.log(err); }); } }, [accountAddress]);
  • 46. ZeroLAB ZeroLAB This piece of code will automatically connect to your account if you previously connected to the app. U P D A T E A P P // TODO5: Auto reconnect to wallet if wallet is connected useEffect(() => { // reconnect to session when the component is mounted peraWallet.reconnectSession().then((accounts) => { // Setup disconnect event listener peraWallet.connector?.on('disconnect', handleDisconnectWalletClick); if (accounts.length) { setAccountAddress(accounts[0]); } }) }, []);
  • 47. ZeroLAB ZeroLAB C O N N E C T A C C O U N T T O A P P After you save all the changes in your code (Ctrl + S or  command + S), your app is able to connect to your account now.
  • 48. ZeroLAB ZeroLAB C O N N E C T A C C O U N T T O A P P From your PeraAlgo Wallet app > Tap Scan QR > Scan the QR code on the app.
  • 49. ZeroLAB ZeroLAB C O N N E C T A C C O U N T T O A P P Tap Select Account > Choose Account 1 > Tap Connect.
  • 50. ZeroLAB ZeroLAB C O N N E C T A C C O U N T T O A P P Your accountis connectedto the Wallet Connection app!!!!!!
  • 51. ZeroLAB We have done enabling the web frontend to connectto our account via Pera Algo Wallet, which willallow us to do more on the web frontend later. In the next practical session, we will write, deploy and test a simple smart contract. P R A C T I C A L 3

Editor's Notes

  1. After being compiled, the smart contract can be deployed on the blockchain platform via a special transaction called contract creation. A unique identifier will be returned from that transaction. In some blockchains, the identifier is a special account address, while in others, it is identified by a unique name or a unique number. The derived identifier can be used in transactions to transfer and receive funds or invoke functions in the contract.