• How to write your first smart contract in solidity

How to write your first smart contract in solidity

The problem with learning to code on ethereum smart contracts is to know where to start from. After just learning about blockchains and ethereum, you try to google, in the hopes of getting started but you are stymied looking at dozen possible options with complicated stuff you don’t understand. You wanted to make a Dapp that would eventually go on a blockchain, but can’t even begin to begin.

Well, there is a good news. Creating a smart contract doesn’t have to be that daunting. With just a basic understanding of any object oriented language (C++, C, java, etc), the right tools and set-up at your disposal, you could easily create simple to complex smart contracts and test them out in little to no time- without needing to get into the pain of knowing how to deploy the contracts (though you will eventually need to know about the Dapp frameworks and tools)

Follow this link (https://remix.ethereum.org/) to browser-solidity to kickstart your journey to coding smart contracts.  All the codes will be written in solidity in this tutorial. Browser-solidity is mostly used for debugging code but it is more than enough to get a start. We assume you have basic understanding of blockchains and how they work. In this demonstration :-

  1. You will learn how to use browser-solidity.
  1. And how to write a simple token sale contract and call its methods.

When we’re done you’ll know exactly how to write some deep looking smart contract code, ready to dive into the complicated task of actually deploying the contract to a live blockchain.

  1. Getting started with browser-solidity

After you click on the browser solidity link (make sure you use that link), you will find a default smart contract named ‘ballot.sol’ (don’t worry if you don’t) in an interface as shown below.

 

The panel on the right has a few options that you should know about in order to call the contract functions properly:-

    1. The Contract Tab is where the transactions take place. You can select the development environment, the accounts and the gas limit and value.
      1. The environment tab allows you to select between running the contract on a web3 provider , injected Web3 and javascript VM. A web3 provider connects to an actual node or a localhost. The injected Web3 uses the environment provided by mist. We will use javascript VM where everything is local and in memory of browser-solidity.
      2. You can select the user accounts available, according to your environment in the accounts list. Selecting an account from the list is equivalent to ‘logging into’ the account. Transactions will take place from the account thereon. The addresses can be copied by using the button adjacent to the dropdown.
      3. Gas limit sets the maximum gas allowed for each transaction.
      4. Value corresponds to msg.value, or the ethers, the default cryptocurrency used in the ethereum blockchain, that will be transferred with each payable function. The default currency we will use here is Wei. Make sure that the amount you enter in the value box trails by the tag ‘wei’. For ex-: ‘10 wei’.

 

  1. The settings tab deals with compiler related options. You don’t need to deal with it, unless you want to change the compiler version or if you need to compile the code (when auto compile is switched off)
  2. Under the files tab you have option to publish all your files to a public github gist or to copy it to another browser-solidity instance.
  3. The debugger will allow you to run the code line by line in case you get stuck somewhere with your smart contract. It will become a very powerful tool when you start writing your own smart contracts.

Our first job would be to start the javascript VM which allows us to simulate a blockchain inside the browser-solidity interface.

Under the contract tab, in the environment drop down list, select javascript VM.

When you are done you will be able to see  5 accounts in the accounts drop down list below having ample amount of ethers each (don’t worry if all of them don’t). You will be needing them in order to access the smart contracts.

To add or open contracts, you can access the panel on the left.

The third icon from the left in this panel connects you to a localhost. It will allow you to synchronise the changes that you make in browser solidity to your local files. You can find the steps to set it up by clicking on it.

  1. A Simple Token Sale Contract

You won’t be needing the Ballot.sol smart contract which you find in browser-solidity by default. Delete it and add a new file (by double clicking Ballot.sol in the left panel) naming it TokenSale.sol.

A token sale can be thought to be similar to an IPO (Initial public offering), where the token contract is owned by an XYZ company and anyone can buy tokens/shares. In simple words, this will be a smart contract where users can buy shares of that company. This tutorial will cover just the basics, i.e buying of the tokens, without complicating the code.

We are now ready to start writing the contract.

A contract resembles a class which has a few methods.. We have 3 methods here, to buy tokens, to check the token balance and to check the ether balance. This will look pretty simple for someone acquainted with any OOP language.

Make sure you understand the code line for line before copying it, to make future implementations easier.

You can find below the code for a very simple Token Sale contract with inline comments explaining each line:

Other little points to note in the code-

  1. msg.value points to the ‘value’ in Contract tab dialog box. That is, when you call the function, msg.value will be equal to the amount you have entered in the ‘value’ dialog box.
  2. msg.sender is the account you have selected from the drop down list.

After you paste this code into the solidity interface, it will automatically compile it. If that doesn’t happen, go to the settings tab and click on compile. Hopefully now, post the compilation, there will be some ethers in each of the
5 accounts. That should do it for you.

Go back to the ‘Contract’ tab.

First, you will have to create the contract using the create button. This will fire up the contract, displaying all the public variables and functions

When the contract is created, you would be able to see a launch debugger and copy address option,  along with the simulated ‘transaction’ and ‘execution’ gas costs. We will go through them one by one :-

  1. The launch debugger opens up the debugger tab allowing you to understand the flow of the code. It becomes easy to identify errors when you face one.
  1. The copy address button sounds self explanatory. It will copy the address of the voting smart contract. Useful for sending ether to the contract, etc. In this case, you will copy the address of the contract to check the ether balance using the checkBalance function after tokens have been bought.
  1. Transaction costs are the costs for sending the contract code to the ethereum blockchain depending on the size of the contract.
  1. Execution costs cover the costs for storing global variables and the runtime of the method calls.

Now, you will also be able to view the public variables and external functions that were created with the contract.
The legend under the ‘value’ dialog box in the right panel shows you what each colour denotes.
The ‘payable’ tag that we added to the buyTokens function makes our function a ‘Transact (payable)’ type function.

Lets start to call the functions.

  1. Select any of the addresses from the dropdown list to make them the transacting account to start buying tokens.
  1. After selecting the address, enter the amount you want to spend to buy tokens in the ‘value’ dialog box. 1 wei fetches you 10 tokens (set by the tokenSwap variable). Write the respective value in wei (for ex:- 10 wei) in the value dialog box. Make sure you write ‘Wei’ after the amount. And make sure the amount is lesser than or equal to 1000 wei.
  1. Now call the function by simply clicking on the buyTokens function.

You will be able to see the transaction and execution costs associated.

Subsequently, you can check if tokens have been deposited to the account by simply copying the address with which you bought the tokens and passing it (“with double quotes”) in the balanceOf function.

The working of the modifier can also be checked by putting a value of over ‘1000 wei’ and you can see it shoots an error. Launch the debugger to see that the code flow gets stuck at the modifier.

You can also check if your contract has received the money (from other accounts buying tokens) in a similar manner by copying the tokenSale contract address (created during initially firing up of the contract) and using the checkbalance function, pretty straigtforward now.

And there it is, if you have been able to call the above methods, you have made a simple smart contract and studied its functionalities in a matter of minutes.

In further posts, we will demonstrate how to make more complicated contracts that will be deployed to a local blockchain, also making the frontend to invoke the functions. We hope this post helped you in getting a very rudimentary understanding of how smart contracts are created, along with some basic solidity functionalities.

You can now change gears and have a further look at the solidity documentation here (http://solidity.readthedocs.io/en/latest/) and have a deeper read on ethereum by using this link (https://github.com/ethereum/wiki/wiki/White-Paper).

The following two tabs change content below.
Techracers

Techracers

Leaders in providing end-to-end blockchain solutions and services. We help businesses build revolutionary products and practices for the new era of digital economy in order to create transformational value for their customers.
July 31st, 2017|Blockchain Tutorials|