$30 off During Our Annual Pro Sale. View Details »

FinTech Lecture 11 : Further Smart Contracts

FinTech Lecture 11 : Further Smart Contracts

Slides I used for Lecture 11 of FinTech - Financial Innovation and the Internet 2021 Fall at Graduate School of Business and Finance, Waseda University on December 10, 2021.

Kenji Saito
PRO

December 08, 2021
Tweet

More Decks by Kenji Saito

Other Decks in Technology

Transcript

  1. Changes in the economy and labor.
    FinTech — Financial Innovation and the Internet 2021 Fall
    Lecture 11 : Further Smart Contracts
    Kenji Saito, Graduate School of Business and Finance, Waseda University
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.1/36

    View Slide

  2. This class is recorded
    Camera ON is recommended, but not required
    Zoom names : change your names to whatever you want to be called
    Please link your Zoon names to your real names in your reports
    Zoom names are important, because if you choose to be called by your real names, still I don’t know whether I
    should call you by your given or family names
    You do need to speak often (we are going to have a lot of dialogues)
    We will use breakout rooms a lot, but those won’t be recorded unless you do it yourselves (need to be allowed)
    ↑ Well, not so much so far. . . because we are familiarizing ourselves with new concepts first
    Later on, hopefully we will move to a stage with a lot more dialogues
    Keep your Zoom client updated!
    We might use latest features
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.2/36

    View Slide

  3. The lecture slides can be found at :
    https://speakerdeck.com/ks91
    Recording and chat text will be posted at Moodle and Discord
    Trial automatic transcription will be posted at Discord
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.3/36

    View Slide

  4. Schedule (provisional)
    Lecture 1 9/24 Overview of FinTech (1) •
    Lecture 2 10/1 Overview of FinTech (2) •
    Lecture 3 10/8 Internet Technology and Governance (1) •
    Lecture 4 10/15 Internet Technology and Governance (2) •
    Lecture 5 10/22 Internet Governance and the World of Apps •
    Lecture 6 10/29 The World of Apps - continued •
    Lecture 7 11/12 Basics of Cryptography and Blockchain •
    Lecture 8 11/19 Blockchain •
    Lecture 9 11/26 Blockchain and Smart Contracts •
    Lecture 10 12/3 Smart Contracts •
    Lecture 11 12/10 Further Smart Contracts •
    Lecture 12 12/17 DeFi : Decentralized Finance
    Lecture 13 1/7 Cyber-Physical Society and Future of Finance
    Lecture 14 1/14 FinTech Ideathon
    Lecture 15 1/21 Presentations and Conclusions
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.4/36

    View Slide

  5. Last Week, We Did
    . . .
    Impossibility and Challenges of Blockchain
    Brief Introduction to Upgrading and Governance of Blockchain
    Assignment Review — Science Fiction Prototyping
    Smart Contracts and Ethereum
    Just started
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.5/36

    View Slide

  6. Today’s Topics
    Overview of Ethereum
    With demo
    Smart Contract Programming
    With demo
    Understanding Applications of Blockchain
    Assignment
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.6/36

    View Slide

  7. Overview of Ethereum
    Blockchain and State Transition
    EVM (Ethereum Virtual Machine)
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.7/36

    View Slide

  8. What is Ethereum?
    Vitalik Buterin, “Ethereum White Paper: A NEXT GENERATION SMART
    CONTRACT & DECENTRALIZED APPLICATION PLATFORM”
    Applying blockchain technology
    Targeted average block interval : 15 seconds
    Put a programming language on it
    Turing complete = can emulate a universal Turing machine (roughly speaking, a computer)
    (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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.8/36

    View Slide

  9. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.9/36

    View Slide

  10. Glossary
    Ether (ETH)
    Native currency of Ethereum (compensation for mining)
    External Actor
    A real person/entity who can digitally sign, having an account
    EOA : Externally-Owned Account
    Autonomous Object (internal actor)
    Operates autonomously within the system, and has an account
    That said, if you don’t send a message, it won’t work (and miners 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 written in blockchain
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.10/36

    View Slide

  11. 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 autonomous object receives a message, performs a contract, and changes state
    Gas must be supplied for each execution step (to avoid an infinite loop and to compensate the miner) (partially burnt)
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.11/36

    View Slide

  12. Demonstration
    Using 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
    Let’s demonstrate sending some fractions of Ether between accounts
    Both on memory (simulated network) and on a test network
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.12/36

    View Slide

  13. Technical Challenges of Blockchain
    Non real-time (probabilistic behavior)
    Difficulty of secrecy (guarantee of verifiability to all)
    Oneness (distribution vs. replication)
    Not scalable (do not scale if replicated to all participants)
    Harder governance of evolution (can’t change if everyone needs to be united)
    Incentive mismatch (discrepancy of motivations for participation in infrastructure and applications)
    Supported by the value of the native currency (crash would stop all applications)
    ⇒ Can be solved by redesigning it zero-base
    Actually in progress (ex. BBc -1)
    Problem with many ledgers is that they are not redesigned zero-base
    ex. Hash-chains without proof of work can be tampered with
    ex. Talking about “newspaper model”, you can’t prove anything by publishing articles in company newsletters
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.13/36

    View Slide

  14. Ethereum’s Approach (solutions blockchain-way)
    Non real-time (probabilistic behavior)
    ⇒ Towards transaction finalization mechanism (Casper)
    Difficulty of secrecy (guarantee of verifiability to all)
    ⇒ ZoE (Zcash on Ethereum)
    Oneness (distribution vs. replication)
    Not scalable (do not scale if replicated to all participants)
    ⇒ Sharding, Plasma (multi-layered)
    Harder governance of evolution (can’t change if everyone needs to be united)
    ⇒ Benevolent Dictator For Life (BDFL) (with bitter smile ;) )
    Incentive mismatch (discrepancy of motivations for participation in infrastructure and applications)
    Supported by the value of the native currency (crash would stop all applications)
    ⇒ Will people who want to run the apps buy Ether and support?
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.14/36

    View Slide

  15. BBc-1’s Approach (solutions non-blockchain-way)
    Non real-time (probabilistic behavior)
    ⇒ No probabilistic behavior before transaction commits
    Difficulty of secrecy (guarantee of verifiability to all)
    ⇒ Transaction content is kept secret outside the domain, and can be
    encrypted inside
    Oneness (distribution vs. replication)
    Not scalable (do not scale if replicated to all participants)
    ⇒ Scale-out on a domain-by-domain basis, intra-domain DHT in the future
    Harder governance of evolution (can’t change if everyone needs to be united)
    ⇒ Autonomy by domain (don’t care about intra-domain protocols)
    Incentive mismatch (discrepancy of motivations for participation in infrastructure and applications)
    Supported by the value of the native currency (crash would stop all applications)
    ⇒ No native currency, proof of context work by mutual aid
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.15/36

    View Slide

  16. Smart Contract Programming
    Programming language
    Characteristics and challenges
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.16/36

    View Slide

  17. Programming Language
    EVM interprets bytecode (instruction set for virtual machines or interpreters)
    EVM is a stack machine (stack calculator) (see Lecture 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.17/36

    View Slide

  18. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.18/36

    View Slide

  19. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.19/36

    View Slide

  20. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.20/36

    View Slide

  21. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.21/36

    View Slide

  22. Applications and Demonstrations :
    Automated Escrow
    An attempt to automate real-estate brokerage, banking, and Legal Affairs Bureau
    (or judicial scrivener)
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.22/36

    View Slide

  23. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.23/36

    View Slide

  24. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.24/36

    View Slide

  25. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.25/36

    View Slide

  26. Open console and connect to Ropsten testnet
    Use brownie console
    >>> network.disconnect() # disconnect from the default, simulated environment of Ethereum
    >>> network.connect(’ropsten’)
    >>> len(accounts)
    0
    >>> accounts.add(paste the hexadecimal string of the private key here)

    >>> 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 Ropsten ETH from some public faucet
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.26/36

    View Slide

  27. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.27/36

    View Slide

  28. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.28/36

    View Slide

  29. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.29/36

    View Slide

  30. 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 Ropsten testnet explorer
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.30/36

    View Slide

  31. 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 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.31/36

    View Slide

  32. Understanding Applications of Blockchain
    In one single diagram
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.32/36

    View Slide

  33. Understanding Applications of Blockchain
    Token
    Smart Contract Provenance
    Fungible
    Non-redeemable
    Fungible
    Redeemable
    Non-fungible
    Redeemable
    Non-fungible
    Non-redeemable
    Certifying
    Identifying
    payment
    ID card
    security token
    last will
    logistics
    insurance claim
    Tracking
    Sensing
    fiat money
    crypto-pet
    Proves you are the one
    since you can handle
    the private key?
    Transfers numerical
    representations of
    debt / asset?
    Maintains authenticity
    of registered code, data
    and resulted states?
    (Authority) issues
    certificates about
    some content?
    Updates records about
    sustained presences?
    Is data still valid even
    if the subject is gone?
    Many think we implement token and provenance apps with smart contracts, but. . .
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.33/36

    View Slide

  34. Assignment
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.34/36

    View Slide

  35. Assignment 5. “The DAO Attacked”
    In 2016, an autonomous decentralized investment fund “The DAO” leaked
    3.5M ETH in an attack that exploited a bug in a smart contract, but this
    incident was made to look like it never happened, by the hard fork of Ethereum
    (1) Choose between A) public policy position (of a country with many victims), or
    B) management position at The DAO
    (2) Discuss briefly what would have been the best thing to do from your position
    Deadline and how to submit
    December 14, 2021 at 17:59 JST
    From Moodle (mandatory) — this time, we are using a 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
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.35/36

    View Slide

  36. See You Next Week!
    Have a nice weekend!
    Lecture 11 : Further Smart Contracts — FinTech — Financial Innovation and the Internet 2021 Fall — 2021-12-10 – p.36/36

    View Slide