© Shilpa Karkeraa 2020
S. KarkeraaUnlocking Blockchain on Azurehttps://doi.org/10.1007/978-1-4842-5043-3_5

5. Smart Contracts

Shilpa Karkeraa1 
(1)
Mumbai, India
 
Let’s start with two definitions:
  • Contract – A written or spoken agreement, especially one concerning employment, sales, or tenancy, etc., that is intended to be enforceable by law.

  • Smart Contract – A programmable digital agreement that may be self-enforcing or self-executing or both, based on the nature of the agreement and transaction, made directly between involved stakeholders over a blockchain network.

Before drilling down into smart contracts, let’s understand their placement in the blockchain stack. Recapping the last couple of chapters, view Figure 5-1 bottom to top.
../images/474923_1_En_5_Chapter/474923_1_En_5_Fig1_HTML.jpg
Figure 5-1

Layers of the blockchain ecosystem

The lowermost layer, the nodes layer, contains the machines/nodes involved in the blockchain. These machines may be physical servers, mobile phones, cloud instances, or virtual machines. Several nodes may use the same machine on different ports, or every node might have its own representation over a smartphone. This depends on the configuration of the node representing the user. This corresponds to the Chapter 2 elements of an Azure Workbench, where the architect can decide the number of instances and event registers among the instance stakeholders.

The second layer, the linkages layer, contains the hybrid ledgers, which provide different configurations of the network connectivity—private or public, permissioned or open, on cloud, off cloud, or a combination of it. As explained in Chapter 3, where we learned the types of encryptions, distributions, and other aspects, the linkages layer is governed by the form of consensus being used across the network. Blockchain frameworks such as Hyperledger, Ethereum, Corda, and others may be used based on the nature of the blockchain application.

The topmost layer, the logical layer, consists of the programmable smart contracts, which are closest to the user side of things. The conditions of the smart contract will auto-govern the transactions in the blockchain formulated with the other two layer configurations. Correlate this with existing centralized stacks of backend (containing servers, databases) to front end (UX, HTML, JavaScript). Similarly, smart contracts form the front-end elements that are written with programming languages such as Solidity, Vyper, Serpent (closer to the backend operations), and LLL. However, these languages are fairly new and are continuously evolving based on application demands.

Thus, in this chapter, the focus will be on the underlying logic used by these programming languages to design and develop intuitive smart contracts in various decentralized apps. So, let’s review how a smart contract can be used in our real lives, which is not limited to machines, computers, laptops, and smartphones.

Real-life Smart Contracts

Houses, homes, properties, buildings, and bungalows—shelter is a basic necessity for all humans. General legal contracts are made over every transaction to gain shelter, be it buying a house or renting a home or leasing shops or investing in properties. Legal contracts have been traditionally done on paper, though recently have moved into digital forms that are governed by the law. Civil courts are responsible for resolving disputes over breaches of contract so as to execute rightful actions. This process is a long iteration of various stakeholders fighting to have a just outcome for several details.

Case Purchase of Property

Issues with Traditional Methods: The buyer is interested in purchasing an apartment in a building. The building is due to be completed by 2020, as promised by the builder. The buyer initiates payment installments as per the builder’s terms and conditions, noted when signing the contract. At one point, 80 percent of the cost has been paid, and suddenly the builder is unable to deliver even by 2021. This causes a severe loss of time and money as well as instability for the buyer. This situation has inconvenienced thousands of home buyers. To resolve it, lawsuits, negotiations, and a lot of court visits are required to discuss the legal terms and conditions and the different inferences and pleas over the contextual meaning of the contract. After a long iteration of months and sometimes years, justice may or may not be served.

Now, imagine the blockchain version of this ecosystem. The house is an asset of the owner. It is digitized not just through a paper or an online contract but also in the form of a digital lock and key to the house. This security system protecting the house could be a node in the blockchain. When the buyer buys the house from the builder, the node access is provided to the rightful owner based on the fulfillment of the conditions of the smart contract, enabling physical access as well. Actions taken by the stakeholders get auto-triggered to make timely installments from the buyer and timely services by the service providers (builder); ownership can be transferred in real time upon making the final payment, and the node access of the house is transferred to the buyer. The deal is decentralized and witnessed by other node stakeholders on the chain. Also, the audit trail and the state of records are maintained transparently on the blockchain throughout.

This leads to a completely transparent process that records every state of the transactions involved and automates contracts based on executable clauses. The end users experience a seamless agreement that is tamper-proof, immutable, and auto-enforceable.

Smart Contracts Solution in Real Estate : The buyer initiates interest in a digital asset (house-key node that is linked to the physical asset through IoT and blockchain setup) on a blockchain. This blockchain is a hybrid ledger consisting of nodes representing builders, housing groups, brokers, and buyers on a public chain (similar to an e-commerce platform but a different arrangement since the rules of the platform are not governed by just one centralized body). The participants on the chain are independent entities and can participate in the on-chain activities. In case a buyer, on reading the information from the public ledger of real estate, is interested in a property from a housing group, a private permissioned chain is formed with the relevant stakeholders. In this private chain, the stakeholders decide on the conditions on a smart contract and agree on the automatic execution of the conditions as per the smart contract. So, in this case, when a buyer pays installments through the private ledger, the stake of the house node is being transferred proportionately. This is exactly what can be programmed. On completion of payment, the digital asset is transferred in real time to the owner without any delay. This is unlike the traditional method of a check, the funds from which may not get transferred for days, and the building company may take some time to figure out the exact status of the funds transferred into their account. Alternatively, the other condition that can be programmed in the smart contract could be regarding the what to do upon failure of delivery of the house by the builder. See Figure 5-2.
../images/474923_1_En_5_Chapter/474923_1_En_5_Fig2_HTML.jpg
Figure 5-2

Public and private chain setup for real estate. Upon consensus over the rules of the smart contract on the private ledger, the key access is transferred

For example, let’s observe the following scenario: It is pre-programmed that by March 1, 2020, if the key has not been transferred to the owner due to non-completion of delivery in spite of full payment by buyer, the builder must start paying penalty/rental charges. This condition then gets auto-executed without any discussion. The consensus of the chain adheres to the smart contract, and the transactions are made accordingly in real time. Thus, the penalty is not delayed.
../images/474923_1_En_5_Chapter/474923_1_En_5_Fig3_HTML.jpg
Figure 5-3

Real estate on a blockchain with smart contracts for stakeholders

In Figure 5-3, the buyer and the builder are locked into the conditions of the smart contract regarding the purchase of a house. Let us assume the basic conditions that the smart contract may contain:
  • Timely payment instalments by buyer to builder

  • Timely delivery of housing facilities by builder to buyer

These are very basic but important transaction activities undertaken by both stakeholders in any agreement over a house. Now, when the wallet amount is transferred by the buyer to the builder, the smart contract enables the housing facility of the property. The second clause is the confirmation by the buyer of all facilities.

Pseudo code for the smart contract based on the preceding conditions:
If Payment Amount by Buyer by 1st March 2020 == Cost of Property by Builder as on quote for 1st March 2020:
            Enable House Ownership and Key Access for Buyer on 1st March 2020.
If Buyer confirms on Access and housing facilities:
            Deal is successfully settled.
Else if Builder delays access and ownership:
            Pay rental cost to Buyer till period of delay
Else If Payment is delayed > 15 days && < 6months by Buyer:
            Penalize interest of 10% of House Cost
Else If Payment is delayed by 6 months by Buyer:
            Penalize interest of 20% of House Cost

In another scenario, a tenant stops paying timely rent as promised via traditional paper contract. The owner is harassed by improper communication and delayed payments. Also, on being asked to vacate the premises, tenant fails to do so, making it a legal issue and adding costs, time, and inconvenience to the owner.

If this scenario were to be blockchained, the smart contract would be pre-programmed with the schedule of the payments and what would happen upon the breach of the contract. On mutual agreement via the smart contract on the ledger, indicated by their respective digital signatures, the house node access would transferred to the tenant (enabling physical access) for the said duration of the smart contract. Upon a non-payment on the ledger, the smart contract would self-execute the warning to the tenant to pay within the warning time. If even that probation time is breached, the digital asset key of the house would be auto-transferred to the owner such that the tenant could not re-access. The non-paying tenant would be removed from the private ledger as per the pre-agreed smart contract, barring him from any further transactions (see Figure 5-4).
../images/474923_1_En_5_Chapter/474923_1_En_5_Fig4_HTML.jpg
Figure 5-4

Smart contract execution for a blockchain network between the tenant and owner

Exercise
  1. 1.

    Identify traditional contract use cases and list them.

     
  2. 2.

    Draw out stakeholders of the identified use cases.

     
  3. 3.

    Explore the digital assets and transactions involved.

     
  4. 4.

    Quantify the conditions of movement/status of asset/transactions.

     
  5. 5.

    Draw flow diagrams of the smart contract construct and execution (similar to Figure 5-4).

     
  6. 6.

    Based on that, design the pseudo code.

     

Smart Contract Languages

Once the exercise is completed, the design is to be moved toward development and implementation. For this purpose, let us see the various smart contract languages available for various purposes.

Smart ContractLanguage

Blockchain Platforms

Features

Solidity

Ethereum, Quorum, Wanchain, Aeternity, Counterparty, Rootstock (RSK), Qtum, Cardano, DFINITY, Soil, Expanse, Ubiq, Ethereum Classic, Monax

• Widely used language

• Large number of Integrations with Visual Studio, Remix, Truffle

• Multi type safe functions

• Maintains the object-oriented structure with inheritances of methods and variables

Sophia and Verna

Aeternity

• Functional programming, state, strongly typed, first-class objects, pattern matching, a crowdfunding example

F∗

Zen

 

RIDEON

Waves

• Enables account control functionalities across multi-chain touchpoints.

• Has the ability to implement multi-signature cases, atomic swaps and token freeze limits.

C++, C

EOS, Neo, Neblio, Burst

• Extremely convenient for developer

• Tokenizes governance access

• A self-sufficient reward model and fee elimination

• High-speed parallel processing

• Centralization concerns with EOS

C#

Neo, Stratis

• Makes use of the .NET framework

• Allows easy integration with enterprise and existing packages in C#

Kotlin

Neo, Corda

• Ease of analysis over state of data

• Supports parallel transactions in high-traffic legal entities, including detailed entries

• Eliminates mis-ordering of transactions due to the hash functions inbuilt to manage rightly

GoLang

Neo, HyperLedger Fabric, Neblio

• Allows one to build permissioned blockchains with Hyperledger Fabric

• Advanced querying capabilities

• Active community support

During this survey of all existing smart contracts, there came to light an interesting analysis of Ethereum’s largest transactions and the smart contracts for these sets of transactions. The users behind these smart contracts were mainly centralized and decentralized exchanges, ICOs, and token collectors. This was mainly due to the cryptocurrency market which gained high popularity in last couple years. This showcases, smart contracts so far have been used over financial transactions & trade over the Blockchains.

However, the focus of this book being aimed toward the core technology, we shall look into the application side of smart contracts and not tokens—the economics of it. The instability of the crypto-market and this young set of languages makes it highly questionable whether it is worth it for a developer to learn such languages.

Creating Smart Contracts

As we know, smart contracts are programmable contracts that auto-execute based on various activities and transactions, thus fulfilling pre-defined rules. So, for a developer, the design of this logic to create programmable event-based functions is important.

Contracts in the real world often have several loopholes that are then fought over in a legal system. Smart contracts in a blockchain’s decentralized world are expected to programmatically cover all cases of a situation for all stakeholders involved. However, it is the developer’s design logic that must cover most cases so as to avoid loopholes. Also, several smart contract language compilers may enable these checks to evaluate the Turing completeness. In simpler terms, the compiler needs to check for all cases that is computationally possible to check. This can only be established when the use case is tangible or binary for clear decision-making. Business developers, when considering smart contracts, have to deduce user stories that are tangible so as to enable these features. Refer to the pseudo-code logic in the real estate use case, for example. Thereby smart contracts require the logic to be developed in a way that it covers all cases & covers data driven decisions across the cases.

Smart contracts enable automated execution of decisions based on the data purely. This means that based on the data flowing through the business logic defined in the smart contract, various clauses/actions are triggered. Thereby reducing manual biases of over the data & functions on the pre-defined set of conditions. To be clearer, a delay in payments must cause the addition of interest, which is usually accounted for in large-scale financial transactions or financial institutions. However, there are millions of freelancers who receive delayed payments with no interest. Now, instead of a paper contract, if a freelancer were to engage in business via a smart contract that was programmed to cover the addition of interest for delayed payments from the commissioning company, the effort and delay would be covered aptly. Conversely, if the smart contract were pre-programmed and agreed upon for a timely delivery of the project and the freelancer failed to deliver on time, penalties would be auto-calculated on the ledger, making it a fair programmatic agreement.

Let’s look at another use case to further understand the use of smart contracts.

Automobile: Manufacturing, Distribution, Reselling, Servicing

Like homes, cars are enabled smart devices. The readings of the car’s performance can be observed in real time and added to the shared ledger of relevant stakeholders. In case of a malfunction, the entire tamper-proof history is clearly available to the servicing nodes of the automobile company. Similarly, the ownership of the vehicle is transferred in real time at the very second of the payment that aligns with the smart contract. Thus, blockchaining the automobile purchase for a first-time buyer from manufacturers through distributors can be performed on-chain, enabling a better user experience for both parties. Now, let’s consider a second-hand purchase, where the buyer purchases the vehicle from the seller. In this case, many times, the ownership transfer entails a long procedure with various other stakeholders. If this were to be digitized and validated via a smart contract, the transparency and convenience would be helpful.

For this purpose, we chose Ethereum in the following example. Note that the essence of this practical walkthrough is to help the reader observe the actual implementation. However, the language and the setup may be irrelevant, as it would vary based on the application, time of version, and user requirements of the scenario.

Here is the scenario: There are three types of users on a chain—manufacturer, vendor, and owner (the one who owns the car).

../images/474923_1_En_5_Chapter/474923_1_En_5_Figa_HTML.png

The owner wishes to own a vehicle, books it through the vendor, the vendor orders from the manufacturer, and the vehicle is dispatched after 80 percent of payment has been made. This process traditionally requires the buyer to part ways with the majority of the money first and then have the car dispatched. The transfer of ownership is a longer process compared to the span of time over which the money is paid. With this private chain, the ledger provides a chance for real-time transfer of ownership upon payment of money, with complete transparency between all stakeholders.

To set up the environment for this application, we use the Truffle Suite to develop smart contracts in Ethereum with Azure. Remember: Before choosing the implementation language, one has to design the flow and develop conditions. Upon understanding the nature of the application, one must choose the language and the tools (see Figure 5-5).
../images/474923_1_En_5_Chapter/474923_1_En_5_Fig5_HTML.png
Figure 5-5

Stack arrangement

For test purposes, we will start with a small instance to initialize the basic setup on Azure. To set up the environment for this application, we use the Truffle Suite - a development environment, testing framework and asset pipeline for Ethereum. Truffle Suite enables to develop smart contracts with a lot of convenience due to the set of tools inbuilt.

Search the Azure Marketplace for Truffle. One can find several variants on the marketplace. Upon clicking on Truffle, it explains what the suite provides. It enables developers to create virtual accounts over a virtual machine and directly use Truffle tools for smart contracts on Solidity during the pre-setup of an Ethereum blockchain.

Truffle allows you to initialize the VM configuration with the instance name, area zone, and so forth. Choose the desired VM size specs and the region of operation. Select the desired disk specs and proceed to review and create.

Once the steps for the virtual machine are complete, a full set of interconnected resource groups will be ready for use.

Truffle has now provided a VM that is installed with the framework and the ten accounts. The purpose of Truffle here is to provide the basic infrastructure with the Ethereum blockchain nodes and the wallets. See the following:

https://docs.google.com/document/d/1GBNlHfLrd0orOKJHedhBSRX43xgokF9GA7ZIb3ljX04/edit?usp=sharing

These nodes could be local or on Azure instances, based on your configuration. Let us look at the syntactical format of a Solidity smart contract.

We have designed the following smart contract for a manufacturer, for example:
pragma solidity ^0.5.4;
contract Manufacturer {
      //Definitions of Users, Objects & States
      address public manufacturer;
      address public vendor;
      address public owner;
      address public car;
      uint public constant price = 4 wei;
      struct car1{
      string cModel;
      uint cRegNo;
      string cLicensePlate;
 }
 mapping (address=> uint)public balanceOf;
 car1 carDetail;
//Function Definitions
 function setCar(string memory _cModel, uint _cRegNo, string memory _cLicensePlate)public{
      //storing data in struct
      carDetail.cModel= _cModel;
      carDetail.cRegNo= _cRegNo;
      carDetail.cLicensePlate= _cLicensePlate;
 }
 function getCar() view public returns(string memory, uint, string memory) {
      return (carDetail.cModel, carDetail.cRegNo, carDetail.cLicensePlate);
 }
      struct manufacturer1{
      uint mAge;
      string mName;
      string mAddress;
 }
 mapping(address => manufacturer1) manufacturerDetails;
 manufacturer1 manufacturerDetail;
 constructor ()public payable
   {
      manufacturer = msg.sender;
      //initialize
      balanceOf[manufacturer] = 0;
 }
 function setManufacturer(address manufacturer, uint _mAge, string memory _mName, string memory _mAddress)public{
      //storing data in struct
      manufacturerDetail.mAge= _mAge;
      manufacturerDetail.mName= _mName;
      manufacturerDetail.mAddress= _mAddress;
 }
   function getManufacturer(address manufacturer) view public returns (uint, string memory, string memory) {
      return (manufacturerDetail.mAge, manufacturerDetail.mName, manufacturerDetail.mAddress);
      }
      // State management
      enum State1{Created, Locked, Inactive}
      State1 public state1;
      modifier inState1(State1 _state) {
      require(state1 == _state);
      _;
      }
      event PurchaseConfirmed1();
      event ItemReceived1();
}
The constructs of the smart contract are in three major parts:
  1. 1.

    Definition of Variables – Users, Objects, and States

     
  2. 2.

    Function Definitions – Read-Write Operations and their accesses

     
  3. 3.

    Update of state variables based on event triggers

     

In the preceding code, we have first initialized a contract for a manufacturer, where the definition of variables includes the stakeholders with whom he interacts and objects such as Car that are developed on his end.

The addresses are mapped to the user nodes. The data blocks, such as the status of the manufactured car, are initialized based on the functions. These functions enable the generation of the Car record and its statuses and manufacturer details.

Upon event triggers, the status of the Car object updates are purchased and received according to the contract. Upon these event triggers, the manufacturer’s balance may be updated and the car’s ownership may be registered.

Note that the syntax of Solidity is not the prime focus of the chapter, but rather the ability to design such smart contracts. The language could be any—C++, Python, Solidity—based on the application, business premise, and developer capacities.

Go ahead and detail out a new use case in food, employment, warranties, or other fields where paper contracts have never helped.

Exercise
Think of problems in the current food-supply scenario in your house.
  1. 1.

    Write the challenges you face, such as improper quality, wastage of food, lack of supply, pesticides sprayed, artificially developed food, or an unknown source. Choose one.

     
  2. 2.

    Identify the stakeholders that handle this food supply for you. E.g., could be your supermarket, online store, or a farm nearby, or the delivery guy, the farmer, the retailer, the wholesaler, etc.

     
  3. 3.

    Build a block diagram of a block chain representing all these stakeholders.

     
  4. 4.

    Arrange the linkages of processes involved related to the challenge selected in Step 1. For example, if the challenge is wastage of food, link the inventory node of the house to other fast-consuming houses.

     
  5. 5.

    Once the chains are linked, decide the type of chain—public, private, or hybrid—and arrange linkages based on it.

     
  6. 6.

    In a chain, decide on events that require consensus, and the type of consensus.

     
  7. 7.

    If it is based on a set of pre-defined rules that all stakeholders have to agree upon, implement, or maintain data upon, create a flow diagram of the rules and conditions.

    E.g., if the challenge is quality of food, then link all stakeholders from the farming area, to the distributors, to the delivery to track the conditions of growth, the time of freshness, and have cameras at each node linked on the blockchain (IoT + blockchain). If the delivery node is to maintain the temperature of food at 4 degrees, the sensory nodes could update the blockchain in real time for all stakeholders of this data.

     
  8. 8.

    When data is added onto the blockchain, the smart contract has to successfully run through the data across the chain to form consensus. If the data (in the preceding example) breaks the rule on the contract, the food is auto-rejected by the buyer, as the supplier couldn’t maintain the conditions in the smart contract.

     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181