Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

FinTech 9-10: Smart Contracts and Decentralized...

FinTech 9-10: Smart Contracts and Decentralized Finance

Slides I used for FinTech - Financial Innovation and the Internet 2024 Fall at Graduate School of Business and Finance, Waseda University on November 8, 2024.

Kenji Saito

November 08, 2024
Tweet

More Decks by Kenji Saito

Other Decks in Technology

Transcript

  1. Digital Economics — generated by Stable Diffusion XL v1.0 FinTech

    — Financial Innovation and the Internet 2024 Fall Lecture 9-10 : Smart Contracts and Decentralized Finance Kenji Saito, Graduate School of Business and Finance, Waseda University Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.1/59
  2. This class is recorded Using Zoom For your convenience in

    reviewing the lectures Recordings are shared via Dropbox and you can ask questions with time-stamped comments Of course, students are encouraged to ask questions in class The recordings could be used for research on (online) learning Transcribed for use and anonymized Will let you know when the necessity arises Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.2/59
  3. The lecture slides can be found at : https://speakerdeck.com/ks91/collections/fintech-2024-fall Recording

    and chat text will be posted at Moodle and Discord Note, however, that chat messages are often unnoticed I have invited you all to the Discord server of the class (continued from the past years) Trial automatic transcription and summary for lectures will be posted at Discord Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.3/59
  4. Schedule (provisional) Lecture 1 10/4 Overview of FinTech (1) •

    Lecture 2 10/4 Overview of FinTech (2) • Lecture 3 10/11 Internet Technology and Governance (1) • Lecture 4 10/11 Internet Technology and Governance (2) • Lecture 5 10/18 The World of Apps (1) • Lecture 6 10/18 The World of Apps (2) • Lecture 7 10/25 Blockchain (1) • Lecture 8 10/25 Blockchain (2) • Lecture 9 11/8 Smart Contracts and Decentralized Finance (1) • Lecture 10 11/8 Smart Contracts and Decentralized Finance (2) • Lecture 11 11/15 Cyber-Physical Society and Future of Finance (1) Lecture 12 11/15 Cyber-Physical Society and Future of Finance (2) Lecture 13 11/22 FinTech Ideathon Lecture 14 11/22 Presentations and Conclusions Online presence is possible but not recommended for non-online lectures for interactivity reasons Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.4/59
  5. Last Time, We Did . . . Discussion : Imagine

    API (brief reflection on API concept) Basics of Cryptography Cryptographic hash function / Public key cryptography / digital signature Zero-knowledge proof Assignment Review Understanding Blockchain Bitcoin’s “question” and “answer” / Beaker/Newspaper Model (physical model of Bitcoin) Applicability of Blockchain Impossibility and Challenges of Blockchain Assignment — Science Fiction Prototyping Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.5/59
  6. Today’s Topics Impossibility and Challenges of Blockchain (contd.) Brief Introduction

    to Upgrading and Governance of Blockchain Assignment Review Smart Contracts and Ethereum Ethereum — Beaker/Newspaper/Machine Model Smart Contract Programming Demonstration How do we purchase digital rights to a real estate with digital currency? Assignment Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.6/59
  7. Impossibility and Challenges of Blockchain (contd.) Lecture 9-10 : Smart

    Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.7/59
  8. Scaling Out Question There is one ATM that always has

    10 people in line Sorry if you are in an advanced environment, and you don’t know what we are talking about (or even wonder what an ATM is) ;) What happens to the number of people in the queue if we add one ATM? Other conditions remain the same cf. Daisuke Yamazaki, “Rethinking Scaling Out” (in Japanese) http://www.slideshare.net/yamaz2/ss-58813038 Performance problems can be solved by adding a server ⇒ The system scales out Blockchain does not scale out in its bare form (because everyone makes and maintains a replica) Improvement is possible if you see it as a KVS (Key-Value Store) Because of the distributed KVS technology But you might lose autonomy Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.8/59
  9. Scaling Out and Blockchain 7PMVNFPG%BUBUP1SPDFTT -PBEQFS/PEF #MPDLDIBJO 1SPQFSMZEFTJHOFEEJTUSJCVUFETZTUFN In blockchain,

    the cost of maintaining data structures rises linearly as transactions increase It does not scale out Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.9/59
  10. Blockchain’s “Oneness Trap” It does not scale out Adding more

    nodes does not solve or mitigate performance challenges Must be “the world is one” to work System does not work correctly if the network is partitioned by a large-scale disasters or political change Difficulty of governance to advance technology You cannot “try something different partially, and if it works, apply it to the whole” Impossibility of governance : Agreement by the “whole” must be maintained, but the “whole” cannot be defined ⇒ Powered few changes the technology instead ⇒ Those are disadvantages of non-decentralized nature of blockchain Conversely, there are great expectations and potential for truly decentralized “record fixation device in the air” Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.10/59
  11. Incentive Mismatch Ethereum cannot survive as an application platform if

    ETH as a currency crashes and declines Supported by validators’ motivation to get ETH When the value of ETH drops, validators withdraw Can people who want to run apps (smart contracts) buy ETH to maintain the price? If ETH’s market participants are primarily app users, may be. . . (but they aren’t) The design of the raw Bitcoin is goal-consistent, but . . . In other words, “Bitcoin cannot survive if BTC declines” would be fine But as proof applications such as Proof of Existence advance, similar problems arise Either way, the future of the system depends on the interests of the miners/validators ⇒ Need to separate application platforms from currency systems That is where the recent ledger technology is going, hopefully (because many still aren’t) Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.11/59
  12. What is the True Worth of Blockchain? Roughly speaking, what’s

    the thing you can never do without blockchain? Ex1 : Digitizing the last will and testament (in a thought-experiment sense) After the death of the person, the private key used for the digital signature may no longer be a secret Can’t believe a notary saying, “it is as signed before the death” (possible collusion with malicious heir) Ex2 : Online banking passbook data as proof (for the liabilities of banks) If you download it as a CSV file, the data anyone can create is not considered as evidence Even with the digital signature of the bank, once the private key is leaked, the data can be created by anyone Prove “data digitally signed at cetain past date has not been tampered with” (instead of believing those who insist so) “The Last Will Test” is to ask them if they can do that with their blockchain A test to see if something that someone has been pitching as “it’s a blockchain” really makes sense An idea (hash-chain with proof of work) that may satisfy this true worth, combined with existing technologies around the idea is the Bitcoin blockchain Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.12/59
  13. How Well Is It Realized Today? Is there a technology

    that can pass the “last will test”? Public blockchain may pass the test while the market value of the native currency is high Defense such that it would cost a lot to tamper with When the price of the native currency drops or crashes it becomes unreliable Private ledger systems in general only insist, so they do not pass the test Mostly, “blockchain made and operated by XXX Inc.” is meaningless ← please be careful We are building new technology to make it pass the test BBc-1/BBc-2 (Beyond Blockchain One/Two; https://github.com/beyond-blockchain) (just an example) There is an inherent challenge of linkage between records and entities Includes areas that cannot be solved by engineering alone (does the public key really belong to the person?) Including the openness of the source code, it is roughly the problem of . . . “How can we trust automated mechanisms?” Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.13/59
  14. Brief Introduction to Upgrading and Governance of Blockchain Weaknesses are

    not left untouched, but continue to be improved But governance issues remain Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.14/59
  15. Enhancements to Bitcoin Blockchain Virtualization – Open Assets Protocol (no

    fork) Interpret transaction data in a specific way so that quantities independent from BTC can be defined and used Bug fix – Segregated Witness (SegWit) (soft fork) Signatures are separated from the transaction body Better privacy and conciseness – Taproot (and Schnorr signatures) (soft fork) Scripts can be partially disclosed by expressing them in Merklized Abstract Syntax Trees (kind of Merkle trees) Quickness – Payment channels (no fork) Only write to the blockchain when the channel is opened and closed, and in between you can make fast payments Conceptually, connected payment channels form a Lightning Network How do we upgrade? Soft fork : miners vote by setting a bit in a block header Wait, voting? Is it an Internet way? Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.15/59
  16. Payment Channel (Bitcoin’s case) "MJDF " #PC # #MPDLDIBJO 

    UP"#  UP#  UP"  UP" MPDLUJNF QBZUSBOTBDUJPOGFFUPNJOFS PQFODIBOOFM pOBMQBZNFOUDMPTFDIBOOFM QBZ QBZ QBZUSBOTBDUJPOGFFUPNJOFS  UP#  UP"   UP#  UP"        MPDLUJNF Alice pays fast by sending Bob transactions to pay, which are cut out of the deposit addressed to Alice and Bob Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.16/59
  17. Science Fiction Prototyping What about it? Lecture 9-10 : Smart

    Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.17/59
  18. Why Science Fiction Prototyping? What is Science Fiction? Fantasy based

    on or disguised as the thoughts and ideas of science and technology The world with existing science and technology is the real world Ex1 : Medical drama Ex2 : Economic novels The world with science and technology unknown to the real world → Fiction Ex1 : Medical drama with nano-machines Ex2 : Drama with digital currency that depreciates (my book “NEO in Wonderland”) Designing new media and putting it into society = living science fiction To work out plans for that = to write science fiction Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.18/59
  19. Assignment Review Lecture 9-10 : Smart Contracts and Decentralized Finance

    — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.19/59
  20. Assignment 4. “Smart Contracts” Please think freely with the image

    of the word “smart contract” to fantasize a specific application example, and state the application briefly That is, go ahead and write a very short science fiction Deadline and how to submit November 5, 2024 at 17:59 JST From Moodle (mandatory) (Q&A forum) So that your classmates can read your report, refer to it, and comment on it Optionally, you can also post to #assignments channel at Discord So that anyone in our Discord can read your report, refer to it, and comment on it Just plain text, and be concise, please You may want to apply Kent Beck style for abstracts (4 sentences) (problem) (why it is a problem) (startling sentence) (consequences) of a story Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.20/59
  21. Trends and Measures Trends . . . of your reports

    Measures . . . how to improve the class 24 responses out of 25 students (as of this morning; always better late than never) Your Sci-Fi stories are about . . . Time Bank / healthcare, hospital diagnostics, Personal Health Blockchain / EternalBond / Paris Agreement / index funds / smart traffic / Life Node / decision-making platform / life contract / freelancers / starting a company / art marketplace / manage entire companies / coffee distributor buys a year’s supply of Kona coffee, Autonomous Commodity Trading Contract / voting system / arbitration / The Last Dance / The Heirloom Keeper / farming / Buying a Home in Seconds / family trusts Very interesting stories! Although many of you didn’t really write stories (that’s OK, but making a story makes it more lively) Several students came up with a sort of application of the last will example That is good, because this would be an appropriate application of blockchain Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.21/59
  22. K-san’s Story (Paris Agreement) Climate change continues to worsen as

    countries struggle to meet their emissions targets under the Paris Agreement Without strict accountability, countries can easily miss the 1.5◦C goal, putting ecosystems and human health at risk Imagine if smart contracts could enforce these climate goals automatically, penalizing countries financially the instant they exceed emissions limits This would transform the Paris Agreement from a voluntary promise into an enforceable, code-based commitment, ensuring real progress in the fight against climate change ⇒ Well-formed Kent Beck style (or ) This also raises cyber-physical questions (for the next week) How do we monitor the emissions of a whole country? Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.22/59
  23. T-san’s Story (Life Node) In cases of death, the Life

    Node activates a protocol that automatically distributes assets, settles debts, and assigns any remaining obligations It collects extensive information in the final moments, including health indicators, final memories, and nearby video feeds, etc to confirm the cause of death and establish fault if applicable, streamlining the process and eliminating traditional legal procedures However, as the system has grown, so have its vulnerabilities Hackers may manipulate Life Nodes, altering data or reprogramming contracts to change liability or asset distribution These risks serve as a warning of the potential fragility within a world governed by automated contracts ⇒ Downside is well described Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.23/59
  24. S-san’s Story (life contract) In the future, every citizen will

    receive a “life contract” at birth / This is a smart contract that determines a person’s life path based on data-driven predictions / The contract includes “if-then” conditions that guide the person’s behavior based on their abilities, health and contribution to society / For example, if a high aptitude for a specific career is identified, then the contract defines an educational pathway that supports the aptitude / In this way, the person’s potential can be optimally promoted / The contract aims to optimize human potential but at the same time restricts personal choice, leaving people frustrated One day, a citizen discovers a flaw in her contract and realizes that it can be changed, allowing her to regain control of her life / She breaks away from modern society and begins a life underground and helps others to break free from their shackles / The movement grows into a national uprising in which citizens demand their freedom and fight against the state’s control mechanisms / The previously orderly system is on the verge of collapse, while a civil war threatens, in which people defend their freedom against the system / The society threatens to tear itself apart in a conflict between control and self-determination ⇒ (reminds me of) GATTACA! (1997 American dystopian Sci-Fi film) Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.24/59
  25. M-san’s Question Can future blockchain governance models support selective changes

    or updates in certain areas without requiring unanimous agreement? For instance, is it possible to have separate “mini-governance” systems within a blockchain that allow for localized alterations without impacting the entire network? ⇒ Smart contracts (or DAO) can work that way DAO is technically a set of smart contracts that can be altered using indirect reference to the code by voting with so-called governance tokens That defines how one blockchain application behaves I also think that future blockchain-like system can be more truly decentralized so that authorities are distributed (like BBc-2 we are working on, which will be an inter-connected set of self-governed private ledger systems) Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.25/59
  26. Smart Contracts and Ethereum Ethereum — Beaker/Newspaper/Machine Model Smart Contract

    Programming Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.26/59
  27. Overview of Ethereum Blockchain and State Transition EVM (Ethereum Virtual

    Machine) Ethereum explained by a physical model Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.27/59
  28. What is Ethereum? Vitalik Buterin, “Ethereum White Paper: A NEXT

    GENERATION SMART CONTRACT & DECENTRALIZED APPLICATION PLATFORM” Applying blockchain technology Block interval : at most 1 block in a 12-second time slot Put a programming language on it Turing complete = can emulate a universal Turing machine (well that’s almost a definition of a programming language) Foundation for DApps (applications that automate the center) An attempt to make the current financial and monetary system obsolete That’s what smart contracts are all about Automate digital asset transfers and their state transitions Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.28/59
  29. Blockchain and State Transitions TUBUF FYUFSOBMBDUPST BDDPVOU &7.DPEF &UIFSˠHBT JOWPLF

    DPOUSBDUDPEF NFTTBHFPSBOFXBVUPOPNPVTPCKFDU EBUBFYDIBOHFEBNPOHBDDPVOUTPS&UIFS TUPSBHF TUBUF` TFUPG USBOTBDUJPOT EJHJUBMTJHOBUVSF &7. IVNBO GPSFYBNQMF Blockchain = Run of a state machine (state transition system) = Operation of a computer Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.29/59
  30. Glossary Ether (ETH) Native currency of Ethereum (compensation for validating)

    External Actor A real person/entity who can digitally sign, having an account EOA : Externally-Owned Account Autonomous Object (internal actor) ← or rather, automated object Operates autonomously within the system, and has an account That said, if you don’t send a message, it won’t work (and validators run them) Account Has an Ether balance, and can have storage (state) and EVM code EVM Code Smart contract program Smart contract = application program on Ethereum = intelligent contract Authenticity is ensured by being recorded in blockchain Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.30/59
  31. EVM : Ethereum Virtual Machine TUBUF FYUFSOBMBDUPST BDDPVOU &7.DPEF &UIFSˠHBT

    JOWPLF DPOUSBDUDPEF NFTTBHFPSBOFXBVUPOPNPVTPCKFDU EBUBFYDIBOHFEBNPOHBDDPVOUTPS&UIFS TUPSBHF TUBUF` TFUPG USBOTBDUJPOT EJHJUBMTJHOBUVSF &7. IVNBO GPSFYBNQMF BVUPOPNPVT PCKFDU Triggered when an automated object receives a message, performs a contract, and changes state Gas (computing resource) must be bought for the following reasons To avoid infinite loops and control congestion (base fee; burnt), and compensate the block proposers (priority fee) Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.31/59
  32. Beaker/Newspaper/Machine Model (1/7) Physical model of how Ethereum works today

    cf. PROOF-OF-STAKE (POS), Eth2Book Preconditions About beakers (containers for native cryptocurrency) Unlike Bitcoin, beakers are not created anew for each transaction, but are created as a set with the private key and placed at a specific address for each Private key opens the stopper, and the liquid is injected somewhere (no need to empty it) The pour spout is always open, allowing liquid to be injected About Liquid The liquid is used as fuel for the mechanical calculator to run automatically About the machine (mechanical calculator) We use the world’s one and only mechanical calculator It has a vast memory and works by inserting punch cards and setting a beaker Programmers cannot type directly into a punch card Use a service that compiles human-readable code into punch cards Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.32/59
  33. Beaker/Newspaper/Machine Model (2/7) Transactions Calculator-assisted processing is called a transaction,

    and there are three types: (1) Set source and destination beakers and move the fuel by the specified amount (2) Set up a beaker with a card deck describing the application program and initial parameters, and write the program in memory (deploy) · The calculator also executes the initialization code for that program to set up the application (3) Set up a card and beaker and use it to call a program in memory Signed newspaper article The person wishing to execute their transaction distributes copies of the following information as their signed article to the validators described later Address of the beaker from which the fuel is injected (signed so we know it is you) Punch card contents Amount of fuel that may be given to the validator running the calculator (priority fee) and the maximum amount of fuel that may be used The articles of the executed transactions make up one page of the newspaper Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.33/59
  34. Beaker/Newspaper/Machine Model (3/7) Fuel consumption Mechanical calculator does not run

    at a constant fuel consumption rate; it runs worse (requires more fuel) when transactions are crowded and better (requires less fuel) when not One unit of calculation that consumes fuel is confusingly called gas Newspaper page size is also weighed in gas (Total gas usage for executed transactions) The standard paper size is 15 million gas and the maximum size is 30 million gas If the page standard is exceeded, the fuel consumption of transactions will be worse on the next page, and if below the standard, the fuel consumption of the next page will be better People like to use the calculator when they can get the most mileage, so we hope this will help regulate congestion (what do you think?) Move to the next method with sufficiently accumulated costs of PoW Method described on the next page and beyond cannot be started from zero Ethereum has moved from PoW to the next scheme in September 2022 Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.34/59
  35. Beaker/Newspaper/Machine Model (4/7) Deposits and Validators Fuel is weighed in

    units of Gwei where 1 Giga Gwei is ETH A validator is an entity or person who has deposited 32 ETH(!) into the system Validators are required to do the following tasks, and if they do them diligently, they will increase the ETH deposit, and if they do them sloppily, they will forfeit the ETH deposit · The maximum value that counts as a deposit is 32 ETH (actual amount can be more) · Validator is expelled for falling below 16 ETH Slot and Newspaper Page (block) proposal Time is separated by slots at 12 second intervals In each slot, one of the validators wins a raffle (in the usual sense) Winning validator lets selected articles actually run on the calculator (if they fail to run, the articles are discarded), composes a page of the newspaper and proposes it to everyone If the validator skips it, the page was not made in that slot Other validators that received the page will do confirmation calculations Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.35/59
  36. Beaker/Newspaper/Machine Model (5/7) Epoch and Finalization 32 slots as 1

    epoch (384 sec) Validator is assigned to a committee for one of the slots in each epoch (beacon committee) to testify (sign) the correctness of the page proposed for that slot The first slot in an epoch is called the checkpoint Validator specifically attests to the checkpoints of two consecutive epochs If testimonials from validators that amount ≥ 2 3 of the total deposit are obtained The latest checkpoint is justified The second latest checkpoint is finalized (the pages up to it are their final versions) Sync Committee Every 256 epochs, 512 validators are selected as a committee to testify for the pages This will help non-validators to consider the correctness of the pages Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.36/59
  37. Beaker/Newspaper/Machine Model (6/7) What if the sequence of pages in

    an epoch branches? Since everyone does what they do as they please, divergence may occur For example, one validator might think that no block was proposed in the previous slot In that case, we will use the history with the most testimonials weighed by the deposits (modified Nakamoto consensus ← the history with the largest cost is the most correct) Confiscation and expulsion If you are selected for a sync committee and do not respond, you forfeit from your deposit If you do not testify at checkpoints, you forfeit from the deposit Failure to finalize a page for more than 4 epochs will result in forfeiture from the deposits attested to the minority side (no reward for the majority side in the meantime) Hopefully this will make it easier for the majority side to get ≥ 2 3 of the deposits If you propose more than one page in the same slot, attempt to alter the history, or double-vote, you will be banned after forfeiting your deposit (after 36 days) If there are multiple validators who misbehaved at the same time, we will consider possibility of a conspiracy and confiscate them so badly Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.37/59
  38. Beaker/Newspaper/Machine Model (7/7) Rewards Reward for working diligently as a

    validator is proportional to the amount of your deposit and inversely proportional to the square root of everyone’s total deposit Delay in testifying will reduce the amount of your reward Rewards are given per epoch Way of drawing lots or electing validators to committees (existing metaphor) Uses a conceptual DAO (RANDAO) to generate random numbers This is a deck of playing cards placed in the memory of the calculator Validator proposing a page shuffles the deck once during the proposal Takes XOR of the digest of the signature on the data based on the epoch number and the existing RANDAO Each time a page is generated, the deck is shuffled one after the other, so that it accumulates enough randomness It is random yet deterministic since everyone is looking at the same deck The deck at the end of each epoch is used to determine the proposers and committee members after 2 epochs Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.38/59
  39. Smart Contract Programming Programming language Characteristics and challenges Lecture 9-10

    : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.39/59
  40. Programming Language EVM interprets bytecode (instruction set for virtual machines

    or interpreters) EVM is a stack machine (stack calculator) (see Lecture 5-6) Programmers don’t usually program in bytecode or machine languages Requires compilers for other, high-level languages High-level language : human-readable/writable language On the other hand, languages close to machines are called low-level languages . . . We may be scolded by artificial intelligence in the near future ;) Examples : Solidity — JavaScript-like language Current primary language Vyper — Python-like language LLL — Lisp-like language Fe — Rust-like features with reference to Vyper? ← NEW! Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.40/59
  41. Solidity Sample Code (this is a high-level language!) pragma solidity

    >=0.4.18 <0.6.0; contract IndivisibleAsset { /* transfer ownership of non-divisible assets */ string public _name; string public _symbol; uint256 public _quantity; address public _owner; constructor(string name, string symbol, uint256 quantity) public { _name = name; _symbol = symbol; _quantity = quantity; _owner = msg.sender; } function transfer(address to) public returns (bool) { require (_owner == msg.sender); _owner = to; return true; } } Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.41/59
  42. Another Solidity Sample Code (snippet) . . . function transfer(address

    to, uint256 value) public returns (bool) { balances[msg.sender] = balances[msg.sender] - value; balances[to] = balances[to] + value; return true; } . . . This can be the core of a (not-so-secure) token contract Without considering overflow/underflow A token contract typically manages the balances of all users Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.42/59
  43. Features of Programming Language Solidity JavaScript-like Object-oriented Describe a contract

    as a template (type or class) Constructor is called during deployment Deploy here means to deploy the contract to the blockchain Decides what parameters to pass to the constructor upon deployment Conforms to Ethereum programming model Deployed contract is a specific entity (instance) Has an account (identified by the address, just like a human user) Has storage and ETH balance Can send messages to other contracts Model where deployed contracts are manipulated by sending messages On the assumption that the authenticity of the code that responds to the message is guaranteed Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.43/59
  44. Characteristics and Challenges Characteristics Execute the program during the block

    validation process, and reflect the results in the “world state” Redundant verifiers Closed within the state of blockchain (maintained by the verifiers) This design is consistent in the Ethereum system Challenges I/O commands cannot be issued from within the program Not affected by the outside world other than external actors who send signed messages ⇒ ex. Data from sensors cannot be read directly (problem of an oracle) Not able to directly affect the outside world ⇒ ex. Cannot send commands to the motor to turn it on/off Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.44/59
  45. Demonstration Automated Escrow An attempt to automate real-estate brokerage, banking,

    and Legal Affairs Bureau (or judicial scrivener) Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.45/59
  46. ex. Automated Escrow to Purchase Land (automation of centers) %FpOFEb"JS`

    SFUVSOMBOE 1VSDIBTF$POUSBDU -BOE"TTFU MBOE EFQPTJU USBOTGFSMBOESJHIUTUPCVZFS USBOTGFSQBZNFOUUPTFMMFS QBZNFOU EFQPTJU %JHJUBM5PLFO DSFBUFBOEpYJOUIFBJS FJUIFSDBOEPUIJT DSFBUFBOEpYJOUIFBJS DBOGSFFMZKPJOBOEMFBWF DBOGSFFMZKPJOBOEMFBWF 4FMMFS #VZFS JOUFSOBM TUBUF SFUVSONPOFZ TFUUMF USBOTGFS JOUFSOBM TUBUF USBOTGFS JOUFSOBM TUBUF     1. Purchase contract is fixed in the air to prevent taking away of land or money (both parties can verify the contract) 2. Deposit land rights and purchase money in the contract (if they change their minds, they can take them back) 3. When settled (anyone can do it if both right and money are deposited), the rights and money for the property are transferred simultaneously Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.46/59
  47. For Demonstrations, We Use Brownie, a Python-based development and testing

    framework for smart contracts on EVM https://eth-brownie.readthedocs.io/en/stable/ Today, we will use the Python interpreter environment it provides And infura.io that provides accesses to Ethereum (main and test) networks https://infura.io Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.47/59
  48. A Little Preparation If you have problems with newer versions

    of Python 3, try Python 3.9 (3.9.18) Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.48/59
  49. Sample Code and Demo git clone from GitHub $ git

    clone https://github.com/ks91/sample-smart-contracts.git Follow README 1. Setup a sample token project with brownie Brownie is a Python-based Ethereum programming and test environment Javascript-based one is called Truffle, and an Ethereum remote procedure call client is called Ganache See? Engineers are fun people to work with! 2. Copy the content of contracts, scripts and tests directories of this sample project into the corresponding directories of the token project 3. Compile 4. Test Today, I will demonstrate manually the test for automated escrow Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.49/59
  50. settle() from OneTimeEscrow function settle() public returns (bool) { require(_token_.balanceOf(address(this))

    >= _price_); /* ’this’ means this contract */ require(_asset_.getOwner() == address(this)); _token_.transfer(_seller_ , _price_); _asset_.transfer(_buyer_); emit Settled(); /* event log */ return true; } Just to introduce the settle() part from the sample code Only if both the price and the asset are deposited with the contract, It transfers money to the seller and asset to the buyer Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.50/59
  51. Open console and connect to Sepolia testnet Use brownie console

    >>> network.disconnect() # disconnect from the default, simulated environment of Ethereum >>> network.connect(’sepolia’) >>> len(accounts) 0 >>> accounts.add(paste the hexadecimal string of the private key here) <LocalAccount object ’hexadecimal string of the account’> >>> accounts[0].balace() Here is the ETH balance of the account We set up two accounts Once you have created multiple accounts, you can try to transfer ETH, for example as follows >>> accounts[0].transfer(accounts[1], "1 ether") But before that, you may want to feed the accounts with Sepolia ETH from some public faucet Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.51/59
  52. Test Code (1) from brownie import * import pytest def

    test_deploy_and_settle(Token, IndivisibleAsset, OneTimeEscrow): asset = accounts[0].deploy(IndivisibleAsset, "5322 Endo", "mˆ2", 300) token = accounts[0].deploy(Token, "Test Token", "TEST", 18, "1000 ether") Deploying token and asset contracts The above is just the test code as it is, so in the console we will just type the inside of the function First, let’s do seller = accounts[0] and buyer = accounts[1] for readability Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.52/59
  53. Test Code (2) token.transfer(accounts[1], 300, {’from’: accounts[0]}) escrow = accounts[0].deploy(OneTimeEscrow,

    token, accounts[1], asset, accounts[0], 300) Sending 300 coins from seller (accounts[0]) to buyer (accounts[1]) to prepare Because the buyer has to cast a transaction that pays 300 coins Deploying Escrow Contracts Buyer is accounts[1], seller is accounts[0], and the price is 300 coins Since we are using the sample arguments of the baked Token as they are, 300 coins is actually a very small unit, like wei in ETH Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.53/59
  54. Test Code (3) token.transfer(escrow, 300, {’from’: accounts[1]}) asset.transfer(escrow, {’from’: accounts[0]})

    assert token.balanceOf(accounts[0]) == 999999999999999999700 assert token.balanceOf(accounts[1]) == 0 assert token.balanceOf(escrow) == 300 assert asset.getOwner() == escrow Buyer (accounts[1]) deposits 300 coins in escrow, and Seller (accounts[0]) deposits the asset in escrow assert tests a statement, and fails the test if it turns out to be false But we are in console (not doing an automated test), so we just see the values Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.54/59
  55. Test Code (4) escrow.settle({’from’: accounts[0]}) assert token.balanceOf(accounts[0]) == 1000000000000000000000 assert

    token.balanceOf(accounts[1]) == 0 assert token.balanceOf(escrow) == 0 assert asset.getOwner() == accounts[1] Calling settle() and closing the transaction In this code, it is called by seller (accounts[0]), but it is OK to call from either side Let’s see some transactions on an Ethereum Sepolia testnet explorer Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.55/59
  56. Authenticity of Contracts Anyone can participate in block validation and

    contract execution as a verifier ⇒ Everyone has access to the contract code It is in principle verifiable that the correct contract is being executed I/O is outside blockchain → this is possible without revealing the entirety of the agreement True worth of smart contract is that everyone can confirm that “the correct contract was executed”? Program code and its execution results as “record whose contents and existence cannot be denied by anyone” But Ethereum’s method should not be the only one There are many issues including how to manage the contracts’ life cycles We have already talked about The DAO Incident Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.56/59
  57. Assignment Lecture 9-10 : Smart Contracts and Decentralized Finance —

    FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.57/59
  58. Assignment 5. “Artificial General Intelligence” AGI (Artificial General Intelligence) is

    capable of performing all the intellectual activities possible for humans at a level equal to or better than that of humans This will mean the replacement of intellectual labor, and will also accelerate the replacement of physical labor because of the precise control of robots, as well as any other major changes in society Suppose that AGI will appear in 2026 (cf. Anthropic’s CEO’s blog) Please briefly describe the changes that could occur in the area of finance by 2030 Deadline and how to submit November 12, 2023 at 17:59 JST From Moodle (mandatory) (Q&A forum) So that your classmates can read your report, refer to it, and comment on it Optionally, you can also post to #assignments channel at Discord Just plain text, and be concise, please Lecture 9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.58/59
  59. Have a Nice Weekend, and See You Next Week! Lecture

    9-10 : Smart Contracts and Decentralized Finance — FinTech — Financial Innovation and the Internet 2024 Fall — 2024-11-08 – p.59/59