Smart Contracts

What Are Smart Contracts And How To Write Them - A Complete Guide

Blockchain technology is rapidly growing and making its presence in various industries. It is going to dominate the world in the future, with heavy operations being dependent on it. blockchain technology has made its presence in the financial sector, as well as the educational sector. It has spread its wings towards healthcare in recent times.

However, working with Blockchain might seem intimidating for beginners. It comes with some terminologies that might seem overwhelming at first. This is why we are here to help upcoming blockchain developers to get used to the terminologies associated with the tech. One such term is ‘Smart Contracts.’ In this article, we will discuss what ‘Smart Contracts’ are and how to write them.

What are Smart Contracts?

smart contracts

Smart contracts are programmes that run when specific conditions are met and are recorded on a blockchain. They are often used to streamline the implementation of a contract so that all parties can be certain of the conclusion immediately, without the involvement of an intermediary or time lost. They can also streamline a workflow by triggering the next activity when certain conditions are met.

Advantages of Smart Contracts

Speedy, Efficient and Accurate

When a requirement is met, the agreement is immediately executed. Since smart contracts are electronic and automated, there is no documentation to process and no time spent rectifying errors that frequently occur when filling out forms manually.

Trustworthy and Transparent

There is no reason to wonder whether information has been manipulated for personal gain because there is no third party involved and encrypted records of transactions are transmitted between participants.

Security

Blockchain transaction data are encrypted, making them extremely difficult to hack. Furthermore, because each record on a distributed ledger is linked to the preceding and subsequent entries, hackers would have to change the entire chain to change a particular document.

Savings

Smart contracts reduce the need for intermediaries to complete transactions, in addition to the associated time delays and costs.

How to write your first Smart Contract?

smart contracts

Structure of Smart Contract

The gaming industry’s adoption of NFT is still in its early phases, thus despite the numerous benefits it offers, it still faces considerable challenges. Despite these challenges, NFTs have acquired prominence in the gaming industry, since they have the ability to revolutionise how gamers consume online games and make in-game asset purchases

Pragma Directive

Certain compilation features or checks can be enabled by using the “pragma” keyword. The sentence below specifies that the source file (smart contract) will not compile with compiler versions before 0.4.0 and after 0.6.0. This declaration assures that when a new compiler version is introduced, no unexpected behaviour is introduced.

1

pragma solidity >=0.4.0 <=0.6.0

Contract Declaration

The keyword “contract” is used to declare the contract. This declaration creates an empty contract with the name “Purchase Order.”

1

2

contract Purchase Order

{ }

Storing necessary information to the contract

Any contract, or more broadly, every programme, may involve the storage of some data. Providing data to the application gives it more versatility. A key feature is a transition from hard-coded values in the software to user-supplied values. Variables enable you to store data, label data, retrieve data, and alter data.

Smart Contract Development: Introducing Variables

In solidity, the variables are of two types

  1. Value Type: These variables are provided by value, which means that they are always copied when used as function arguments or in assignments. Integers, booleans, addresses, and so on.

  2. Reference Type: These variables are of complex kinds and are passed by reference; they do not fit into 256 bits and must be maintained carefully because copying them is costly.

Adding data to Smart Contract

Let’s include a data variable in the contract. Every purchase order must be accompanied by some amount of merchandise. Let’s add a variable called product quantity with the data type integer or number.

The variable we are adding now is an unsigned integer denoted by uint256, where 256 denotes 256 bits of storage.

  • U- unsigned (meaning this type can only represent positive integers, not positive and negative integers)
  • INT- integer
  • 256- 256 bits in size
  • minimum value uint256 can be assigned is 0
  • maximum value uint256 can be assigned is 2^256-1 [a very large number]

Product amount is only a positive variable, and we are currently assuming that we will cater to a very large value for inventory level.

The specified “product quantity” variable is part of the contract state and so maintained or stored in contract space. This variable currently has a default value of 0.

1

2

3

contract PurchaseOrder{

   uint256 product_quantity;

}

Defining constructor

When the agreement is deployed, the function Object() { [native code] } is invoked. The function Object() { [native code] } fills the contract with values. When the contract is deployed, the product quantity is set to 100 in the current circumstance. A parameterized function Object() { [native code] } can be formed by supplying a variable and initialising product quantity with the value supplied.

The access modifier “public” linked with the function Object() { [native code] } is important to note here. The public keyword indicates that this function is open to everybody; it is not limited.

1

2

3

constructor() public{

product_quantity = 100;

}

Adding functions

Let’s now add a function to our software to make it more interactive. Functions are program-controlled capabilities that can be introduced. The keyword function comes before any function. The function declaration looks like this: “function function name> access modified> state mutator> return value>”.

Get function

Reading the stored value is one of the most basic attributes for any software. We’ll need to read the “product quantity” variable in the following contract. A read function or a get function is introduced to give this capability. We are not manipulating the stored value in this function; instead, we are simply obtaining it.

Let us now dissect our get function (get quantity).

No.KeywordValue
1.<function name>get_quantity(){no parameters are passed}
2.<access modifier>public {anyone can access the function}
3.<state-mutator>view denotes that the function just examines the state of the agreement and does not alter it; therefore, view.
4.<returns>returns a variable of type uint256 defined by what the function returns

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

Setter functions

Viewing the data is required, as we showed in the previous section, but most scenarios also necessitate the opportunity to write the data. The addition of a setter function provides this specific feature. This function accepts a value from the user as an input parameter. The value of the variable “product quantity” is written to/updated using the value provided to the function by the user.

Let us now deconstruct our set function (update quantity).

Including a function for updating the value of the product quantity

No. Keyword Value
1. <function name> update_quantity (uint256 value){parameter value of type uint256 is passed }
2. <access modifier> public {anyone can access the function}
3. <state-mutator> It is not necessary because the functions update the state.
4. <returns> returns a variable of type uint256 defined by what the function returns
1 2 3 function update_quantity(uint256 value) public { product_quantity = product_quantity + value; } When all of information is added up, this is how the final contract should look. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 pragma solidity >=0.4.0 <=0.6.0; contract PurchaseOrder{ uint256 product_quantity; //state variable /*Called with the contract is deployed and initializes the value*/ constructor() public{ product_quantity = 100; } // Get Function function get_quantity() public view returns(uint256){ return product_quantity; } // Set Function function update_quantity(uint256 value) public { product_quantity = product_quantity + value; } }

Deploying the Smart Contract

It’s time to put the smart contract to the test. We will utilise Remix Online IDE to test this smart contract.

Remix is an online Ethereum smart contract playground. Remix is entirely browser-based. Remix provides an online IDE (Integrated development environment) for creating smart contracts. Remix includes an online solidity compiler feature. The smart contract in Remix IDE can be effortlessly compiled using a specified compiler version.

Remix also allows you to quickly test the smart contract.

Remix provides a complete toolkit for starting smart contract development and unit testing without requiring any installation on your local PC. This is really useful for developers who are just getting started with solidity because they only need to focus on building a smart contract rather than worrying about the infrastructure.

To begin with smart contract development with Remix IDE, all you require is a browser and an internet connection. Rapid development, testing, and validation of a smart contract concept.

Remix’s user interface has just been updated.

smart contract

When you click on the file icon marked in the above image, a file explorer window will open.

  1. A new document can be generated by clicking the + icon and naming it PurchaseOrder.sol.
  2. This will generate an empty file called PurchaseOrder.sol, which you may open by clicking on it.
  3. Let’s copy and paste the entire contract into PurchaseOrder.sol.
  4. Click on the second icon, which should appear in the left menu directly below the file icon.
  5. Choose the compiler version under the Compiler title. The version currently in use is 0.5.8.
  6. After selecting the compiler version, click “Compile PurchaseOrder.sol.” The smart contract will be compiled as a result of this.
smart contract

7. When the smart contract has successfully been compiled, click the “Compilation Details” button, and the following information should appear. Following compilation, two key pieces of information are made available.

  • ABI stands for application binary interface. This is a json file that contains information about all of the methods provided by the smart contract, as well as metadata about the methods.
  • Bytecode is the operating code of the Ethereum virtual machine. Smart contract logic is turned into bytecode during compilation.

8. The smart contract must first be deployed in order to be tested. To deploy the smart contract, navigate to the next icon in the left menu, just below the compile icon. The screen below will appear. The smart contract must first be deployed in order to be tested. Click the next icon in the left menu, below the compilation icon, to deploy the smart contract. The screen below will appear.

smart contracts

Deployment Option

The deployment screen offers a few options; let’s go over them one by one

  • Environment: This is akin to deciding to buy a laptop from Amazon, Flipkart, or Newegg (all of which are online retailers); you choose where you want to purchase from based on your needs. Similarly, in the case of Remix, you have the option of deploying and testing the smart contract. There are three options in the dropdown next to the environment label.

    JavaScript VM- In the browser memory, a local Ethereum single node is spun up, providing 5 pre-funded test accounts that can be used for the transactions (deployment, invoking functions)

    2. Injected Web3 Provide – This is dependent on MetaMask. Metamask functions as a broker or middleman, allowing web apps to interface with smart contracts. Metamask enables the management of identities as well as the signature of transactions transmitted to the Ethereum network. This middleman or third party will assist you in determining which blockchain network the smart contract will be put on.

    3. Web3 Provider – This option is accessible if you are operating a local Ethereum node and an RPC endpoint is available. The smart contract will be installed on the local Ethereum node.

  • Accounts: The environment selected populates this information. As an example, JavaScript VM comes with five pre-funded test accounts. Web3 providers and Injected Web3 do not offer pre-funded test accounts.
  • Gas limit: This is the most Gas that the initiator is ready to spend on any transaction. In the event of an infinite loop, this is the spot to protect against emptying all cash in the account.
  • Value: The value that may need to be sent while establishing the smart contract. This is a boolean value.

To deploy the contract, select the JavaScript VM option, then choose the initial account from the accounts drop-down, taking note of the account balance (100 ether).

Make sure the smart contract name displayed is PurchaseOrder, then click deploy. Key events that will occur

  1. The transaction fee for deploying the smart contract is subtracted from the account balance, which changes from 100 ether to 99.999999 ether.
  2. Under deployed contract, a new smart contract tile will appear, along with the address of the new smart contract, similar to this (0x692a70d2e424a56d2c6c27aa97d1a86395877b3a)
  3. The following information will be displayed in the console window:
  4. Transaction hash – uniquely identifies the contract deployment
  5. Transaction cost
  6. Contract address
smart contracts

Interacting with the deployed contract

  1. The following two interaction methods are accessible under the deployed contract: update quantity and get quantity.
  2. These two interaction methods are defined in the “Purchase Order” contract as public methods.
  3. Quantity of updates The “update quantity” method requires an input argument, which is why the input box exists.
  4. The “get quantity” method returns the value of the product quantity.
  5. Let’s see what happens when we call get quantity; the return value 100, which was set in the function Object() { [native code] }, is displayed. This does not result in a transaction.
  6. Let us use update quantity with 30 as input. This results in a transaction.

In a word, any operation that triggers a write operation to the contract’s state (i.e. alters the contract variables) results in a transaction.

smart contracts

Any activity that just reads the contract’s state does not result in a transaction.

Smart Contract Development Conclusion
smart contracts

We have only scratched the surface of solidity by creating our first smart contract. We’ve just seen everything it requires to test a smart contract, from deploying it to beginning transactions.

Share This Post
Facebook
Twitter
Telegram
WhatsApp
Tumblr
Reddit
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *