What Are Smart Contracts? How to Build on a Cardano Blockchain
Decentralization is now an important part of our daily lives, whether we realize it or not. We see it in finance, the arts, data ownership, and various other areas.
The Cardano blockchain is one of the fastest-growing and most widely used blockchains. It is a third-generation, proof-of-stake blockchain platform and home to the ADA cryptocurrency.
In this article, we will discuss smart contracts and how to build a dApp on a Cardano blockchain.
What are smart contracts?
Smart contracts are computer programs or protocols for automated transactions stored on a blockchain and run in response to certain conditions. In other words, smart contracts automate the execution of agreements so that all participants can ascertain the outcome as soon as possible without the involvement of an intermediary or time delay.
Smart contracts are self-executing contracts in which the contents of the buyer-seller agreement are inscribed directly into lines of code.
According to Nick Szabo, an American computer scientist who devised a virtual currency called "Bit Gold" in 1998, smart contracts are computerized transaction protocols that execute contract conditions.
Using smart contracts makes the transactions traceable, transparent, and irreversible.
How do smart contracts work?
Think of smart contracts as digital “if-then” statements between two (or more) parties. If one group’s needs are met, the agreement can be honored, and the contract is considered complete.
Let’s say a market asks a farmer for 100 ears of corn. The former will lock funds into a smart contract that can be approved when the latter delivers. When the farmer delivers their obligation, the funds will immediately be released (i.e., after fulfilling a legal contract). However, the contract is canceled, and funds are reversed to the client if the farmer misses their deadline.
Of course, the above is a small use case. Smart contracts can be programmed to work for the masses, replacing governmental mandates and retail systems, among other benefits. Moreover, smart contracts would potentially remove the need to bring certain disagreements into court, saving parties time and money.
Types of smart contracts
1. Smart Legal Contract
The most common type of smart contract, a smart legal contract, involves similar legal requirements (i.e., mutual assent, expressed by a valid offer and acceptance; adequate consideration; capacity; and legality) to its traditional counterpart, and it is put in place to hold concerned parties accountable for fulfilling their end of an agreement. When set up properly, a smart contract is legally enforceable and requires the parties to fulfill their obligations; failure to fulfill obligations in the contract may result in legal action that can be automatically triggered by the smart contract against the party in breach.
2. Decentralized Autonomous Organizations
Decentralized Autonomous Organizations, or DAOs, can be defined as communities on the blockchain. These communities can be defined by a set of agreed-upon rules coded via smart contracts. Every participant and their actions are subject to the community’s rules with the task of enforcing them. These rules are made up of many smart contracts and work together to watch over activities in the community.
3. Application Logic Contracts
Application Logic Contracts (ALC) contain an application-based code that remains in step with other blockchain contracts. They enable communication across different devices, such as the merging of the Internet of Things (IoT) with blockchain technology. ALCs are pivotal pieces of multi-function smart contracts and mostly work under a managing program.
With this explanation, let's begin.
What is Cardano?
The Cardano blockchain is a new blockchain based on the Shelley consensus algorithm. It’s designed to be a secure, scalable, and easy-to-use platform for building and running decentralized applications.
Cardano is a proof-of-stake blockchain platform: the first to be founded on peer-reviewed research and developed through evidence-based methods. It combines pioneering technologies to provide unparalleled security and sustainability to decentralized applications, systems, and societies.
With a leading team of engineers, Cardano exists to redistribute power from unaccountable structures to the margins – to individuals – and be an enabling force for positive change and progress.
What is a blockchain?
A blockchain is a decentralized digital distributed ledger that records all transactions using a peer-to-peer network to verify and record transactions. Blockchains use complex encryption to maintain secure databases without a trusted central clearing authority.
Ethereum is a blockchain based on the Ethereum Virtual Machine. To make transactions on the Ethereum blockchain, we’ll spend some ethers. This cryptocurrency is used to pay for gas in the Ethereum blockchain.
Likewise, we’ll spend ADA in the Cardano blockchain to pay the gas fees.
What are dApps?
A decentralized application, or dApp, is an application that can operate autonomously, typically through the use of smart contracts, that runs on decentralized computing blockchain systems. DApps are open source and often have user-generated content.
The best dApps are designed to run exactly as programmed without any possibility of downtime, censorship, fraud, or third-party interference.
The difference between a dApp and a conventional app is that the conventional app is controlled by a single entity, while a dApp has a blockchain as its backend.
For example, a React to-do app might store its data (the to-dos) in an Ethereum blockchain. Or, you could build a voting system in Angular and store its data in the Cardano blockchain.
What is ADA?
As mentioned above, ADA is the native cryptocurrency of the Cardano blockchain. You can use and transfer ADA on the Cardano blockchain just as you would ETH on the Ethereum blockchain.
ADA can be used as both a cryptocurrency and a token. ADA being used as Cardano’s native currency means that it is:
Accepted as fee-payment
Accepted to make deposits
The only currency in which rewards are distributed
Just like ETH is divided into denominations (e.g., Wei), ADA also has denominations. Lovelace is the smallest unit of ADA; 1 ADA equals 10^(-18) Lovelace, which can be divided into a total of 1,000,000 Lovelaces.
What is Plutus?
Plutus is a programming language for writing smart contracts on the Cardano blockchain. Other programming languages you can use for the Cardano blockchain include Glow lang, Marlowe, etc., but Plutus is the fastest among them.
Plutus is based on Haskell, so using it requires prior knowledge of Haskell programming.
Writing our smart contracts using Plutus
Let’s walk through how to write smart contracts using the Plutus programming language. These apps can run off-chain and manage active contract instances.
According to Cardano Testnets, Plutus contracts consist of parts that run on the blockchain (on-chain code) and parts that run on a user’s machine (off-chain or client code). We’ll write our smart contracts using a Plutus online editor and simulator.
A Plutus smart contract is a Haskell code that runs in a user’s wallet and sends code to the blockchain to be run by the nodes in the blockchain. The smart contracts run on the blockchain, not the user’s machine.
Plutus smart contracts define the smart contract and its state. Inside these definitions are endpoints, which define the smart contract’s behavior. These endpoints are functions executed by the wallet. They are known as off-chain functions and are used to build transactions and send them to the blockchain.
Building our simple dApp with Plutus
Let’s write a simple dApp in the Cardano blockchain using the Plutus programming language.
In this example, we will write a smart contract to print “Hello, Tech Writers!” to the console.
Let's open the Plutus online editor and simulator
This will populate some code for us. Clean it up and add this code below.
import Data.Text qualified as T
import Playground.Contract
import Plutus.Contract
import PlutusTx.Prelude
import Prelude qualified as Haskell
hello :: Contract () EmptySchema T.Text ()
hello = logInfo @Haskell.String "Hello Tech Writers"
endpoints :: Contract () EmptySchema T.Text ()
endpoints = hello
type DummySchema = Endpoint "dummy" ()
mkSchemaDefinitions ''DummySchema
$(mkKnownCurrencies [])
Let’s go through the code:
import Data.Text qualified as T
import Playground.Contract
import Plutus.Contract
import PlutusTx.Prelude
import Prelude qualified as Haskell
Here, we imported the libraries and built-in functions we will need:
- The
Data.Text
library is used to convert strings to text - The
Playground.Contract
imports the smart contract interfaces defined in the playground - The
Plutus.Contract
library is used to define the smart contract from the Plutus core library - The
PlutusTx.Prelude
library replaces the normal Haskell Prelude library and includes functions that are refined and easier for the PlutusTx compiler to compile
hello :: Contract () EmptySchema T.Text ()
hello = logInfo @Haskell.String "Hello Tech Writers"
The above code snippet defines a hello
function, where the Contract () EmptySchema T.Text ()
tells the compiler the function will return nothing. The logInfo
function is a built-in function that logs a message to the console. So, in summary, the hello
function will log Hello Tech Writers
to the console.
endpoints :: Contract () EmptySchema T.Text ()
endpoints = hello
This creates an endpoints
function, which will run the hello
function and expose it to the blockchain.
type DummySchema = Endpoint "dummy" ()
mkSchemaDefinitions ''DummySchema
$(mkKnownCurrencies [])
The above snippet creates the DummySchema
type, which defines the smart contract’s state. Finally, it exposes the endpoints
to the blockchain.
In our Plutus playground, we can click the green Compile button to compile our contracts.
After a successful compilation, the blue Simulate button will open up a page where we can run the smart contracts on the blockchain.
You’ll notice that we have two wallets, each with an open balance of 1000000 Lovelaces. The Available functions
in each wallet show the functions that can be used.
In our case, we see our hello
function and another Pay to Wallet
function. The Pay to Wallet
function sends funds to another wallet, and the Plutus contract defines it. We don’t get to see the code because it’s added there when we import the below modules:
import Playground.Contract import Plutus.Contract
If we look at the section on the page below, we’ll see an Actions section. This section is where the functions we want to run are added when the wallet address card above is clicked.
We already have a card in the Actions; the card simulates delay on the blockchain. We can remove this card by clicking the "Cancel" icon.
Now, click on the dummy
button, and you’ll see a card appear in the Actions section:
Click on the green Evaluate button, and you will see the hello
function run on the blockchain.
After some time, a Transactions page will appear:
Scroll down to the Logs
section, and you will see the hello
function log Hello Tech Writers
to the console:
Conclusion
This tutorial demonstrated how to write a dApp on the Cardano blockchain using the Plutus programming language.
We started by walking through smart contracts, how they work, and the types of smart contracts. Then, we introduced the Cardano blockchain and the Plutus programming language; next, we explained ADA. We then introduced the Plutus programming language and described how we could use it to compile and run smart contracts on the Cardano blockchain.
Finally, we explored some examples of smart contracts written in the Plutus programming language and run on a simulated Cardano blockchain.