Build Your First Ethereum Smart Contract with Solidity

in #technology5 years ago

1. What is Smart Contract?

Smart contracts are self-executing contracts with the terms of the agreement between two or more parties being directly written into lines of code. The code and the agreements contained therein exist across a distributed, decentralized blockchain network.

The concept of the Smart Contract was first proposed by Nick Szabo, An American legal scholar and cryptographer, back in 1994. Szabo defined smart contracts as computerized transaction protocols that execute terms of a contract. Many of his predictions come true in contexts preceding Blockchain technology.

Back then; there was little interest or activity using the idea of the smart contracts due to the lack of digital platform supporting them. But today, with the growing adoption of the cryptocurrency and blockchain technology, smart contracts are increasingly popular. From this point in this article, we will be exploring the blockchain in particular of Ethereum and smart contract implementation on its node.
So, let's get started.
SK7_3683_1539775853008.png
The figure above explains the journey of writing a code and then deploying it to the Ethereum blockchain. In this article, we will teach you how the above diagram is carried out practically. So, the first phase is writing a smart contract code. But before we get into that let’s first understand some of the tools required to write one.

2. Basic Terms you need to Understand


2.1 Programming Language

There are number of languages that can be used to write smart contracts. But, currently dominating the blockchain world is Solidity which we will be using in this tutorial. Solidity is a programming language that is used for writing smart contracts which runs on Ethereum Virtual Machine of Blockchain. It’s syntax is similar to that of JavaScript and is a contract-oriented, high-level language.

Since a community on Ethereum blockchain development is increasing, there are several upcoming projects for creating languages for writing and managing smart contracts. Some of the them that you might be interested to look at are:

  • Vyper
  • List
  • Chain

2.2 Remix IDE (Browser-based IDE)

It is a web IDE for writing and executing Ethereum smart contracts. It is used to run your code with any version of solidity and against any Ethereum node (even local). It’s a good place to start hacking smart contracts and understand the development process. I wouldn’t recommend using it for any production development though. We will get familiar and dive deep into it during the process of writing smart contracts.

2.3 Metamask

MetaMask is the way to browse blockchain application and connect to Ethereum through a browser. It holds your private key so that your identity can be used to sign transactions and broadcast it to the blockchain. MetaMask is a running light node, installed as a Chrome extension. Before getting in the tutorial, install metamask in your browser by simply searching for it in the webstore. You will be asked to enter a password and then you are all set for using metamask.

2.4 Etherscan

Etherscan is a block explorer that gives you the UI for getting information about the main Ethereum networks. It is used to search for addresses, transactions, smart contracts and tokens, trace any movement of Ether or flow of transactions. You can even read smart contracts’ source code and get gas usage of any transaction. We can even use this for test nets such as Ropsten or Rinkeby.

2.5 Ethereum Virtual Machine (EVM)

Ethereum Virtual Machine provides a runtime environment for smart contracts based on Ethereum. Just like all Blockchains, Ethereum leverages on multiple nodes that run software on their computer to ensure security as well as maintain trust. Each node that takes part in the Ethereum protocol runs software on their computer which is referred to as Ethereum Virtual Machine (EVM). EVM guarantees security by preventing Denial-of-service attacks and also, interprets and executes the bytecode generated after compiling a smart contract and ensures that communication can be achieved without any interference.

3. Writing our first Solidity Smart Contract


So, let us start by writing a simple smart contract to add and subtract a variable by 1 and then deploying it to a test network. For this, we will be taking it a step at a time.

Step 1: We need to open the remix IDE. So, open http://remix.ethereum.org/ on your browser and start writing our first smart contract.

pragma solidity ^0.4.0;

contract Counter {
int private countValue= 0; // state variable
function incrementCounter() public { // increment function
countValue += 1;
}
function decrementCounter() public { // decrement function
countValue -= 1;
}
function getCount() public constant returns (int) {
return countValue;
}
}

So, as in the code, the pragma here defines the version of solidity that will not compile with a compiler earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0 (this second condition is added by using ^). Then, we are defining a contract called Counter. These contracts can be considered similar as a class in oobject-orientedlanguages. These classes contain data in state variables and functions that are used to modify these variables. Here, countValue is a state variable that holds a value and we have functions such as incrementCounter and decrementCounter to modify the countValue variable. Also, the state variable here is private which means they are only visible for the contract that they are defined in and not in the derived contracts. A general structure of a smart contract would be as above in the code.

4. Compiling smart contract


We can compile our contract by clicking on the “start to compile” button available on the right-hand side of Remix which will generate the required bytecode and ABI and other major details which can be seen by clicking in the Details button located aside of the compile button. After clicking on it, the details modal dialog displays the detailed information about the current selected contract.

4.1 Bytecode
htmlupload-1535006997727.png
Bytecodes are the hexadecimal representation of any smart contract. Every data we feed into EVM is treated as hexadecimal code. So, the object property inside the bytecode section of the remix browser(i.e. the hexadecimal representation of our smart contract) is used for deploying our smart contract in the Ethereum blockchain. The EVM is going to run this bytecode whenever we carry out a transaction.
4.2 OpCode
htmlupload-1535007073414.png
While bytecode is the hexadecimal representation of the smart contract, opcode is simply a low level representation of the smart contract that the humans can understand. These opcodes can be used to understand bytecodes. As we can see, the opcodes start with PUSH1 0x80 PUSH1 0x40 MSTORE. This can be converted into hexadecimal values and bytecodes are formed. We know, the hexadecimal value of PUSH1 is “0x60” and that of MSTORE is “0x55”. Using this to convert opcodes into bytecodes and removing the hex-form “0x”, we get a bytecode by replacing the keywords with its hexadecimal values resulting in “6080604052” which can be seen is the starting values of the actual bytecode. In fact, we can see every bytecode starting with this value because this is how any smart contract would bootstrap.

4.3 ABI
htmlupload-1535007249871.png
ABI, Application Binary Interface, basically is a medium in order to call functions in a contract and get the data back. A smart contract is basically a bytecode deployed on the Ethereum blockchain. There could be several functions in a contract and ABI is necessary so that you can specify which function in the contract you would like to call, as well as guarantee that the function will return data in the format you are expecting.

As we can see in the ABI section of the detail modal, it consists of an array of 3 objects where each object represents our functions in the smart contract. That means, the object “0” is the incrementCounter function. Similarly, the object “1” contains our getCount function and lastly, the object “2” contains our decrementCounter function.

5. Deploying Smart Contract


5.1 Install MetaMask

MetaMask is a browser extension that is used in order to connect to the Ethereum blockchain. We need an Ethereum account to deploy our smart contract and MetaMask handles this very well for us. If you did not install metamask earlier, here’s a procedure to do so.

You can install from this link: https://metamask.io/

After installing MetaMask it will ask you to setup your account, then you can choose a different network of Ethereum, for this tutorial we will be selecting a Ropsten testnet. And in order to get some ether for deploying the contract, you can request some ether from the ropsten faucet. Simply click the deposit button and then the get ether button.
htmlupload-1535007464208.png
Deploy the contract on the Ethereum Network
We can do this by navigating on to the “run” tab of the remix browser. Here, we need to understand basic terms before deploying our contract.

Deploy the contract on the Ethereum Network
We can do this by navigating on to the “run” tab of the remix browser. Here, we need to understand basic terms before deploying our contract.

htmlupload-1535007589904.png
a. Environment

The Remix IDE provides many environments for executing the transactions:

JavaScript VM: It will run an isolated ethereum node in the browser using Javascript.
Injected Web3: It uses the "Web3 provider" embedded in the browser. For example ,MetaMask extension will embed a "Web3 provider", you can configure to connect that provider to a testnet or to mainnet. This allow to interact with a real network.
Web3 Provider: It will ask for you to supply the RPC address of a ethereum client. This provides maximum control, you connect to your own node. For example, a remote node with geth, parity or any Ethereum client.
b. Account

We will be deploying our smart contract using this account. So, this account must have enough ether to cover the gas required for deploying our contract.

c. Gas Limit

Every operation on the Ethereum platform costs a certain number of gas. The operations that require more computational resources costs more gas than the operations that require few computational resources. Whenever we specify some gas amount for a transaction in Ethereum, there are two components to take into consideration. First one is the gas Limit. Relating an ethereum transaction to that of a car, the total gallons of gas to put in the tank of car is considered as gasLimit in an ethereum transaction. Note that this amount affects the execution of our smart contract and it must be sufficient for all of the resources that is required by our smart contract. Otherwise, it returns an Out of Gas Exception. Here, MetaMask attempts to make their best guess at this value and is more or less right. A key point here is that any unused gas for the transaction will be returned to the user. So, when you set a gas limit of 300,000 and let’s say the transaction only takes 200,000 — you won’t be charged for 300,000 and the remaining gas is returned to your account. The gas limit isn’t the value that specifies how much you have to spend, rather it’s value shows how much you are willing to spend.

Second, is the gas price. It determines the speed at which the transaction is added to the block and is typically denoted in gwei(10⁹ wei). However, it does not affect the execution of transaction. That means, higher the gas price, the more faster the transaction is added to the block. Considering the previous car analogy, the price that you pay for a unit of gallon of gas is considered as gas price. So, the total gas amount to carry out an ethereum transaction is calculated by my multiplying the gas consumed in carrying out a transaction and gas Price. So, Total Gas amount = gas used by tx * gas price

d. Value

Since, we are not sending any ether to a person, we will leave this field as 0 which can be understood as (not necessarily) that we are carrying out this transaction related to smart contract.

  1. Deploy our smart contract

We can now deploy our contract by clicking the deploy button. After clicking the deploy button you can see a transaction initiation log on console section of Remix IDE like shown below, which provides a link to view exact status of our transaction.
htmlupload-1535008624567.png
Our smart contract is now assigned an address which is the unique identity of our application. We can call any of the function of our application using this address. After successful deployment of contract, Remix will provide us with an interface to interact with our contract with its address and available functions at below section of Run tab.
htmlupload-1535008674541.png
In above figure we can see, there are three buttons available for us to interact with our contract. If you look closely, they are the exact replica of our three functions that we have written in our contract code and they are incrementCounter, decrementCounter and getCount. Now you can click on those buttons to increase or decrease the value of count. All changes will take place on Ethereum blockchain having no central authority to change value whatsoever. Pretty cool right?

This will be the end of this article about creating and deploying simple contract on Ethereum blockchain using just two tools i.e. MetaMask and Remix IDE. In next article, we will move on to explore more complex and real-time usages of contracts.

Sort:  

✅ Enjoy the vote! For more amazing content, please follow @themadcurator for a chance to receive more free votes!

Hello @avsek! This is a friendly reminder that you have 3000 Partiko Points unclaimed in your Partiko account!

Partiko is a fast and beautiful mobile app for Steem, and it’s the most popular Steem mobile app out there! Download Partiko using the link below and login using SteemConnect to claim your 3000 Partiko points! You can easily convert them into Steem token!

https://partiko.app/referral/partiko

Congratulations @avsek! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.36
TRX 0.12
JST 0.040
BTC 70446.49
ETH 3571.68
USDT 1.00
SBD 4.73