Day 3 – Smart contracts

  • Rationale: What is a Smart Contract? Why Smart Contracts?
  • A Detour into the Real World: Distributed Systems Principles Revisited
  • A Detour into the Real World: Etherum, Solidity, and Remix
  • Writing Smart Contracts
  • Compiling and deploying the smart contracts
  • Use Cases: Writing a Smart Contract in Solidity with Remix
  • Use Case 1: Auction
  • Use Case 2: Lottery in Solidity
  • Smart Contracts Differently
  • Imperative Programming and Contracting
  • Logic and Rules –A Primer
  • Rule-based systems in blockchain
  • Use Case: Lottery with rules
  • Where to go from here…

Blockchain at a glance :

  • A blockchain solution is most suitable for applications with these characteristics:
  • Decentralized problems, meaning participant hold the assets and are not co-located.
  • peer-to-peer transaction without intermediaries.
  • Operate beyond the boundaries of trust among unknown peers.
  • Require validation, verification, and recording on a universally timestamped, immutable ledger.
  • Autonomous operations guided by rules and policies

http://doyouneedablockchain.com

Smart contracts

Smart contracts are neither smart nor contracts, they are : immutable, deterministic computer programs that run in an isolated fashion on the blockchain

  • Computer program : a collection of instructions that performs a specific task when executed by a computer, it is desirable that the program will eventually stop
  • Immutable : Once deployed it cannot change
  • Deterministic : The outcome of a contract is supposed to be the same for anybody who runs it
  • Isolated : The program should not affect the execution of other programs
  • Blockchain : Runs in a distributed, autonomous, trustworthy fashion

A smart contract :

  • Is a function that is deployed in the blockchain : Hence, it is an immutable piece of code (it cannot be changed once deployed)
  • Operates on the blockchain : hence it leverages the immutable recording and trust model of theblockchain
  • Is triggered by transactions on the blockchain : which provide its inputs, or by messages sent fromother smart contracts.
  • Works in the semantics and constraints of a transaction and verifies, validates and executes them

Brief history :

Nick Szabo detailed it in the 90’s before bitcoin and ”coined” the term. 1997 publication :

http://www.fon.hum.uva.nl/rob/Courses/InformationInSpeech/CDROM/Literature/LOTwinterschool2006/szabo.best.vwh.net/idea.html

Essentially an electronic coordination mechanism embedded in the blockchain

Buggy design can lead to significant failures of the distributed coordination : DAO hack, parity wallet lockup

Why would you want a smart contract ?

You might want to maintain constraints on zransactions :

  • Deliver something on a certain date
  • Ensure a particular feature
  • Review credentials

-> Introduce conditions, rules, policies into simple transactions

Encoded rules in a program, as nobody runs the server, nobody can “just” change the rules.

Visible to all -> what about secrecy

Exectued out of control of a single party -> what about bugs

Based on collective agreement on rules -> what if disagreement arises, are rules bases typically complete ?

Distributed computing principles revisited :

“A collection of independent computers that appears to its users as a single coherent system.”

“You know you have one when the crash of a computer you’ve never heard of stops you from getting any work done.” Leslie Lamport

Challenges in distributed systems :

Ethereum

Ethereum is a mainstream blockchain : Compared to BitCoin, in Ethereumsmart contracts are first-class citizens

The smart contracts are executed in the EthereumVirtual Machine (EVM) :

  • It allows to execute programs in a platform-independent fashion (like Java or .NET)
  • It is designed to be distributed: the program is executed on different nodes of the network
  • It supports a Turing-complete instruction set

The tokens are named Ether (ETH)

  • 1 Ether is 1018Wei and 109Gwei
  • 1 Ether is ca. $ 385 (Sept. 2020, https://ethereumprice.org)
  • They can be used to invoke a smart contract, to cover the mining expenses, etc.

It uses Gas to quantify the cost of executing a smart contract and set a cap to it

Creation of a smart contract

The first step is writing a smart contract : Requires a programming language

When the smart contract is ready, it is compiled by an Ethereumc compiler, producing Bytecode : The Ethereum compiler usually optimizes the code to reduce the computational load

The bytecode is a set of low-level instructions for the EVM

The Bytecode is submitted to the EVM

  • It is stored in a block of the blockchain
  • It becomes available for invocation.

Writing smart contracts

  • Solidity is the most popular language for Ethereum
  • Inspired by JavaScript, Java, and C++.
  • Solidity is specifically designed to write smart contracts for the Ethereum
  • Lityis an ongoing project which is extending Solidity and the EVM to support rule execution

Other : Vyper (Python inspired) and Bamboo

Main phases of writing a smart contract :

  • Requirement analysis
  • Design
  • Implementation
  • Testing

Waterfall / Spiral / Agile Yada Yada

Requirements analysis : The requirement analysis captures the goals and the objectives of the stakeholders, representing them as requirements

Design : takes the requirements as inputs, and define the functionalities of the software, as well as its structure and components

While designing a smart contract, it is key to identify :

  • Which data is needed for the processing (want to keep in the blockchain a minimal amount of info to reduce cost and to avoid making info public)
  • What users interacting with our contract should send and what they should receive back
  • Which calls should be charged and which should be free

Implementation :

A smart contract is a file with extension sol

it contains :

  • Data (or state variables)
  • User defined types (struct and enum types)
  • Functions
  • Function modifiers
  • Events

Declaring the smart contract

pragma solidity>=0.5.0;

contract MyFirstContract {
…
}

pragma indicates which version of the compiler is required to compile the contract. Solidity uses camel-case style for names (capital letters in declarations no space)

State variables

State variables permanently store data in the contract, it requires :

  • A name
  • A data type
  • A visibility level (default:internal)

Solidity supports :

  • Booleans (bool)
  • Signed and unsigned integers (int/uint)
  • String literals (string)
pragmas olidity>=0.5.0;

contract MyFirstContract{
    uint age;
    string name;
…
}

A key type is address : it identifies Ethereum addresses. Each user and smart contract in the blockchain has assigned an address. It is a unique identifier, contains the balance in wei. It can be used to transfer Ether between accounts or to invoke a smart contract.

Arrays and mappings

Arrays are list of variables of the same type, we can have arrays of arrays (matrices and tensors)

A mapping is a key-value store (an hash map. It allows to access the value given by the key. it is not possible to retrieve the key given the value

uint[] grades;
mapping(address =>uint) ages;
…
grades[10]; //retrieves the 11thelement
ages[0x1ED13B2108B2c43e7e6Dbf7f089205A3A3b2A69D]; //retrieves the age of 0x1ED13…

Structs and enums

The struct type allows to declare user-defined types assigning it a unique name. Invidual elements can be accessed through the dot operator.

An enumeration (enum) is a set of possible values a variable can assume, N, S, W, E. Enumeration are useful to define states of smart contracts

enumPriority {Low, Medium, High};

strcutAlert {
    Priority priority;
    string message;
}

Alert a = new Alert(Priority.High, “The sink is leaking!”)
a.priority; // retrieves the priority of a

State variable visibility

The visibility indicates who can access the state variable :

  • Public : they can be accessed inside and outside the contract
  • private : they are visible only in the contract where they are declared
  • internal : they can be accessed from the contract and extending contracts

If no visibility is declared, the visibility is set to internal

When the state variable is public, solidity generates a getter function : A special function which returns the content of the variable

uint age; // the visibility level is internal
string private name;

Functions

State variables define a state and store data, but they cannot process and modify it. Functions embeds operations as set of instructions to be executed.

To define a function :

  • A name
  • Zero or more input arguments (defined as data type + name)
  • Zero or more output parameter data types
  • A level of visibiliuty and (optionally) modifiers
function checkAge(uint age) returns(bool) {
    return age >= 18;
}
checkAge(15) // returns false

Function visibility

  • public : the function can be invoked inside and outside the contract
  • private : the function can be invoked in the contract that defined it
  • internal : the function can be invoked inside the function that defined it and in the extending contracts
  • external : the function can be invoked only from outside the contract that defines it

the default visibility level is internal

Function modifiers –payable, pure, view

Function declarations can be enriched with four modifiers:

  • Payable: allows a function to receive Ether when invoked : The payment is collected by the contract (a contract can receive and send Ether, as a user)
  • Pure: the execution of the function does depend only on the input arguments, and there are no operations on state variables (read/write)
  • View: the function can access the state variable but cannot modify them
function checkAge (uint age) public pure returns(bool) {
    returnage >= 18;
}
checkAge(15) // returns false

Constructor

The constructor is a special function which initialize the state :

  • It takes zero or more input arguments and returns zero
  • Every contract can have at most one constructor
  • It is optional (it may miss)
contract OwnedContract{

    address owner;
    constructor() { owner = msg.address; } // msg is a special object with information about the user invoking the function
    
    function whoIsTheOwner() public view returns (address) { return owner; }

}

Function modifiers –require

  • Require sets conditions which need to be satisfied to execute the function
  • When the condition is not satisfied, the function execution stops and returns a message
contract OwnedContract2 {
    address owner;
    constructor() { owner = msg.address; }
    function sayMeHi() public view returns(string) {
        require(msg.sender== owner, “Only the owner can invoke me”);
        returns“Hello!”
    }
}

Function modifiers –modifier

  • modifier can group the require statements and assign them a name
  • Functions can use then use the modifiers as the base ones (e.g. view)
contract OwnedContract3 {
    address owner;
    modifier onlyOwner {
        require(msg.sender== owner, “Only the owner can invoke me”);
    }
    constructor() { owner = msg.address; }
    function sayMeHi() public onlyOwner returns (string) { returns“Hello!” }
    function sum(uinta, uintb) public onlyOwner returns (uint){ returnsa+b; }
}

Inheritance

  • Contracts can inherit state variables, functions, etc. from other contracts
  • The inheriting contract can access the publicand internal state variables and functions
contract OwnedContractBase{
    address owner;
    modifier onlyOwner{ require(msg.sender== owner, “You are not the owner”); }
    constructor() { owner = msg.address; }
}
contract TimeContract is OwnerContractBase{
    function tellMeTime() public onlyOwner returns(uint) { return now; }
}

now is a special keyword that returns the timestamp of the current block (in UNIX time)

Tools for writing smart contracts

an IDE supporting Solidity is nice to develop – text highlighting, code completion etc.. -> Microsoft Visual Studio, Remix (includes a compiler and runtime test environments to try the smart contracts)

https://remix.ethereum.org/#optimize=false

Testing

Deploying it directly to the public Ethereum blockchain is not a good solution : it’s expensive, we need to test it thoroughly

The best way to do it is to have a local testing node. The node is diconnecgted from the rest of the blockchain network. They allow to create different users with high budget. The mining of the transactrions is almost instantaneous. Some IDE offers an internal testing nodes. We can also install it as standalone applications

Writing smart contracts –some remarks

  • Follow the Keep It Simple principle
  • Design a contract focusing on one specific operation
  • Write simple functions, keep the code readable
  • Put all the state variables at the beginning of the contract
  • Order functions in the following order: constructor, external functions, public functions, internal functions, private functions
  • Do not put code which is not strictly required in the contract
  • Control the input arguments
  • Exploit function modifiers
  • Remember that what is in the blockchainis visible to everyone
  • Make a good use of the visibility operators
  • Off-chain vs in-chain data

From the solidity file to the bytecode :

Smart contract is written, now we should compile it. We want to extract 2 elements :

  • The bytecode : a long text, starting with 0x, with all the instructions encoded in a binary format
  • The application binary interface (ABI) : a JSON file describing the interface of the smart contract : the public and external methods which can be invoked by other users/contracts

how to generate the bytecode and the ABI :

  • Remix embeds a compiler which can extract the bytecode and the ABI from the smart contract
  • We can use a framework to compile the smart contract from command line (e.g. solc)

Deploying the smart contract

the last step is deploying the smart contract : we can do that by submitting the ABI and the bytecode to the Ethereum Virtual Machine. We should also provide : who is deploying the contract, the maximum amout of gas.

If successful the operation returns an address, which can be used to invoke the smart contract methods

How to deploy the smart contract

  • Remix can deploy the smart contract to the EVM (live demo in a few minutes)
  • We can interact with the EVM API and submit the request rogrammatically. We can for example use web3-js, a Javascriptlibrary to interact with an EVM, and execute the following code:
contract = web3.eth.contract([{“constant”:false,...); // pass the ABI as the argument
contractInstance= contract.new({
                from: 0x1ED13B2108B2c43e7e6Dbf7f089205A3A3b2A69D, //submitter address
                data: 0x60806016405000823480156100057..., //contract bytecode
                gas: ”4700000”
            },function(e, contract) {
                console.log(“contract address: ” + contract.address);
});

Use case 1 : An Auction on the blockchain

  • Defining the methods
  • Implementing the first version of the contract
  • Manage the validation of the inputs with require
  • Replace name with the sender address
  • Using ether for bidding
  • Avoid uninfluential bids
  • Only the owner can close the auction
  • Give back money to the losers

USe case 2 : Lottery in Solidity

Check my github for the code : https://github.com/8rax/CAS-Blockchain/tree/master/hands-on

Programming paradigms

Imperative Programming

  • procedural, which groups instructions into procedures,
  • object-oriented which groups instructions together with the part of the state they operate on

Declarative Programming

  • functional in which the desired result is declared as the value of a series of function applications,
  • logic in which the desired result is declared as the answer to a question about a system of facts and rules,
  • mathematical in which the desired result is declared as the solution of an optimization problem

Summary

We can apply inferenceto a knowledge base to derive new information and make decisions

  • Basic concepts of logic:
  • syntax: formal structure of sentences
  • semantics: truthof sentences wrtmodels
  • entailment: necessary truth of one sentence given another
  • inference: deriving sentences from other sentences
  • soundess: derivations produce only entailed sentences
  • completeness: derivations can produce all entailed sentences


–Forward, backward chaining are linear-time, complete for Horn clauses
–Propositional logic lacks expressive power

Logic rules and blockchain

Programming through logic rules moves the smart contract development from an imperative to a declarative paradigm

–There are theoretical guarantees on the complexity of the smart contract (e.g. will the execution end?)

–There are a number of projects which are trying to combine these two worlds, e.g.


–Lity: an extension of Solidity with support to logic rules
–Wonka: a rule engine for Nethereum(a .NET library for Ethereum)

Lity

We use Lityas a good example of how blockchaincan support and enable rules


–Lity extends Solidity

  • Every Solidity program is a Lityprogram, but not the opposite
  • It combines imperative and declarative programming
  • Lity does not run on Ethereumnodes –it uses functions which are not supported
  • It requires CyberMiles, a blockchaininfrastructure developed by the CyberMilesstartup

Brax

Dude in his 30s starting his digital notepad