Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconBlockchain Technologybreadcumb forward arrow iconHow to Write & Deploy Your First Smart Contract?

How to Write & Deploy Your First Smart Contract?

Last updated:
13th Feb, 2020
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
How to Write & Deploy Your First Smart Contract?

Smart Contracts are a leading trend in Blockchain technology today. If you are thinking of building a career in the field, this article will help you with all that you need to know to write your first smart contract

Learn Online Software Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

How to Write Your First Smart Contract?

Today’s digital age has allowed two parties to enter into agreements without third-party involvement. These digital contracts are processed by the blockchain and stored on a public database. So, the transactions are trackable and irreversible. 

If you want to write your first smart contract, the resources compiled below will put you right on track. 

Ads of upGrad blog

Read: 10 Blockchain Trends & Predictions for 2020

Defining smart contracts

The term ‘Smart Contract’ was first proposed by American computer scientist Nick Szabo back in 1996. It is a computer or digital protocol that facilitates, verifies, and enforces the performance of a contract. As a general-purpose computation, a smart contract resides on a Blockchain or distributed ledger. 

In other words, the contract is built into the code in the form of a computer program. And the designated actors receive permission to execute the function of the program. The predefined rules should be met for the successful execution of the smart contract. 

Take a Purchase Order (PO), for instance. It is a simple contract between a buyer and a seller. Certain conditions have to be fulfilled for carrying out the PO. These specifications include successful payment by the buyer, delivery of goods by the supplier as per the terms agreed upon at the time of purchase, conditions for return etc. 

So, the buyer can place an order and the supplier can fulfill the order in a digital format. Over a computing network, all the actions are called transactions. And all transactions are verified and enforced by the network. Once confirmed, the transactions cannot be reverted. 

Explore our Popular Software Engineering Courses

Read: Prerequisites to learn Blockchain. It’s not what you think it is

Requirements For Setting up a Smart Contract

Various programming languages are available for building smart contracts. The choice of language mainly depends on the blockchain platform. For example, Solidity, Vyper, eWASM, and Ethereum bytecode are some of the most popular smart contract languages for the Ethereum blockchain platform. 

Smart contract development environment

Before you write your first smart contract, set up the playground for its development. Going deeper into the blockchain world would be tricky without the knowledge of development environments. You can choose from the following alternatives. 

  • Remix IDE: It is an integrated development environment for building and testing smart contracts. This entirely online option is highly recommended for beginners, as it requires no installation. Moreover, it poses fewer challenges for prototyping and quick validating of smart contracts. 
  • Local Setup: Local machines provide yet another resource for smart contract development. The tools provide greater flexibility for enterprise-grade applications. And although it takes time to set up this environment, the selection of tools for Distributed Applications or DApps is a reasonably straightforward process. 

Structure of a Smart Contract

Let us explore a purchase order contract developed using the Solidity programming language. 

A Solidity smart contract follows a standard structure, comprising ‘data’ and ‘function.’ While data maintains the current state of the smart contract, the function applies logic to transition this state. 

The contract begins with the statement called ‘pragma directive.’ The keyword “pragma” enables compiler checks or features. Consider the statement below:

pragma solidity >=0.4.0 <=0.6.0

The declaration intends to ensure that the smart contract will not compile with a compiler version earlier than 0.40 and after 0.60. 

Next comes the ‘contract declaration.’ The following statement uses the “contract” keyword and identifies an empty contract by the name “Purchase Order.” 

contract PurchaseOrder{}

In-Demand Software Development Skills

Storing data

Every contract or computer program has data stored in it. Variables provide a way to store, label, retrieve, and manipulate the data. There exist two types of variables in Solidity – Value, and Reference. The value type variables are always copied when used as function arguments, such as booleans, integers, etc.

Whereas, reference type variables store the data location. Any change in one reference variable affects another variable. Therefore, they have to be managed carefully. Examples include Arrays and Structs. 

Adding data

In a purchase order would typically have a product quantity associated with it. So, now, let us add a data variable to the smart contract. We will add a variable product_quantity with the assumption that it will have only positive values. 

First, we introduce an unsigned integer represented by uint256. Here, unsigned (u) means the type of variable that can only represent positive integers, and 256 signifies the storage of 256 bits. 

contract Purchase Order{uint256 product_quantity;}

Constructor

The constructor initializes the smart contract with some values when the contract is deployed. Suppose the product quantity is set at 100. 

constructor() public{product_quantity = 100;}

It should be noted that the keyword or access modifier “public” specifies that the function is not restricted. So, it can be accessed by anyone. 

Adding functions

Adding functions makes your program interactive. These are controlled capabilities preceded by the keyword “function.” The declaration includes the function name, access modifier, state mutator, and return value. 

To read the stored value, we add the “get function.” With “get_quantity,” this function gets the capability to retrieve or read the stored data. Look at the statement given below. 

function get_quantity() public view returns(uint256){return product_quantity;}

Breaking it down further, we see that:

  • Function name: get_quantity (The “()” mean that no parameters are passed)
  • Access Modifier: public (access is not restricted)
  • State Mutator: view (indicates that the function does not change the state of the contract, but only reads it)
  • Returns: defines what is returned by the function, i.e., a variable of type uint256

Setter functions

The setter function comes into the picture when you want to write or update the data. This function takes an input parameter from the user, based on which it updates the value of the “product_quantity” variable. The set function (update_quantity) is plugged like this: 

update_quantity(uint256 value) public {product_quantity = product_quantity + value;}

Now, plug all the statements given above to write your first smart contract

Explore Our Software Development Free Courses

Deploying the smart contract

Once you are through with the steps as mentioned earlier, it is time to test your smart contract. You can do the same using Remix IDE, which provides Solidity compiler capability to create, test, and validate your smart contract online. 

Here are the stepwise instructions to design and deploy a smart contract with Remix Online IDE:

  1. Click on the plus icon to create a new (empty) file
  2. Click to open the empty file
  3. Paste your contract into this file
  4. Go to the left menu and click on the second icon, just below the file icon. With this, the solidity compiler option will appear
  5. Go to the compiler label to select the compiler version
  6. Click on the file to compile the smart contract
  7. After compilation, click on the compiler details button to understand the bytecode and application binary interface. Bytecode contains the operational code of Ethereum and smart contract logic after conversion and compilation
  8. In the left menu, click on the icon below the compile icon to deploy your smart contract 

Interacting with the deployed contract

Ads of upGrad blog

The public methods mentioned in the contract provide ways to interact with the deployed contract. In the context of the Purchase Order, “update_quantity” and “get_quantity” are the two interaction methods available. You can also input your parameters using the input box. Remember that any operation that changes the contract variables will result in a transaction. 

With this, we have covered the basics of how to write your first smart contract, and how to test and deploy it using the Solidity programming language in an online development environment. We also understood the process of interacting with a smart contract and initiating transactions. So, apply your learning and create a smart contract today. After all, practice makes perfect! 

Wrapping Up

There is a rise in careers in blockchain technology and blockchain has tremendously changed the very face of the technology industry forever.  If you’re interested to become a blockchain developer and build smart contracts and chain codes, checkout IIIT-B & upGrad’s Advanced certificate program in blockchain technology

Profile

Mayank Sahu

Blog Author
Mayank Sahu is the Program Marketing Manager with upGrad for all emerging technology vertical. His past experience is in analytics industry extensively in healthcare Domain. Mayank has completed his Graduation from IIT Delhi.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Popular Blockchain Course

Frequently Asked Questions (FAQs)

1What are some possible applications of smart contracts?

Smart contracts are computer programs that carry out the conditions of a contract automatically. They use blockchain technology, which is a distributed database that enables secure, transparent, and tamper-proof transactions. Car rental, hotel reservations, and event tickets are just a few examples of how smart contracts might be employed.

2Why are smart contracts considered more secure than regular contracts?

Because smart contracts are implemented on a blockchain network, they are considered more secure than traditional contracts. A blockchain is a cryptographically secured distributed database. This means that the information on the blockchain cannot be tampered with or hacked. As a result, a smart contract's execution is guaranteed to be precise and dependable. They're also public and auditable, which means everyone on the blockchain can view the contract's conditions and check that it's being carried out. On the other hand, smart contracts can help to lower the risk of fraud and conflicts. The bottom line is that they have a lot of features and are easy to use.

3Why are smart contracts becoming more popular?

One of the most essential advantages of smart contracts is that they may assist organizations in automating procedures and lowering costs. For example, a company may utilize a smart agreement to pay its suppliers immediately after a delivery is made. This would reduce the need for the company to process payments manually, saving both time and money. It can also be used to build trust between companies and their customers. For example, a smart contract could be used to construct a secure online payment system. This would allow customers to make payments without fear of their personal information being compromised. Last but not least, it can be used to construct digital identities for both people and businesses. Businesses would be able to authenticate their customers' identities and protect them from fraud as a result of this.

Explore Free Courses

Suggested Blogs

Top 12 Highest Paying Blockchain Jobs in India [A Complete Report]
900287
Blockchain is an emerging job skill in the IT industry. Technological advancements are gradually bringing this distributed ledger technology to the ma
Read More

by Mayank Sahu

19 Feb 2024

Skills Needed to Become a Blockchain Developer
53723
Blockchain development is one of the fastest-growing sectors. Companies are looking for blockchain developers to make new implementations, advance the
Read More

by Mayank Sahu

Prerequisites to Learn Blockchain Technology: It&#8217;s Not What You Think It Is
53963
There has been a massive development in the field of Blockchain technology in the last decade. Many people and companies came to know about Blockchain
Read More

by Mayank Sahu

16 Feb 2024

Blockchain Developer Salary in India 2024 [For Freshers &amp; Experienced]
901955
The Blockchain Era is has arrived, and it is now. Enterprises across various sectors of the industry are warming up to the concept of the decentralize
Read More

by upGrad

11 Feb 2024

Top 10 Interesting Blockchain Project Ideas for Beginners/Students [2024]
174981
Summary: In this Article, you will learn top 10 interesting blockchain project Ideas for beginners. Trusted Crowdfunding Platform Using a Smart Cont
Read More

by upGrad

14 Jan 2024

Blockchain Applications in Supply Chain
5614
The distributed-nature technology of Blockchain has disrupted many industries, with its uses and blockchain applications in supply chain leading to in
Read More

by Radhika Maloo

28 Aug 2023

Applications of Blockchain in Healthcare Industry
6541
After taking the finance and business sector by storm, Blockchain applications in healthcare are now all set to radicalize the healthcare industry. Ev
Read More

by Shubham Chakraborty

23 Aug 2023

What is Ripple Blockchain? Everything You Need to Know in 2024
7143
Ripple is a popular name in the tech industry. And Ripple blockchain has created a lot of buzzes. We all know how blockchain is transforming the indus
Read More

by Mayank Sahu

21 Aug 2023

How Blockchain in Transforming Manufacturing Industry [2024]
6117
How Today’s Large Scale Industries Leverage Blockchain to Scale Their Manufacturing Process As a foundation for distributed ledgers, blockchain is an
Read More

by Mayank Sahu

26 Jun 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon