Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Build your first smart contract

Build your first smart contract

In the world of software development, blockchain technology is gaining more and more interest. Among the different implementations, Ethereum is one of the most used blockchains in the world thanks to its flexibility and the possibility of executing code through smart contracts. This talk will present the fundamental concepts of the Ethereum architecture and the functioning of smart contracts. Next, it will show how to use the HardHat framework to develop, test and publish decentralized applications on the EVM blockchain.

GDG DevFest Pisa - 1st April 2023

Giovanni Toraldo

April 01, 2023
Tweet

More Decks by Giovanni Toraldo

Other Decks in Technology

Transcript

  1. About me DevOps Engineer @ Hyland • Alfresco BDU •

    Ansible playbook • Helm charts Open Source enthusiast Medieval reenactor during the weekends 🎯 Twitter: @gionn
  2. 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
  3. Total crypto market cap, a result of 12,301 cryptocurrencies tracked

    across 666 exchanges. https://www.coingecko.com/en/global-charts
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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!)
  14. 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
  15. Create a new Hardhat project • mkdir src/myproject • npm

    init -y • npm install --save-dev hardhat
  16. 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
  17. Run HardHat test network • Spin up a fully functional

    blockchain in memory that is compatible with Ethereum / EVM
  18. 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
  19. 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
  20. 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