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
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.
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).
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.
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.
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…
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
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
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.