Smart contracts are the part of Blockchain ecosystem, that enables users to exchange any asset without any 3rd party intervention. You can learn more about it here(link).

There are many Blockchains that supports smart contracts using its dedicated cryptocurrency. Most popular one is Ethereum.

So the question is how to write one?

After learning about the dynamics of blockchains and ethereum, when you try to search it, you are presented with obsolete examples which may seem difficult for a solidity beginner and according to me, creating a smart contract doesn’t have to be that daunting.

With just a basic understanding of any object-oriented language and the right tools and assuming that you have a basic understanding of blockchains and how they work, you can move on.

In this tutorial, we will try to create a Smart contract for a Token sale (I bet most of you are interested in this part only) with minimal time and resources, and we will try avoiding the download of a Full blockchain node on our system because why to do it if you can develop just fine without it !!

To kick start our journey, we need few tools at our disposal:

Remix: (https://remix.ethereum.org/) All the codes will be written in solidity in this tutorial. Remix is mostly used for debugging code but it is more than enough to get a start.

Getting started with Remix.

On opening Remix, you will find a default smart contract named ‘ballot.sol’ in an interface as shown below. (Remix updates interface sometimes, so don't worry if you don’t see some differences, but eventually, all functionalities will be same only)

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

The Run Tab is where the transactions take place. You can select the development environment, the accounts and the gas limit and value.

The environment tab allows you to select between running the contract on a web3 provider, injected Web3 and javascript VM.

a. A web3 provider connects to an actual node or a localhost.

b. The injected Web3 uses the environment provided by mist or MetaMask.

c. We will use javascript VM where everything is local and in memory of Remix.



You can select the user accounts available, as per your environment in the accounts list. Transactions will take place from the account thereon.

Gas limit sets the maximum gas allowed for each transaction.

The “Value” corresponds to 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. Or change the currency from the drop-down.

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)

The debugger tab 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 smart contracts.

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

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. You will be needing them in order to access the smart contracts.

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

A Simple Token Sale Contract

You won’t need Ballot.sol smart contract which you find in Remix by default. Delete it and add a new file naming it TokenSale.sol or whatever you like.

This tutorial will cover just the basics, 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,

a. To buy tokens,

b. To check the token balance and

c . To check the ether balance.



This will look pretty simple for someone familiar with any OOP language.

Make sure you understand the lines of code before copying it, to make its implementations easier.

You can find below the code for a very simple Token Sale contract:

Some Explanation of some of the Important part of Code.

Code Starts with Defining Solidity version.

pragma solidity ^0.4.11;

Mapping is an equivalent to an associative array.

mapping (address => uint) balance;

A modifier checks if a condition is met before executing a function.

The payable keyword allows the contract to accept ethers.

Other little points to note in the code

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 of wei or ether (any selected) you have entered in the ‘value’ dialog box.

msg.sender is the account address that you have selected from the drop down list.

----------------------------------------

TO REPLACE WITH SNIPPET : https://gist.github.com/anonymous/13659224e889e9bf51fbf6229100258a#file-tokensale-sol

----------------------------------------

// To specify what version of compiler this code will compile with

pragma solidity ^0.4.11; contract tokensale { // Declaring the maximum number of tokens available for sale.

uint public maxTokens = 1000; // The number of tokens you can buy for one wei (Solidity converts all unitless values from ethers to wei).

// We will keep the default currency to be wei. It will get clearer.

uint public tokenSwap = 10; // This variable, initially set to zero, stores the number of tokens that have been bought, i.e it will

// get incremented each time someone buys tokens.

uint public supply = 0; // mapping is an equivalent to an associative array. We store token balances corresponding

// to each address that buys tokens in this mapping.

mapping (address => uint) balance;

// A modifier checks if a condition is met before executing a function.

// This modifier checks if there are tokens available before the buyTokens function is called.

modifier isTokenAvailable () {

require (msg.value*tokenSwap + supply <= maxTokens); // require checks the condition and the function that

_; // follows, denoted by the '_', is only run if the condition

} // is satisfied.

// A function to check the ether balance of any address.

function checkBalance (address addr) external returns (uint) {

return addr.balance; // The address.balance call returns the ether balance of the given address.

}

// To check the token balance of any address. The external keyword allows the function

// to be called from outside the contract. If no keyword is specified, all functions are external

// by default..

function balanceOf (address tokenHolder) external constant returns (uint) {

return balance[tokenHolder];

} // A function to buy tokens accessible 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 Remix)

// 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

isTokenAvailable {

uint tokensAmount = msg.value * tokenSwap; // At this point, msg.value is in wei.

balance [msg.sender] += tokensAmount;

supply += tokensAmount;

}

} -----------------------------------------

After you paste this code into the remix 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 ‘RUN’ tab.

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

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

Let’s start to call the functions.

a. Select any of the addresses from the dropdown list to make them the transacting account to start buying tokens.



b. 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 and Amount is lesser than or equal to 1000 wei .



c. Now call the function by simply clicking on the buyTokens function.



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

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.

You can test the modifier by putting a value of over ‘1000 wei ’ and you can see it shoots an error.

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.

That's all!

Hope you’ve got the right insights on building your first smart-contract through this article. This process has been practically tested and followed by us for the early development of smart-contracts.

Feel free to comment in case you’ve any queries or concerns!!!