The Easiest Way to get into coding solidity

Nidish Ramakrishnan
11 min readMar 3, 2018

--

Introduction

The problem with learning to code ethereum smart contracts is a never ending one, because you don’t know where to start from. After just learning about blockchains and ethereum, you try to google, with the hopes of getting started but you are stymied looking at tons of possible options with stuff that looks like gibberish. You want to deploy a myriad of Dapps to the mainnet, but can’t even begin writing a line of code.

Well, there is a good news. Creating a smart contract doesn’t have to be that challenging. 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. Browser-solidity is mostly used for debugging code but it is more than enough to get a start.

Scope of this tutorial

All the codes will be written in solidity in this tutorial. We assume you have basic understanding of blockchains and how they work. In this demonstration :-

  1. You will learn how to use browser-solidity.
  2. 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.

Note — Remix keeps fixing and updating its interface time and time again. All snapshots taken are at the time of writing this blog, 3rd March 2018(the Remix team doesnt tag releases on github). But if the then interface seems very different to you, you can use the following steps to install and run remix locally-

  1. git clone https://github.com/ethereum/remix-ide.git
  2. cd remix-ide
  3. git reset --hard f6d867650add3bce920609ed2babd1f0741678da
  4. npm install
  5. npm run pullremix
  6. npm run linkremixcore
  7. npm run linkremixlib
  8. npm run linkremixsolidity
  9. npm run linkremixdebugger
  10. npm start

We are all set. Navigate to http://127.0.0.1:8080 on your browser to start coding!

Getting started with browser-solidity

After you start the remix-ide, you will find a default smart contract named ‘ballot.sol’ (don’t worry if you don’t) in an interface as shown below(Just to give you an idea)

Remix interface at start-up

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

The Compile Tab

The compile tab

This is where the compilations happen. You can select which contract to compile from the dropdown list. You can switch on auto-compile(real pain when you have heavy contracts). The details option corresponding to each contract will allow you to view the contract ABIs and method ids(You dont need to know about them for this tutorial)

The Run Tab

This would be used the most by us. After compilation, the contracts get ready to be created in the run tab.

  1. You can change the environment here(which usually decides ‘where’ the contracts get created) as shown in the image in the left. It 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 metamsk. 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 ‘unlocking’ 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’.

The Other Tabs

  1. The settings tab(as seen on the left) deals with compiler related options, general settings that allows you to enable optimization, connecting with remixD that allows you to sync local files to remix, and setting up themes.
  2. The analysis tab allows you to perform a very very low level security audit of your contract. It issues you with static warnings that surely should be looked upon for optimizations.
  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.
  4. The support allows you to contact with someone from the remix team, or with others who might be facing the same problems.

The console

The remix console

Whenever you try to create any type of transaction, you will be able to check out the response in the console. Will be explained in more detail below

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

The run tab

Under the run 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 fifth 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.

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 right 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 6 methods here, one payable method to buy tokens, and other constant methods to read state variables. The structure 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(better copy the code to remix to read through it):

contract TokenSale {
// defining the public variables that the contract will have
// max tokens to be sold
uint256 public tokenCap = 10000;// The number of tokens you can buy for 1 wei uint8 public swapRate = 10;// the total supply sold uint256 public totalSupply;// mapping is an equivalent to associative array. We store token balances corresponding to each address that buys tokens in this mapping. mapping (address => uint256) balances;// A function to check the ether balance of any address. function checkEtherBalance (address addr) external constant returns (uint256) {
return addr.balance;
}
// To check the token balance of any address. The external keyword allows the function to be called from outside the contract. function balanceOf(address tokenHolder) external constant returns (uint256) {
return balances[tokenHolder];
}
// A function to buy tokens accesible by any address. The payable keyword allows the contract to accept ethers from the transactor. The ethers to be deposited is entered as msg.value (which will get clearer when we will call the functions in browser-solidity) and the corresponding tokens are stored in balance[msg.sender] mapping. Underflows and overflows are security consideration which are not checked in the process. But lets not worry about them for now. function buyTokens () external
payable {
require(msg.value*swapRate + totalSupply <= tokenCap);
uint256 tokensAmount = msg.value * swapRate;
balances[msg.sender] += tokensAmount;
totalSupply += tokensAmount;
}
}

Other little points to note in the code-

  1. msg.value points to the ‘value’ in run 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.

NOTE: Never use this code for an actual token. Over-simplified example.

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, you will see the token sale contract in the drop-down list of the run tab. That should do it for you.

Deploying the contract in the VM

Contract methods visible after successful creation of the contract

On the run tab, firstly, you will have to create the contract using the create button. This will fire up the contract, displaying all the public variables and functions. You might notice that the ether balance of your imaginary account just dropped because it takes money to push code to the blockchain like shown in the left.

When the contract is created, you would be able to detect some activity on the console. You would see a creation of TokenSale pending(which honestly doesnt stay ‘pending’ for long). Along with that, the`details` and `debug`options show up. We will go through each of them :-

Details blow up view after successful creation of a contract
  1. The debug option launches the debugger allowing you to understand the flow of the code. It becomes easy to identify errors when you face one.
  2. When you click on details, it looks like greek on the first glance but is all very straightforward.

Status — It tells you the state of the transaction

Contract Address — It displays the address where our contact was deployed to. You can copy this address by clicking on the copy icon on the right hand side panel, next to ‘TokenSale’ where you created your contract. You can copy the address of the contract to check the ether balance using the checkBalance function after tokens have been bought.

From — It is basically the address using which we deployed the contract.

To — The recipient of the transaction which in this case is the contract constructor.

Gas — The gas that was supplied to the transaction

Transaction gas cost — Transaction costs are the costs for sending the contract code to the ethereum blockchain depending on the size of the contract.

Execution gas cost — Execution costs cover the costs for storing global variables and the runtime of the method calls.

Hash — It is the transaction hash. If this was a real blockchain, you could use this hash to search for this transaction whenever you wanted.

Decoded Input — It is the inputs that go in the transaction. In the case of our contract creation, it is the bytecode of our contract, which must be saved on the blockchain(not important for now)

Decoded output — For functions that have a return value, this would display it

Logs — Smart contracts have this functionality of emitting events when certain things happen. So, if our constructor had events, logs would have shown the type and parameters of that event(not important for now)

Value — This is zero for our constructor. This usually displays the amount of ether that was given to transaction. You will be able to see this when we buyTokens

Now, you will also be able to view the public variables and functions that were created with the contract.

Blue coloured functions mean that they are constant functions and dont cost gas to execute. Red coloured ones are state changing functions and will cost you.

The ‘payable’ tag that we added to the buyTokens function makes our function a ‘Transact (payable)’ type function.

Making a transaction on the contract

We are now ready to call the contract functions-

  1. Select any of the addresses from the dropdown list to make them the transacting account to start buying tokens.
  2. 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 swapRate variable). Write the respective value in wei (for ex:- 10) in the value dialog box. Make sure you select ‘Wei’ after the amount. And make sure the amount is lesser than or equal to 1000.
  3. Now call the function by simply clicking on the buyTokens function.
The debugger tab

4. Response can be seen in the console box. You will be able to see the transaction and execution costs associated and this time, in the details, you can see the value to be 10 wei.

5. 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. As we can see from the image on the left, we can check out the solidity state, which is the state of our contract variables at the time of debugging. The ‘step over forward’ button allows us to quickly see the code flow and navigate to the place where the code breaks.

Checking return value from functions

Now that we have bought tokens, you can check how much has 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. This time, check the decoded outputs in the details of the transaction response on the console. And by the way, This transaction didnt punch a hole in your pocket(no gas cost).

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(decoded outputs), should seem pretty easy now.

Conclusion

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. But do remember, this is just tip of the iceberg.

In further posts, we will offer in depth solutions to commonly faced smart contract problems. We hope this post helped you in getting a very rudimentary understanding of how smart contracts are created, along with some basic solidity functionalities. The best part about this tutorial was that these exact same steps can be followed to ripple all actions on to the testnet or mainnet, which is further elaborated in this cool blog by Ayush Tiwari (https://medium.com/techracers/best-way-to-deploy-your-smart-contracts-e5f7b5a52baf).

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

--

--

Nidish Ramakrishnan

Research Analyst at Deqode | Ethereum | Blockchain | Node.js