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.
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.
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.
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.
- 1.
Identify traditional contract use cases and list them.
- 2.
Draw out stakeholders of the identified use cases.
- 3.
Explore the digital assets and transactions involved.
- 4.
Quantify the conditions of movement/status of asset/transactions.
- 5.
Draw flow diagrams of the smart contract construct and execution (similar to Figure 5-4).
- 6.
Based on that, design the pseudo code.
Smart Contract Languages
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).
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.
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.
- 1.
Definition of Variables – Users, Objects, and States
- 2.
Function Definitions – Read-Write Operations and their accesses
- 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.
- 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.
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.
Build a block diagram of a block chain representing all these stakeholders.
- 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.
Once the chains are linked, decide the type of chain—public, private, or hybrid—and arrange linkages based on it.
- 6.
In a chain, decide on events that require consensus, and the type of consensus.
- 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.
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.