soliditySmart 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!
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.
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.
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{}
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.
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:
- Click on the plus icon to create a new (empty) file
- Click to open the empty file
- Paste your contract into this file
- Go to the left menu and click on the second icon, just below the file icon. With this, the solidity compiler option will appear
- Go to the compiler label to select the compiler version
- Click on the file to compile the smart contract
- 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
- In the left menu, click on the icon below the compile icon to deploy your smart contract
Interacting with the deployed contract
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.
This article has been published from the source link without modifications to the text. Only the headline has been changed.