how to write smart contract

The first widely recognized use of blockchain technology was Bitcoin, a peer-to-peer system created specifically to enable value transfer without the need for a third party. It was likely the most reliable implementation of blockchain applications and continues to function well today.

However, without a few crucial technologies that were added to the limited features of Bitcoin, Blockchain would not have advanced to the forefront of technological breakthroughs. Smart contracts were a crucial pillar of that revolution. Smart contracts have many benefits for businesses, including trust, transparency, security, autonomy, and accuracy.

Nick Szabo first used the term “smart contract” in 1997. On the blockchain, smart contracts are nothing more than programs. Calls from external methods or calls from other smart contracts can be utilized to interact with these “smart contracts.” These smart contracts are carried out by the EVM (Ethereum Virtual Machine). When correctly constructed and reviewed, smart contracts can decrease malicious exceptions, fraudulent losses, and the requirement for a trusted intermediary.

The way that individuals and businesses interact could be completely revolutionized by smart contracts. However, because this technology is still in its infancy, many software developers are unsure of how to design and use smart contracts. Having the ability to build smart contracts provides you with a competitive advantage regardless of the technology you choose.

This blog post will go through how to write smart contract, deploy their fundamentals, and their working, and deployment operations. Let’s start with the basics of smart contracts.

Smart Contract Defined

In reaction to the fulfillment of specific requirements, smart contracts are computer programs or protocols for automatic transactions that are kept on a Blockchain. In other words, smart contracts automate the execution of contracts so that all parties can quickly discern the result without needing a middleman or a waiting period.

  • Self-executing contracts, known as “smart contracts,” are those in which the terms of the buyer-seller contract are written directly into lines of code.
  • According to American computer scientist Nick Szabo, smart contracts are computerized transaction protocols that carry out contract terms. Szabo created the virtual currency “Bit Gold” in 1998.
  • Its use renders transactions visible, irreversible, and traceable.

Application of smart contract includes:

  • Transferring funds
  • Recording ownership property
  • Voting
  • Warehouse stocktaking

Because they are permissionless and don’t need a central trusted authority to validate transactions, blockchains have an advantage over traditional databases. For example, a contract can instead be made directly between two parties without the use of a middleman.

This is all about smart contracts. If you want to know more about how to write smart contract and deploy it, keep reading this blog.

How to Write Smart Contract?

Before learning how to construct a smart contract, you must comprehend what an EVM and gas are. The EVM or Ethereum Virtual Machine provides a run-time environment for smart contracts. For each transaction with a smart contract, a fee is calculated in terms of gas.

Before you begin,

  • Knowledge of C++ programming language
  • A code editor or an IDE
  • A fully configured local development environment

Look at the guide below, and you will easily learn to write Hello World smart contract.

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 <0.7.0;
contract SimpleStorage {
    uint storedData;
    function set(uint x) public {
        storedData = x;
    function get() public view returns (uint) {
        return storedData;

The code snippet above shows a smart contract created in Solidity language. Let's take time to examine the function of each line of the code we produced for our smart contract.

Line 1: Specifying the SPDX license type; this was added after Solidity 0.68; these licenses can assist in resolving/avoiding copyright concerns anytime the source code of a smart contract is made available to the public. If you don't want to indicate a license type, you can leave the entire remark blank or use the special value UNLICENSED (this won't cause an error, just a warning).

Line 2: The Solidity compiler we want to use is declared on the first line. For example, we are interested in any version that falls between 0.4.0 and 0.7.0.

Line 3: Here, we are stating our agreement and referring to it as Simple storage. Using the same filename as the contract name is standard procedure. For instance, this contract will be saved as SimpleStorage.sol in a file (.sol is the file extension for solidity smart contracts).

Line 4: Data will be stored in the uint (Unsigned Integer) variable we're declaring with the name storeData.

Line 5-7: After that, we'll include a set function, which we'll use to modify the value of the storeData variable. Here, the set function takes an optional parameter named x, whose value is stored in-store data. Additionally, the function is designated as public, making it accessible to all users.

Lines 8-10: To get the value of the storeData variable, we will construct a get method. This function's view designation informs the Solidity compiler that it is a read-only function.

In addition, the get function has returns (uint), which denotes that the function will return a unit.

How to Deploy Smart Contracts?

Once a smart contract has been created, it must be distributed on the Ethereum network. Here we will discuss the four steps that need to be followed to deploy a smart contract.

Write Smart Contract and Compile It To Receive Bytecode

Source: Stack Overflow

Let's use Solidity to create a getter-setter smart contract. A state variable must be present in the contract, and anyone may read from or write values to it. This exercise can be compared to having a public phone book where anyone can read and write.

LookupContract is the name of the contract, and myDirectory, a state variable of type mapping, is the name of the contract. In Solidity, key-value pairs of data are stored as a type called mappings. You are here translating a string to an int. In Solidity, "uint" is an alias for "uint256," a 256-bit unsigned integer.

Configure Network and Private Key

   module.exports = {
    solidity: '0.8.3',
    networks: {
      mumbai: {
        url: '',
        accounts: [''],

Let's demonstrate using Delhi, the Polygon Testnet. First, replace the old code in hardhat.config.js with the following code.

Select the appropriate version of Solidity, then add your private key and Mumbai RPC. In the official document, a list of RPC is available. You may wish to retain this file on your local computer since it contains your private key.

You can configure additional networks in the networks section, and in step 5, you can select the network to use.

Code for Deployment

Let's start working on the code that will aid in deploying the smart contract now that the environment and configuration file has been set up.

Create the following content in a file named deploy.js within the scripts folder:

   const main = async () => {
    const ContractFactory = await hre.ethers.getContractFactory('your-contract-name') // the file name under 'contracts' folder, without '.sol'
    const Contract = await ContractFactory.deploy(param1, param2, ...) // the constructor params
    await Contract.deployed()
    console.log("Contract deployed to:", Contract.address)
    // // You can test the function.
    // let txn = await nftContract.functionName()
    // // Wait for it to be mined.
    // await txn.wait()
    // console.log("function invoked!")
   const runMain = async () => {
    try {
    await main()
    process.exit(0) // emit the exit event that ends all tasks immediately even if there still are asynchronous operations not done. The shell that executed the node should see the exit code as 0.
    } catch (error) {

Your contract name should not end in ".sol" in line 2. Simply enter myContract here if your contract's filename is myContract.sol.
Put all the arguments that the function Object() { [native code] } of your smart contract needs in line 3.
You can try interacting with your smart contract by calling its functions from lines 7 to 11.

Finally, Deploy

The final step is the simplest; simply issue the command: Delhi: npx hardhat execute scripts/deploy.js

This is how the terminal output should appear:

You will need your smart contract address while creating the front end, so keep it in mind.

Parting Words

Smart contracts have a significant value because dApp development depends on them. They play a big role in creating a decentralized web that is full of innovative and helpful applications. Even with such a crucial component, not everyone is knowledgeable about how to establish smart contracts. This is the rationale behind our decision to examine the principles of developing smart contracts in this post.