Blog

November 5, 2022

How to Create Simple Smart Contract

I.      Introduction

It can be quite challenging, especially if you are new to this field, to learn and understand the technology supporting smart contracts. Even experienced developers are frequently taken aback by how complicated creation of smart contracts might be. With this article, our intent is to delve into basic technical details of creating smart contracts. We will cover where to start coding, how to test your smart contract, and how to launch as well as execute your smart contract.

To understand what the smart contracts are and to easier follow instructions we prepare to create one, you are invited to read our introductory post on smart contracts to familiarize yourself with some of the terminology used, learn how smart contracts work and how they are used in various contexts.

This post will try to teach you how to write your first smart contract using Ethereum, the most popular blockchain technology for smart contracts, and the requirements for generating one. We will also present their implementation in and instructions how to develop one.   

II.      Prerequisites for creating your smart contract

Anyone with enough of enthusiasm (and with enough ETH balance in his pocket) and a bit of programming knowledge, which can be by the way learned, can develop a smart contract and deploy it to the network. Deploying a smart contract requires ETH since they are transaction reward for successfully completed contract, similarly like transfer of assets in traditional contracts. Without ETH, smart contracts may not be deployed to the blockchain and we will explain why later on. In relation to transaction fees, “gas” is a term used to measure the amount of computing work required to do specific tasks on the Ethereum network. The unit of measurement for gas prices is the gwei, which is equivalent to 0.000000001 ETH (10-9 ETH). Gas charges for contract deployment on the Ethereum network are typically substantially higher than those for standard transactions.

To better understand the execution environment, we first need to present Ethereum Virtual Machine (EVM) which serves as a runtime environment for smart contracts built on Ethereum. EVM is not physical but a virtual machine where gas is a measurement unit used for assigning fees to each transaction with a smart contract, each computation happening in the EVM needs some amount of gas. The more complex the computation is, the more the gas is required to run/deploy the smart contracts.

The programming languages Solidity and Vyper are among those supported by Ethereum and are commonly used for creating smart contracts. Solidity is the language developed by Gavin Wood whose goal was to solve the unique problems Ethereum faced in 2014, and it is now the default language of all Ethereum Virtual Machine (EVM) compatible chains. This means that whether you are developing on Ethereum, Avalanche, Polygon, Binance Smart Chain (BSC), or any other EVM chain, you are going to need to know the ins and outs of Solidity. However, there are some chains which do not utilize the EVM and are programmed in different languages. Solana is one additional example of a blockchain which does not use Solidity, but rather the pre-existing languages Rust and C/C++. For the purpose of this article, we will be focusing on EVM chains based on the Solidity as most commonly used language.

It needs to be stressed out that community is very important in the smart contract space in order to keep up with the updates in this area. It would be a good idea to engage on thoughtful forums such as the Smart Contract Research Forum, and chat on Discord to learn and help others learn.

III.      Smart Contract in operation

 As a starting point and for an illustration, we can compare smart contracts operations with a simple vending machine. This example is presented on Ethereum Virtual Machine, a platform with which we frequently work, and based on the logic and rules written in the Solidity programming language. In simple terms, smart contract is a set of computer instructions based on “if this, then that.” Below is the simple example how smart contracts for a vending machine would look from technical perspective through the lens of a computer:

pragma solidity 0.8.7;

contract VendingMachine {

   // Declare state variables of the contract

   address public owner;

   mapping (address => uint) public cupcakeBalances;

   // When ‘VendingMachine’ contract is deployed:

   // 1. set the deploying address as the owner of the contract

   // 2. set the deployed smart contract’s cupcake balance to 100

   constructor() {

       owner = msg.sender;

       cupcakeBalances[address(this)] = 100;

   }

   // Allow the owner to increase the smart contract’s cupcake balance

   function refill(uint amount) public {

       require(msg.sender == owner, “Only the owner can refill.”);

       cupcakeBalances[address(this)] += amount;

   }

  // Allow anyone to purchase cupcakes

   function purchase(uint amount) public payable {

       require(msg.value >= amount * 1 ether, “You must pay at least 1 ETH per cupcake”);

       require(cupcakeBalances[address(this)] >= amount, “Not enough cupcakes in stock to complete this purchase”);

       cupcakeBalances[address(this)] -= amount;

       cupcakeBalances[msg.sender] += amount;

   }

}

On a first side above set of computer instructions looks like a very advanced science and will make most people quite dizzy. If we look the code more closely, the picture become clearer and more logical. In pseudocode, our vending machine example includes following rules or let’s say step-by-step instructions:

In Solidity, we write a smart contract by typing the keyword contract followed by the name of the contract;

pragma solidity 0.8.7;

contract VendingMachine {

We will write our further code in the brackets as all the functions and variables would be a part of it. In next step, we need to define the variables that will be a part of the contract which we are going to program;

   address public owner;

   mapping (address => uint) public cupcakeBalances;

Here, address refers to the wallet address of the owner and mapping refers to a keyword where we can map one type of variable to be associated with another;

“cupcakeBalances” is a mapping where number of cupcakes will be associated with the address. Next, we go on to create a constructor that will be automatically executed when deployment will occur on the Ethereum Blockchain.

   constructor() {

       owner = msg.sender;

       cupcakeBalances[address(this)] = 100;

The creation of first function is getBalance(). It is used to inquire on the balance of cupcakes that are left in the Vending Machine.

cupcakeBalances[address(this)] represents the balance of the cupcakes that are associated with the current Ethereum account.

Function that is next is called refill(). It is restricted only to the owner and thus, the keyword comes as requirement.

The cupcakeBalances gets updated when the amount is entered by the owner to be incremented.

   function refill(uint amount) public {

       require(msg.sender == owner, “Only the owner can refill.”);

       cupcakeBalances[address(this)] += amount;

The last function is the purchase function that helps the person or the customer to purchase a cupcake.

The price for one cupcake that we entered is 1 ETH. Thus, the msg.value should be equal to the amount multiplied by the price of the cupcake which is 1 ETH.

   function purchase(uint amount) public payable {

       require(msg.value >= amount * 1 ether, “You must pay at least 1 ETH per cupcake”);

Code mechanism works if you insert money (which is the 1 ETH per cupcake) + and do snack selection = then the selected snack is dispensed from the machine.

The coding establishes the appropriate logic for balance and refill, stock, and cost per item, and the logic permits actions based on the IFTTT approach whereas IFTTT derives its name from the programming conditional statement “if this, then that.” In the sense that an action, when encountered, triggers one or more automations subsequent action(s).

IV. Step-by-step instructions to develop vending machine smart contract. Let’s experiment!

We will now go through each step of developing vending machine smart contract explained above. First of all, you will need to connect to Alchemy – Blockchain APIs and Node Infrastructure and create an account by clicking on “get started for free”. Once you have set your account up, you will have to create a test environment (APP). So, you choose to create an app, name your project then choose “Goerli” as your network.

No alt text provided for this image

In order to send and receive transactions, we will also need an Ethereum account. You may download and set up a free Metamask account and add it as a browser extension. Make sure to select the “Goerli Test Network” in the upper right toggle after configuring the wallet so you can use the false ETH. Remember these are not real ETH, we will be using just dummy tokens in our attempt and that’s why we select the “Goerli Test Network”.

In the next step, as mentioned hereinabove, in order to deploy your smart contract to the test network, you’ll need either some real ETH, or you can also try to use some “false” ETH, which we will use for our experimentation. To get such ETH you will need to visit Goerli Faucet and enter your Goerli account address, then click “Send Me Eth.” This process can take some time depending on traffic.

 You will notice 0.25 ETH in your Metamask wallet when you check your wallet; this balance is in the gwei denomination that we previously mentioned.

No alt text provided for this image

You must access the composer from the menu, choose Get Balance, and enter your Metamask wallet address in order to double-check the balance on the Alchemy Network.

No alt text provided for this image

You ought to then get this response to your request, and you should be good to go.

No alt text provided for this image

Assuming you already have Visual Studio Code installed on your computer (if not, you must download it), you also need the following software installed: nod.js and the Solidity+Hardhat extension that looks like the one below:

No alt text provided for this image

Once you’ve set everything up, launch Visual Studio Code, select File, New, YourProjectName.sol, and then begin creating your contract in Solidity language. The following will then appear. And now here it is! It’s almost time for your first smart contract.

As you can see, we used the vending machine example from the Ethereum website for this example.

Now we are done with the preparatory stage where we finalized the code writing. Below is how the code looks like on Visual Studio Code. The below code resembles the mechanism to dispense a cupcake from the vending machine, as explained before, if you insert money (which is the 1 ETH per cupcake) + and do snack selection = then the selected snack is dispensed from the machine.

No alt text provided for this image

V. Conclusion

It is true that developing your first contract requires a lot of work and that learning and understanding the technology of smart contracts can be quite challenging, especially if you are new to this field, but you can definitely do it if you put in the necessary effort and have the desire to learn it all.

To summarize, we addressed in this article some key fundamentals that you should be aware of when considering developing your first smart contract, one of which is that deploying a smart contract requires ETH because they are transaction rewards for successfully completed contracts.

We also learned together that on the Ethereum network, gas charges for contract deployment are typically much higher than those for standard transactions. Ethereum supports the programming languages Solidity and Vyper, among others. Some chains do not use the EVM and are written in a different language. Finally, it’s a good idea to participate in thoughtful forums like the Smart Contract Research Forum and chat on Discord to learn and help others learn!

Standard Posts , ,
About Hossam Hesham
Hossam Hesham is an Egyptian legal professional with experience that encompasses working as an in-house banking lawyer, preceded by law firm experience, and most recently he has added to his professional career an experience in banking governance in Italy. Hossam’s experience has an emphasis on contracts and legal advisory. As a passionate lawyer about legal technology, he pursued postgraduate studies and has been conferred a Master’s Degree in Law with a specialization in LegalTech from Lithuania. Hossam has been a member of the Egyptian Bar Association since 2015.

Leave a Reply

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