An Introduction to Smart Contracts

Before you start reading this article, you should have a basic understanding of how blockchain works.

In general, a contract is an agreement made between two or more parties who abide by the terms listed in it. It usually takes the form of a detailed document with several clauses and conditions that are signed on by all parties. Usually, these contracts are enforceable by law and written in human language.

Contracts are everywhere in our lives; for example, if youโ€™re leasing or renting a home, you sign a lease agreement. When you accept an offer to a new job, you are signing an employment contract. Whenever you go shopping and want to return a product, the employees look into the return policy, which is a contract. Any insurance or financial agreements are also contracts.

In this article, Iโ€™ll go over everything you need to know to be well acquainted with smart contracts.

So, letโ€™s look into each of the follow topics:

  • What They Are
  • A Brief History
  • How They Work
  • Benefits/Advantages
  • Limits/Disadvantages
  • Applications
  • The Future of Smart Contracts
  • Sample Smart Contract
  • Additional Reading/Sources

What They Are

Smart contracts are rule-based computer programs that can make decisions based on the conditions built into them. These programs can automatically verify, control, and execute an agreement. For example, they can transfer digital assets between parties when certain conditions are met. This code enforces the contract whereas traditional contracts are enforceable by law.

The way I like to think of smart contracts is like vending machines. Essentially, when youโ€™re running the code of a smart contract, youโ€™re choosing which functions to execute, or which items to obtain from the vending machine. Sometimes these operations require monetary compensation to pay for Gas fees (which I will explain in a later section of this article), or other times they may be free (which depends on the type of smart contract it is).

Dapps

A lot of people interchangeably use the terms smart contracts and decentralized applications (Dapps), but this is incorrect. A smart contract is simply a piece of code that is stored on the blockchain. A Dapp, however, connects the frontend to the backend and may use several smart contracts to run.

Examples of Smart Contracts/Dapps

An example of a smart contract could be one used in the field of voting for elections. It could count the number of votes towards each party and then make a final decision on who won. This smart contract would be immutable, meaning nobody would be able to change it, making it entirely trustworthy.

A huge example of a Dapp that you may have heard of, is MakerDAO. It is essentially a financial system where you can lend and borrow money using cryptocurrencies. MakerDAO has a frontend that communicates with the backend and uses several smart contracts.

A Brief History

The original idea of a smart contract on a distributed ledger was envisioned by Nick Szabo, a cryptographer, in 1994. By โ€œsmart contractโ€ he meant a set of promises written digitally, including protocols which the parties perform on their promises. However, the term โ€œsmart contractโ€ was rarely used until 2008, when Satoshi Nakamoto introduced the concept of Bitcoin.

Later in 2015, the concept of smart contracts was popularized by Ethereum, and in the present day, they are being used for a variety of tasks.

How They Work

Smart contracts are composed of three components: the parties, the subject of the contract, and the terms or conditions that apply to it. Each smart contract is put onto the blockchain that is broadcasted to the entire network and has an address. This code is executable on every node in the network.

Each node has the history of all smart contracts, the history of all transactions, and the current state of all smart contracts.

A Dapp is an interface for people to interact with a smart contract. It consists of the frontend and API to interact with the smart contract(s). A smart contract provides a way for a Dapp to interact with the blockchain.

Below are some concepts that help understand how smart contracts are best suited to the Ethereum platform.

Turing-Completeness

Bitcoin uses a programming language called Bitcoin Script, whereas Ethereum uses Solidity. One big difference between these two languages is that Bitcoin Script is not a Turing-Complete language, unlike Ethereumโ€™s Solidity, which is Turing-Complete. A programming language is considered to be Turing-Complete when it is possible to program any logic into it, including loops.

Bitcoin Script doesnโ€™t support the use of loops, for an obvious reason โ€” it would slow down the entire blockchain if an infinite or computationally demanding loop is put into the system. So, by design, loops were not included in Bitcoin Script.

But Ethereumโ€™s Solidity does support loops, so how does Ethereum handle the problem of the blockchain slowing down? Vitalik Buterin came up with an ingenious solution to this problem.

Gas, Gas, Gasโ€ฆ

Vitalik introduced the concept of Gas, which is a fee that the developer of the smart contract has to pay for executing any operation on the Ethereum platform. It encourages programmers to make their smart contracts as efficient as possible so they pay the least fee possible. If someone writes very inefficient code, or, worst-case, an infinite loop in the smart contract, it may slow the network down temporarily, until the developer of the smart contract runs out Gas. This structure allows Solidity to use loops while keeping the blockchain running smoothly.

The unit for measuring Gas prices is Wei. Every operation run on a smart contract is translated into the number of Wei consumed and charged to the developer. One Wei is 10^-18 of Ether, or one quintillionth of one Ether, the cryptocurrency used on the Ethereum blockchain.

If you would like to see which operations consume how much Wei, take a look at this spreadsheet.

Ethereum Virtual Machines

A smart contract runs on every single computer in the network. What if a smart contract is written maliciously to infect computers? What if they could access your personal files or even turn on your webcam? How do we address this security concern?

Ethereum Virtual Machines (EVMs) effectively solve this problem. When you participate in the Ethereum network, an EVM gets installed on your computer. The EVM completely encapsulates everything that runs on the blockchain and isolates it from the machine itโ€™s running on. The EVM acts like a computer within your computer, and nothing can escape from the EVM onto your actual computer. In fact, EVMs are completely unaware of anything outside of it, which also adds to its several layers of security, guaranteeing that everything happening on the EVM, stays on the EVM.

Benefits/Advantages

Below are a few advantages of using smart contracts over traditional, physical contracts.

Removes Intermediaries: Smart contracts remove the needs for intermediaries and allow direct and transparent relationships between all involved parties.

Efficiency: Smart contracts use software code to automate tedious tasks and related paperwork, thus saving time and money. This automation of tasks also helps avoid human error.

Security: As documents are stored in encrypted form on an immutable ledger, they are highly secure with a low probability of misuse or tampering. Because the data is stored in chronological order, tracking the audit trail becomes very easy.

Decentralization: Because your data is stored on all nodes on the network, even though one node goes down or fails, the other nodes can back it up.

Limits/Disadvantages

While smart contracts come with some awesome advantages, there are certainly some aspects that have to be worked on.

Lack of International Recognization: Decentralized transactions without third parties are not lawfully recognized in several countries. Also, the laws are still not matured enough where they are recognized. This lack of regulation makes its full adoption difficult.

Immutable: As soon as a smart contract is put onto the blockchain, it cannot be changed. There is less flexibility in situations such as addressing a bug in a smart contract or a future need to change the code in the smart contract. The only way for you to change the code would be for you to add a new copy of the smart contract onto the blockchain.

New Technology: This technology is still relatively new, and its implications are still not fully assessed in several of its use cases. So, it still needs to gain a wider trust as it becomes more mature.

Applications

Smart contracts have the potential to be used in almost every aspect of our lives โ€” in healthcare, in finance/banking, in industries, in real estate, and in governments and private sectors.

Below are a few applications of smart contracts.

Banking/Insurance

Many projects are being developed that are looking to transform banking to run on blockchain technology. These projects, that are mainly Dapps, such as Meld and MakerDAO, will inherently need smart contracts to eliminate the need for the intervention of a third party.

In the field of insurance, smart contracts can be used for error checking, routing, and issuing payments efficiently. They achieve this by using a decentralized, immutable ledger for bookkeeping, and minimizing the risk of fraud.

Healthcare

Smart contracts can be used to automate payment systems for healthcare. It can record all healthcare transactions and bills on a blockchain, and create transparency between the patient, the healthcare provider, and the insurance company by creating a single view. These records could be stored in an encoded form to address data security and privacy concerns. Only those to which these records belong can access it.

Real Estate

Real estate transactions involve great amounts of commission to the real estate agents and fees to the lawyers who help the buyer or seller to perform the transaction to transfer the ownership of the property. These commissions and fees to the middlemen can be eliminated with the use of smart contracts.

One can build complex logic in a smart contract that ensures that all clauses of the agreement are met before the transfer of ownership occurs. These transactions will be recorded on an immutable ledger, to minimize the opportunity for fraud.

Management

In decentralized autonomous organizations (DAOs), smart contracts can be used to make decisions on the behalf of humans based on complex conditional logic built into them. For example, if the supply of raw material goes below a certain threshold, a smart contract can trigger an order to the supplier/manufacturer to deliver a new shipment of raw materials.

The Future of Smart Contracts

The adoption of smart contracts in the future depends on how well we address the challenges listed above. The simpler and more straightforward conventional contracts may be easily standardized into smart contract templates. However, the more complicated contracts that require frequent changes due to their unique nature and changing circumstances may have to stay conventional until we find common ground to address some of the above problems.

As this technology matures, we will see more and more uses of smart contracts in various aspects of our day-to-day lives.

Sample Smart Contract

Below is a simple code snippet from Solidity Docs that makes a small mock cryptocurrency. I recommend checking out the Solidity Docs to see more examples.

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;

In line 1, we identify that the code is licensed under GPL Version 3.0, and in line 2, we are specifying the version of Solidity that weโ€™re going to use. We do this because there might be breaking changes in newer Solidity compilers, so we want to keep it at this version.

contract Coin {
address public minter;
mapping (address => uint) public balances;

In line 4, we initialize our contract that we name Coin, and in line 5, we initialize an address called minter, but we donโ€™t give it a value yet. Note that it also has the public tag, meaning that this variable is accessible by other contracts. In line 6, we now create a mapping called balances. A mapping is essentially like a key and value finder, so if you input an address into the balances variable, you will get a uint, or unsigned integer, which essentially means itโ€™s not negative.

event Sent(address from, address to, uint amount);

Here, in line 8, we are still inside the contract, and now weโ€™re making an event. An event basically allows users to see what changes have been made to the contract. An event can be emitted, signaling that it has been executed.

constructor() {
minter = msg.sender;
}

In line 10, we use a constructor. All of the code thatโ€™s nested inside a constructor gets executed when the contract is created. In line 11, we finally define our variable, minter, and set its value to msg.sender, which is essentially the address of the account that sent a โ€œmessage.โ€

function mint(address receiver, uint amount) public {
require(msg.sender == minter);
balances[receiver] += amount;
}

In line 13, a function, mint, is being called. This function essentially creates and sends, or mints, money to a specific address. The parameters of the function are the receiver as an address, and the amount being sent as an unsigned integer. The mingt function can only be called by the developer of the smart contract. In line 14, we are requiring msg.sender, the address of the account that initialized the smart contract, to be equal to the address of the minter. Then, by using our balances mapping, we add the amount we wanted to give, to the receiverโ€™s account.

error InsufficientBalance(uint requested, uint available);

In line 18, we are defining an error. Errors can give information on how and why an action failed. We are passing the parameters requested and available.

function send(address receiver, uint amount) public {
if (amount > balances[msg.sender])
revert InsufficientBalance({
requested: amount,
available: balances[msg.sender]
});

In line 20, we are making a function called send that sends Coins to the address that called the function. In lines 21โ€“24, we first check if the amount requested to send is greater than the balance of the person who called the function. If the condition turns out to be true, the revert keyword unconditionally stops all the code and gives an error, with the parameters of how much was requested and how much is available.

balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Sent(msg.sender, receiver, amount);
}
}

Still inside the function, if the previous condition turns out to be false, then we proceed with the next lines. Here, we are subtracting the amount of Coins sent from the sender, and we are adding that same amount to the receiver. Then, we emit the event, Sent, which tells us that the transaction was successful.

Additional Reading/Sources

Here are some of the sources I used to create this article, along with some additional reading.

If you made it this far, thank you for reading my article. Be sure to stay safe and Happy Holidays!

--

--

๐•ฟ๐•พ๐–”๐–‘๐–š๐–™๐–Ž๐–”๐–“๐–˜๐–ƒ

I am a software developer with a passion for innovation. Stay connected for insights on cutting-edge technology, blockchain advancements, and more.