Slide 1

Slide 1 text

Build your first smart contract Giovanni Toraldo GDG DevFest Pisa 2023 1st April 2023

Slide 2

Slide 2 text

About me DevOps Engineer @ Hyland ● Alfresco BDU ● Ansible playbook ● Helm charts Open Source enthusiast Medieval reenactor during the weekends 🎯 Twitter: @gionn

Slide 3

Slide 3 text

What is a cryptocurrency ● A digital currency that uses cryptography for security and integrity ● Decentralized, not controlled by any central authority ● Transactions are recorded on a distributed public ledger (blockchain) ○ provide users with a high degree of privacy and anonymity, as transactions are pseudonymous and do not require personal identification ● Offer lower transaction fees (but it depends) ● Anyone can start receiving currency just by running a software ○ For sending most of the times you need a third party to exchange your FIAT money

Slide 4

Slide 4 text

Total crypto market cap, a result of 12,301 cryptocurrencies tracked across 666 exchanges. https://www.coingecko.com/en/global-charts

Slide 5

Slide 5 text

Introduction to Bitcoin ● first and most well-known cryptocurrency ○ Born in October 2008 as a research paper ○ Release v0.1 in early January 2009 as OSS ● Limited supply: 21 millions ○ Inflation halvening ● Decentralized consensus: Proof-Of-Work ○ Easy to validate for everyone ○ Hard to generate ■ Each new block generates fresh Bitcoins ● Each transaction requires a fee depending on the network congestion ○ Block size limited, finite number of TX in each block, block emission requires time

Slide 6

Slide 6 text

Bitcoin desktop screenshot

Slide 7

Slide 7 text

Programming Bitcoin: Script ● Stack-based programming language ● Not Turing-complete (no loops) ● Foundation for transactions validation ○ Overspending ○ Requires 1 or more valid signatures ○ Time-lock ● These limitations was a design choice in order to: ○ Have predictable execution times ○ Avoid deadlocks / infinite loops ○ High security ○ Low hardware requirements

Slide 8

Slide 8 text

Introduction to Ethereum ● 2nd crypto as market capitalization ● Network up since 2015 ● Unlimited supply (new eth distributed for each block) ○ Deflationary since 15 September 2022: transactions fees exceeding a threshold get burnt ● Decentralized consensus: Proof-Of-Stake (since 15 September 2022) ○ One random validator randomly selected from the pool propose the next block transactions ■ Requires 32 ETH staked ■ Get punished if bad behaviour detected by other nodes ● Each transaction requires a fee depending on the network congestion ○ Block size limited, finite number of TX in each block, block emission with fixed cadency

Slide 9

Slide 9 text

Ethereum Virtual Machine (EVM) ● Ethereum is not just a blockchain ● Imagine a computer that everyone in the network can: ○ Have access to its state contents (storage) ○ Ask for a computation that can optionally alter the state ● Requests for computation are transactions ○ Consume gas to be evaluated that is paid by the requester ■ throwing an exception requires evaluation ○ There is a cap on gas usage known before broadcasting ● Code for computations has to be deployed before it can be evaluated

Slide 10

Slide 10 text

Use Cases for Ethereum Smart Contracts ● Decentralized finance (DeFi) ○ lending platforms, decentralized exchanges, stablecoins ○ no need for trusted intermediaries like banks, users can provide liquidity while keeping custody of funds (code is law) ● Non-Fungible Tokens (NFT) - ownership of a unique content ○ Digital art, game assets, physical world objects ○ Tradable on dedicated marketplaces ● Whatever is supposed to be public, verifiable by third parties, immutable

Slide 11

Slide 11 text

Dapp example: app.uniswap.org

Slide 12

Slide 12 text

Dapp example: app.aave.com

Slide 13

Slide 13 text

Dapp example: app.pooltogether.com

Slide 14

Slide 14 text

Interact with dapps via browser ● Install a browser extension for wallets ● Generate a new wallet using 24 seed words ○ Multiple derived address ● Buy gas necessary to pay transactions ○ Test networks has free faucets ● Connect to a web3 website ● Interact with the UI ● Emit a transaction via browser

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

Example transaction: gas usage and input data

Slide 18

Slide 18 text

Beware of scams ⚠ World is full of bad people and blockchain made very easy to run away with other people money. ● Do not use on google search sponsored links ○ Rely on saved bookmarks ● Do not enter seed words in any other place than your wallet first setup ● Do not save seed words on an internet connected device ● Do not interact with DM and replies with URL on socials and chats ● Beware of the other standard scam vectors ○ Domain typosquatting ○ Phishing emails ● Verify that the transactions you made are against the expected contracts

Slide 19

Slide 19 text

Smart Contracts on Ethereum ● Solidity code (compiled) can be deployed on Ethereum ⇒ contract created ● Each contract has (like a wallet): ○ An unique address ○ A balance in ETH ● Each contract has: ○ State (variables, constants) ○ Callable functions ■ Alter the state (requires a tx) ■ View only (query the state without a tx) ● Functions can: ○ Make computations ○ Alter the contract state ○ Call other contracts external functions

Slide 20

Slide 20 text

Once a Smart contract is created ● Only the bytecode is always available ● Sources can be optionally uploaded on Blockchain Explorers ● To interact with deployed contracts the ABI must be known ○ List all the available functions and corresponding parameters ○ Generated by the compiler as an artifact ● Contracts are immutable (!) ○ Migrate state from the old to the new contract ○ Separate data and business logic ○ Proxy pattern ● No concurrency issues - transaction are serialized within a block ● A transaction can succeed or fail

Slide 21

Slide 21 text

Solidity programming language ● Object-oriented ○ Inheritance ○ Standard types (boolean, int, string, array) ○ User-defined types (struct and enum) ○ Functions visibility and ● Statically typed ● Errors handling (revert transaction when error raised) ● Events ● Calls other contracts (any!)

Slide 22

Slide 22 text

Solidity storage simplest example

Slide 23

Slide 23 text

ERC-20 (standard token) example (from openzeppelin)

Slide 24

Slide 24 text

ERC-20: transfer (private function)

Slide 25

Slide 25 text

Introduction to Hardhat development environment ● Javascript-based ○ npm install --dev hardhat ○ npx hardhat ● Tasks oriented framework ○ Clean, Compile, Test, Run ● Plugin architecture ● Vscode integration ● Simple folders structure ○ contracts: solidity sources ○ test: mocha/chai tests ○ scripts: plain javascript automation

Slide 26

Slide 26 text

Create a new Hardhat project ● mkdir src/myproject ● npm init -y ● npm install --save-dev hardhat

Slide 27

Slide 27 text

Hardhat demo contract

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

Writing tests with Mocha ● Automated testing is more critical than ever ○ Ensure that code behave in the expected manner ○ Ensure that all the inputs are sanitized ○ Ensure errors are handled as expected ● A bug in your code can have disastrous consequences: ○ March 2023: Euler lost 200M for a bug in a function to donate dust to the protocol

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

Test state after deployment

Slide 32

Slide 32 text

Test transaction revert or succeed

Slide 33

Slide 33 text

Test the transfer happens once the lock expires

Slide 34

Slide 34 text

Deploy script (network agnostic)

Slide 35

Slide 35 text

Run HardHat test network ● Spin up a fully functional blockchain in memory that is compatible with Ethereum / EVM

Slide 36

Slide 36 text

Common security issues ● Attack vectors common also in other platforms: ○ Business logic errors ○ Rounding errors ○ Uninitialized variables ○ Unsanitized input variables ● Reentrancy attacks ○ Calling an external contract that recursively calls your contract which postpone state update ○ To avoid it, change state before calling external contracts (Check-Effects-Interactions) ○ Executing a transfer is actually calling an external contract ○ Reentrancy is not an issue if the effects are the same of calling the function N times

Slide 37

Slide 37 text

Reentrancy bug example

Slide 38

Slide 38 text

OpenZeppelin Opensource secure contracts library - openzeppelin.com ● Implementations of standards like ERC20 and ERC721 ● Role-based permission schemes (onlyOwner) ● Other secure components: ○ SafeMath (avoid overflows) ○ Payments splitter ○ Proxy (upgradable contracts) ○ Pausable ○ ReentrancyGuard

Slide 39

Slide 39 text

Ownable library example

Slide 40

Slide 40 text

Linters and static analysis tools Tools that are easily integrated into an hardhat project: ● Solhint: ○ Code style guide (mixedCase function names, underscore prefix for internal variables, …) ○ Best practices (max line length, cyclomatic complexity, …) ○ Basic security issues detection (missing visibility in a function, simple reentrancy) ● Slither: static analysis to detect vulnerable code ○ They maintain a list of hacks that could have been prevented if using the tool

Slide 41

Slide 41 text

More links ● https://ethereum.org/en/developers/docs/ ● https://docs.soliditylang.org/en/latest/ ● https://hardhat.org/docs

Slide 42

Slide 42 text

Thanks! (have you found the fish?)