Smart Contracts on Blockchain (Part 9- Blockchain Series)

Welcome to the ninth part of the 100 part series on Blockchain.

Previous parts: Part 1, Part 2, Part 3, Part 4, Part 5, Part 6, Part 7, and Part 8

Smart contracts are the self-executing programs that are stored on Blockchain and run when predefined conditions are met. They are the digital versions of the standard paper contract, whose terms of the agreement are written in the lines of code. They automatically execute transactions if certain conditions are met without requiring the help of a third party to manage or approve the transaction. This third party could be a government organization, a lawyer, or any other entity. For instance, in traditional paper contracts, a document outlines the terms of conditions between two parties, which is enforceable by law. If one party A violates the terms, party B can take Party A to court for not complying with the agreement. Whereas, in the smart contract, such agreements are written in code, so the conditions of the agreement are automatically enforced without any third party getting involved.

Third-party is not involved in the execution of smart contracts

The concept of smart contracts was first proposed in 1994 by Nick Szabo, an American computer scientist, and cryptographer who invented a virtual currency called “Bit Gold” in 1998.

A metaphor for Smart Contracts

One of the real-life metaphors for a smart contract that many of you may have interacted with is the Vending Machine! The smart contracts on the Blockchain and vending machines share a lot of commonalities.

Certain rules are hardcoded into the vending machine that decides what happens when certain conditions are met and based on these conditions, the vending machine triggers automatic actions. For instance, if you want a can of soda, then:

(i) You select a product can of soda

(ii) The vending machine tells the amount required to purchase the selected product

(iii) You insert the correct amount

(iv) The vending machine verifies you have inserted the correct amount

(v) The vending machine then dispenses the product of choice

Suppose the cost of a can of soda is $3. If you have only $1 in your pocket, no matter how many times you try, you won’t be able to get the drink. On the other hand, if you put $4 in the vending machine, a soda can, along with the change of $1, is dispensed by the vending machine. And in case you put $3, the vending machine will dispense a soda can alone.

So you can see that in the vending machine, certain rules are predefined and hardcoded into the machine. These rules then get executed in the physical world by the vending machine.

Vending machine: a metaphor for smart contracts

Similarly, smart contracts are rules defined and executed by the lines of code on the Blockchain.

How do smart contracts work?

The life cycle of smart contracts consists of four consecutive phases: creation, deployment, execution, and completion.

(i) Creation of smart contracts: Before any transaction, the contractual parties determine the terms of the contract. It is important to note that lawyers or counselors may be required to help parties draft an initial contractual agreement, but for the execution of the agreement, a third party is not required. After the contractual terms and conditions are finalized, they are translated into programming code called a smart contract. Basically, the code represents a number of different conditional statements that describe the possible scenarios of a future transaction. They work by following simple “if…then…else” statements that are written into code on a Blockchain. The “if” statement is the most basic conditional statement that is used to make a decision on whether the statement or code will be executed or not. “If” the condition is true, “then” the statement will be executed, while if the condition is false, then else statement will be executed. For instance, in Fig, if A is true, then B will be executed, else C will be executed.

If-Then-Else flow diagram

(ii) Deployment of smart contracts: When the smart contract is created, the parties can agree to the terms and conditions by applying their digital signature on the contract. A digital signature is a cryptographic technique that binds a person to digital data. Private keys of the parties are used to create digital signatures. Digital signature has been explained in detail in Part 6. Then the smart contract is stored on the Blockchain network, which can not be altered/modified, making them immutable. Any correction or revision in the contract requires the creation of a new contract. For that reason, you must pay special attention to writing and testing code to avoid introducing bugs in the contract that will never be fixed.

Because of storing the smart contracts on Blockchain, they become decentralized. It means that smart contracts are not controlled by a single machine/human. In fact, all the nodes on the Blockchain store the same contract with exactly the same state. Additionally, the digital signature + the public key of the parties are enough for nodes to verify that the private keys associated with the parties have been used to make signatures on the contract.

Moreover, during this phase, any transfers to the smart contract’s receiving wallet address are blocked. For instance, a smart contract is signed between buyer and supplier. According to the contract, fund transfer from the buyer’s wallet to the supplier only occurs once the buyer receives the goods from the supplier. As a result, any sort of funds transfer on the supplier’s wallets will be blocked. The nodes act as a governing body that validates whether the predefined conditions for contract execution have been satisfied.

(iii) Execution of smart contracts: After the deployment of smart contracts, the contractual terms are monitored and evaluated by all the Blockchain nodes in the network. Once the predefined conditions are met, the smart contract is self-executed. The funds in the form of coins are released from the buyer’s wallet to transfer them to the supplier (as a commitment of exchanging goods). The released funds create a transaction triggered by the met criteria. Consequently, the executed transaction is validated by the nodes on the Blockchain to ensure fulfillment of the contract conditions. This verification process is done by the Proof-of-Work (discussed in Part 7) or Proof-of-Stake (discussed in Part 8) consensus mechanisms. The verified transactions and the updated state of smart contracts are then stored on the Blockchain.

(iv) Completion of smart contracts: According to the predefined conditions on the smart contract, after the buyer receives the goods from the seller, the seller’s wallet is unlocked. Therefore, the funds get transferred from the buyer to the supplier’s wallet. This marks the completion of the smart contract, which is then closed and recorded on the Blockchain.

It is important to note that a sequence of transactions has been executed during the deployment, execution, and completion phases of a smart contract. Therefore, all three phases need to write data to the blockchain.

Life cycle of smart contracts

Advantages of smart contracts

1. Trust: One of the most significant benefits that smart contracts have over traditional contracts is that they are automatically executed when the agreement conditions are met. There is no need to wait for a third party to execute them. In other words, smart contracts remove the need for trust.

For example, if an employer wants to write a contract that holds funds in escrow for a hired person, allowing them to withdraw funds only after the completion of an assigned task. In this case, a third party like Upwork initiates the contract and holds the payment in escrow. Once the hired person completes the work, the employer reviews the work. If the employer is satisfied, he notifies Upwork, and the payment is released. For this, both parties have to rely on the reputation of the intermediaries like Upwork.

On the other hand, the smart contract would work in a fully automated way, ensuring that the hired person receives the money after completing the task. And the employer gets the task completely done. For this, the parties don’t have to rely on intermediaries. Once conditions have been met, nodes on the Blockchain validate the transaction, and the money is released to the hired person. Smart contracts can also hold funds. For example, you could write a smart contract that holds funds in escrow for a child, allowing them to withdraw funds after a specific date. If they try to withdraw the funds before the specified date, the smart contract won’t execute.

2. Transparency: Another property of smart contracts that makes them so critical is the transparency they bring along with them. As discussed earlier, smart contracts contain a detailed list of terms and conditions agreed upon by the parties involved. This pre-agreed setting eliminates the chances of issues and disputes at later stages as the terms and conditions are proposed and passed by the parties themselves.

These terms and conditions remain visible to every party involved in the transaction. Thus bringing transparency in the system. Issues related to communication gaps are also reduced with the implementation of smart contracts as there is only a single version of the truth that is visible to everyone on the network.

3. Immutability: Smart contracts are immutable, which means their code and conditions can not be changed or updated once they are deployed on the Blockchain. Moreover, they are stored and duplicated throughout the whole distributed Blockchain system, thus are traceable and auditable. As a result, malicious behaviors like financial fraud can be greatly mitigated. If you want to change an existing smart contract, you will have to deploy a new version of the contract.

4. Better Time Efficiency: Another significant benefit of implementing smart contracts is better efficiency. In the traditional system, with the paperwork involved, it generally takes days to get a request processed. There is a lot of unnecessary duplication of documents at various stages of the process. Further, the involvement of a large number of intermediaries makes the process more complex, cumbersome, and time-consuming.

But with the implementation of smart contracts, all these redundant and unnecessary steps are eliminated from the process, which significantly reduces the time taken to complete the transactions.

5. Safety and security: Smart contracts along with Blockchain are tamper-proof, reliable, and secure. This characteristic of security and safety brings in more value and trust in the associated transactions.

Ethereum smart contracts

Smart contracts lie at the heart of the Ethereum Blockchain. The smart contracts on Ethereum Blockchain run on the Ethereum Virtual Machine or EVM, which is present on every node in the network. The purpose of EVM is to execute smart contracts.

Gas: Executing a smart contract in EVM comes with a price. Any operation in the EVM requires CPU cycles, disk access, and the memory of the hosting machine. Each computation happening in the EVM for executing lines of code on smart contracts needs some amount of gas. Simply put, gas is a unit used for measuring the amount of computational effort required by the EVM to perform transactions on the Ethereum Blockchain. Therefore gas is used for assigning fees to each transaction with a smart contract. The more complex the computation is, the more the gas is required to run the smart contracts. For every transaction that you submit on the Ethereum Blockchain platform, you must pay Gas in the form of Ethereum’s cryptocurrency Ether (ETH). Gas prices are paid in gwei; each gwei is equal to 0.000000001 ETH (10^-9 ETH).

Transaction fee = Gas units used (limit) * (base fees + priority fees)

Where base fees is the gas price per unit, which means the fee for every unit of gas, burned upon successful completion of the transaction. In addition to the base fee, a priority fee is added, again per unit of gas, the value of which depends on how quickly you want the transaction to go through.

The gas limit refers to the minimum amount of gas a user is willing to consume on a transaction. More complicated transactions like smart contracts, minting NFTs, etc., require more computational work, requiring a higher gas limit than a simple payment. For instance, a standard ETH transfer requires a gas limit of 21,000 units of gas. Let’s say Alice has to transfer 1 ETH to Phil. The base fee for ETH transfer is 200 gwei, and Alice adds a priority fee of 10 gwei. Therefore, transaction fee for 1 ETH transfer would be: 21,000 * (100+10) = 2,310,000 gwei or 0.00231 ETH. On the other hand, the gas fee is much higher for the execution of the smart contract that is more complex in terms of the actions to be performed. The transaction fees increase with the complexity of the contract. While the gas fee for minting NFTs is most expensive relative to other sorts of operations performed on the Ethereum Blockchain.

Solidity: On Ethereum, smart contracts are written in a programming language called Solidity.

Gas fees after Ethereum 2.0: Ethereum has two different versions, Ethereum 1.0 and Ethereum 2.0. Ethereum 1.0 uses proof of work (PoW), but its switch to Ethereum 2.0 uses proof of stake (PoS) consensus mechanisms. In Proof of Work (PoW), validating transactions and block creation on Ethereum 1.0 Blockchain requires a huge amount of computer processing power. On the other hand, block creation in Proof of stake (PoS) is directly proportional to the individual’s holding of the cryptocurrency or the underlining token of the network. Thus, with the reduction in high power consumption in the proof of stake mechanism, gas fees should decrease. Therefore, the shift to Ethereum 2.0 will result in lower transaction fees.

Other Blockchain-based smart contract platforms: Although Ethereum is currently the most important smart contract platform, this is not the only one. Other blockchain platforms suited for designing smart contracts are Hyperledger fabric, Waves, NEO, Polkadot, Tezos, Solana, Cardano, etc.

Smart contract real-world examples

Smart contracts have a broad spectrum of applications from financial transactions to the insurance industry, supply chain, and many more. Now let’s have a better understanding of these contracts through practical, real-life examples:

Insurance industry: The current issue with the insurance industry is the claim processing time, i.e., it takes weeks and sometimes even months to get the claims settled. The processes are outdated and manual. This increases the overhead cost for the insurer, and in turn, customers have to pay higher premiums. Insurance companies can use smart contracts to automate these insurance policies.

In these smart contracts, conditions and rules are defined under which the claim will be approved or rejected. For example, in the event of any catastrophic natural disaster, quantifiable parameters such as the speed of the wind or the magnitude of an earthquake can be recorded on the Blockchain. When the parameters meet the defined conditions in the smart contract, the claims processes are triggered immediately, and the complete payout amount is released without any human intervention.

Implementation of smart contracts not only reduces the overhead costs for the insurer but also brings trust and transparency in the system.

Supply chain: Another good use case for smart contracts is the supply chain which has become quite complex owing to more porous international boundaries and the involvement of a large number of intermediaries. The supply chain involves the flow of products and goods from its initial stage till its final stage, for example, from a producer who produces raw material to a consumer who ultimately consumes them.

Let’s take the example of the Pharma supply chain and understand how Smart contracts can disrupt this space. Certain drugs like vaccines are sensitive to temperature changes. If kept at an unsuitable temperature, the vaccines become inactive and ineffective. But in the current scenario, there is no foolproof way to establish that a vaccine has been kept at the right temperature throughout its journey and is fit for medical use. But with the implementation of smart contracts along with the Internet of things or IoT, it is possible.

But what is IoT? IoT is the concept of connecting physical devices like sensors, cars, kitchen appliances, fitness devices, etc., to the internet. It gives the IoT devices the ability to gather and share data over the internet about how they are used and the environment in which they are operated. Thus, allowing them to communicate with people and other IoT-enabled devices. It’s done using sensors that are embedded in the devices. The sensors continuously emit data about the working state of the devices. The combination of Blockchain and IoT enables sensors embedded in IoT devices to send data to Blockchain networks to create tamper-resistant and immutable records of transactions.

For instance, smart IoT temperature sensors will be installed on the vaccine packets, which will record its temperature throughout its journey, and this information will be updated on the Blockchain. Smart contracts will be predefined for this supply chain. One of the conditions defined in the smart contract will be: if the temperature rises above the expected range (6°C), the manufacturer will be notified, and the drugs will be sent back to him for inspection. Therefore, removing ineffective drugs from the system.

IoT sensors record the temperature of vaccines during transportation, and any fluctuation in temperature is recorded on the Blockchain

These are just some of the few examples of the limitless possibilities of Smart Contracts. Though smart contracts are still in their infancy, the future holds a great promise for them with their applications ranging from regular day-to-day agreements to huge government and enterprise agreements on a global level.

Thanks for reading!

If you liked this article and want to explore real-world applications of Blockchain please follow this link.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store