How to Build an Ethereum Smart Contract

Ethereum, maintained by the non-profit Ethereum Foundation, is by far the most popular platform for blockchain-based projects, and in particular, smart contracts creation. In this article, we will provide a brief Ethereum tutorial, which you can follow to develop your own smart contract.

Ethereum Smart Contract Development

Choosing Development Tools

First, let’s list the tools for developing smart contracts in Ethereum.

We recommend you write and compile code using Remix – one of the easiest to use development environments that has two undoubted advantages for the majority of users:

  • There are a lot of tutorials on using it;
  • It can be launched directly from the browser.

As for the programming language, the major choice for Ethereum is Solidity (which was recognized by developers around the world as the best choice for smart contract development).

Where Do We Start?

We start by presenting a sample of working code. In this tutorial we’re covering one of the most understandable and compact Ethereum smart contract examples available in the public domain, presented at GitHub by isvirin. For convenience sake, we numbered each important logical section.

Smart Contract Development Tutorial

Reviewing the Code Example

//Block 1
contract owned {

address public owner;

function owned() payable {
owner = msg.sender;
}

modifier onlyOwner {
require(owner == msg.sender);
_;
}

function changeOwner(address _owner) onlyOwner public {
owner = _owner;
}
}

//Block 2
contract Crowdsale is owned {

uint256 public totalSupply;
mapping (address => uint256) public balanceOf;

event Transfer(address indexed from, address indexed to, uint256 value);

function Crowdsale() payable owned() {
totalSupply = 21000000;
balanceOf[this] = 20000000;
balanceOf[owner] = totalSupply – balanceOf[this];
Transfer(this, owner, balanceOf[owner]);
}

function payable() {
require(balanceOf[this] > 0);
uint256 tokensPerOneEther = 5000;
uint256 tokens = tokensPerOneEther * msg.value / 1000000000000000000;
if (tokens > balanceOf[this]) {
tokens = balanceOf[this];
uint valueWei = tokens * 1000000000000000000 / tokensPerOneEther;
msg.sender.transfer(msg.value – valueWei);
}
require(tokens > 0);
balanceOf[msg.sender] += tokens;
balanceOf[this] -= tokens;
Transfer(this, msg.sender, tokens);
}
}

//Block 3
contract EasyToken is Crowdsale {

string public name = ‘EasyTokens’;
string public symbol = “ETN”;
uint8 public decimals = 0;

function EasyToken() payable Crowdsale() {}

function transfer(address _to, uint256 _value) public {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
}

//Block 4
contract EasyCrowdsale is EasyToken {

function EasyCrowdsale() payable EasyToken() {}

function withdraw() public onlyOwner {
owner.transfer(this.balance);
}

function killMe() public onlyOwner {
selfdestruct(owner);
}
}

Now, let us proceed to analyze this example.

Block 1

So, the first block, starting with the words “contract owned”, specifies the access policy to the Ethereum smart contract for the project administrators (as a rule, this is a team of programmers). In particular, this group of users gets the opportunity to track what the funds collected from investors were converted into and where they went (to what account). For these purposes, we define the contract owner.

The contract owner is named with a public “owner” modifier, which is assigned with a “msg.sender” value – this is how we denote the person who performed the deployment of the contract itself.

On top of that, we strongly recommend that you provide the option to change the owner. This can be performed simply and concisely inside the “changeOwner” function. Here we just store the address of the new owner and make sure that the function itself is performed from the same address (technically this is due to the “onlyOwner” modifier).

Additionally, in order to avoid errors such as incorrect address, this smart contract has a special field “candidate” in which a new value of the “owner” address is stored (rights will be transferred to a new “owner” only after the previous one confirms this operation).

Block 2

The next contract, which is lower in the hierarchy than Block 1, describes the tools to collect investments and distribute tokens.

It consists of the following elements, each an integral part of the ERC20 security standard:

  • “totalSupply” – indicates the maximum number of tokens that our blockchain system must generate and serve;
  • “balanceOf” – the data structure that stores the information about current balances of each investor;
  • function “Transfer” implements the transfer of funds between depositors and, in general, to everyone who owns tokens inside the system.

And now – a few words about what is happening inside the block itself.

It all starts with the definition of the smart contract constructor: in particular, we assign a value of 21,000,000 (tokens) to the attribute “totalSupply”. Next, we indicate that 20 million of these tokens will be automatically transferred to the smart contract balance, and the remaining one million – to the address of the contract holder purse.

Finally, we execute the “Transfer” function, which will perform the actual relocation of tokens. The results of this, as well as the balances of system participants, can be monitored using the etherscan.io tool.

Next is the “payable()” function, which allows checking if the buyer has enough funds in their account to pay for goods or services. If the result is positive, the conversion to ether can be performed at the rate of 5,000 tokens per one ether. The intermediate transaction data is stored in the “value” field. This function is also launched automatically during each arrival of ethers to the user purse. Additionally, we should note that if the function requests a larger number of tokens than are in the smart contract itself, the unused ethers would be returned to the account of their owner.

Block 3

Block 3 illustrates the implementation of the “EasyToken” smart contract, which demonstrates how to complement our code with the ERC20 conformity routines. In particular, it defines the following three attributes of the created tokens:

  • full name
  • abbreviated name
  • the decimal accuracy of our coin (the number of fraction units; for instance, if we set this value to zero, the resulting coin would be non-divisible)

Block 4

Finally – the most interesting set of functions, which implement the routines for exchanging tokens between wallets and the methods for transferring them into crypto-currency exchanges.

In order to implement all this, we just need to make sure that there is a sufficient number of tokens in the account and, after receiving a positive conclusion, reduce the balance by the required number of tokens and add them to the wallet of the new owner. Thus, by simply overloading the “+” and “-” operators, we implement standard mathematical operations of addition and subtraction on our tokens.

In turn, to exchange the tokens for real currency and transfer it to bank cards, we activate the “withdraw” function.

Done! Our smart contract has been created and is ready for testing!

Ethereum Smart Contract Guide: Summary

We strongly recommend not creating a smart contract on Ethereum in real projects, relying solely on the provided example. Despite the fact that it contains everything required for an ICO-ready crypto-coin, the logic of this code has been maximally simplified. For this reason, the author did not take into account aspects that are important for future investors, such as the fundraising timeframe control, soft cap indication, methods for funds reclamation in the event of a project failure, etc. Moreover, this code has little protection against some known vulnerabilities.

That is why our Ethereum smart contract tutorial can serve only as learning material. To employ it in a real case there is a lot that must be improved and enhanced to maximize the confidence of potential investors.

We hope that our Ethereum Solidity tutorial can help our readers to get a better understanding of how to make a smart contract (or at least become the basis for your programming activities in the sphere of the blockchain and ICO). We also very much hope that you leave comments below about your experience in developing smart contracts – it would be extremely interesting for us to find out!

Programming smart contracts on Ethereum

Nevertheless, if you want to entrust programming smart contracts on Ethereum to real professionals, we are ready to cooperate! Our team of top developers specializes in creating everything related to ICO, and therefore will build even the most complex and non-standard projects for you with ease. Want to discuss this? Just fill out the contact form and our staff will reply shortly.