Ethereum Smart Contract Development for beginners

We want to do something about the prevailing blockchain-developer-talent shortage in the ecosystem. We are launching “BlockchainDev1000” initiative. We want to train 1000 blockchain developers in Nigeria on different skillsets within the next 1–2 years. This article is the first step in achieving that.

What is Ethereum?

Bitcoin blockchain is primarily used for sending money between various parties on the blockchain without the need for a central authority such as a bank. A 19-year-old developer by name Vitalik Buterin wanted to apply the idea of decentralization (no central authority) to do more than just money transfer. He wanted to build applications that could run globally without any central authority in control. For example, if you are a Facebook user, Facebook as a company owns your data and they have the right to remove your account if they wish. In 10 years, Facebook could shut down in which case all your data could be lost.

Vitalik proposed to add a scripting language to Bitcoin to be able to build applications. However, after failing to gain agreement from the Bitcoin development team, in January 2014, he officially published the white paper proposing the development of a new platform with a more general scripting language. A team formed shortly and one of the developers, Dr. Gavin Wood soon released the Ethereum yellow paper, which covered the Ethereum Virtual Machine (EVM), the runtime environment that executes all of the smart contracts on the network (You will learn more about EVM and smart contracts as we progress). The development of the platform was funded through a crowdsale in July–August 2014, with the participants buying the Ethereum value token (ether) with bitcoin. They raised about 31,529 BTC ($18.4 million at the time).

Global Computer

All these computers (also called nodes) are connected to one another and have a full copy of the code and data. When you deploy your code on to the Ethereum blockchain, the code is replicated across all the nodes in the network. When your application stores any data, even that data is replicated across all the nodes. There are thousands of nodes in the network and it is almost impossible for anyone to stop all the nodes. This ensures your application to be always accessible.

Webapp Architecture

A typical web application consists of server-side code which is usually written in a programming language like Java, C#, Ruby, Python etc. The frontend code is implemented using HTML/CSS/Javascript. This entire application is then hosted on a hosting provider like AWS, Microsoft Azure, Google Cloud Platform, Heroku or a VPS.

Users interact with the web application using a client such as a web browser, curl/wget (command line) or through an API. Note that there is one web application which is centralized and all the clients interact with this one application. When a client makes a request to the server, the server processes the request interacts with the database and/or cache, reads/writes/updates the database and returns a response to the client.

In the next section, we will see how this compares to the working of the Ethereum blockchain.

World Wide Web architecture.

Ethereum Architecture

We don’t live in an ideal world and it is unreasonable to expect everyone to run a blockchain server to use these apps. But the idea behind decentralization is to not rely on a single/centralized server. So, the community has come up with solutions (hosted blockchain servers, metamask etc.) where you don’t have to spend lot of your hard disk and RAM downloading and running a full copy of the blockchain but also not compromise on the decentralized aspect. We will evaluate those options in the future lessons.

Now, what exactly is in the Ethereum blockchain? The blockchain has 2 main components:

  1. Database: Every transaction in the network is stored in the blockchain. When you deploy your application, it is considered as a transaction. If you have for example a Voting application that allows anyone to vote for candidates, a vote for a candidate would be considered a transaction. All these transactions are public and anyone can see this and verify. This data can never be tampered with. To make sure all the nodes in the network have the same copy of the data and to ensure no invalid data gets written to this database, Ethereum uses an algorithm called Proof of Work to secure the network. (http://ethereum.stackexchange.com/questions/14/what-proof-of-work-function-does-ethereum-use)
  2. Code: The database aspect of blockchain just stores the transactions. But where is all the logic to vote for a candidate, retrieve the total votes etc. In Ethereum world, you write the logic/application code (called contract) in a language called Solidity. You then use the solidity compiler to compile it to Ethereum Byte Code and then deploy that byte code to the blockchain (There are few other languages you could use to write contracts but solidity is by far the most popular and relatively easier option). So, not only does Ethereum blockchain store the transactions, it also stores and executes the contract code.

So basically, the blockchain stores your data, stores the code and also runs the code in the EVM (Ethereum Virtual Machine). You will learn more about ByteCode and EVM in the future sections.

What are smart contracts?

You must be wondering why these applications are called smart contracts. In general, contract is a written agreement between two or many parties that is intended to be enforced by law. If we take this written contract and translate it into code and deploy on the blockchain, we get digital contracts. But the beauty of this code on the blockchain is that it can enforce the agreement between parties and that is the reason they are called “smart contracts”.

How can this code enforce the agreement? If you remember, once a contract is deployed to the blockchain, it can neither be stopped nor modified. That is how the agreement is enforced. Let’s take a look at a simple example to understand this better.

Let’s say we want to build a Crowdsale application. There is a creator who wants to raise $10,000 to create a product and there are potential customers who are interested in this product and are willing to pre-pay for it. The agreement is, each customer will contribute anywhere between $10 — $10,000 and if the goal is met, the money is sent to the creator. If not, money is sent back to the contributors. This is an ideal use case to use smart contract to enforce the agreement between the creator and supporters. It is trivial to implement this logic in a centralized application as well. The advantages of implementing this in a smart contract are

  1. The money sent by all the contributors is in the smart contract. Neither the contributor nor the creator can take that money.
  2. The code can be implemented so that the money is sent to the creator as soon as the goal is reached.
  3. The code can be implemented so anyone can trigger a refund to all the customers if the goal is not reached within a certain time frame.
  4. This code cannot be tampered with once it is deployed on to the blockchain.

Ether & Denominations

In the real world, currencies have various denominations. For example, a US Dollar is equal to 100 cents and it has various denominations such as pennies (1 cent), nickel (5 cents), dime (10 cents), quarter (25 cents). Depending on your country and currency, you probably have various denominations as well.

Ether also has various denominations as shown on the right. The only two you should really remember are Ether and Wei. Wei is the lowest denomination and this is the denomination you use in your smart contracts.

What is an Ethereum address?

In Ethereum blockchain, address is your identity. An Ethereum address looks like this: 001d3f1ef827552ae1114027bd3ecf1f086ba0f9. An address has a corresponding private key. You can think of private key as a password that only you know. You need this pair of address+private key to interact with the blockchain. Below are few key things to memorize without which it is hard to understand blockchain and Ethereum:

  1. Ethereum address is public and you can share it with anyone in the world.
  2. The private key should never ever be shared with anyone.
  3. The address+private key is not stored in any database. Only you are in control of them.

In the future sections, you will learn how to manage these addresses and ways to use them.

How is an Ethereum address generated?

Generate a private key

k(private key) = f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315

Derive the public key from the private key

K(public key) = 6e145ccef1033dea239875dd00dfb4fee6e3348b84985c92f103444683bae07b83b5c38e5e2b0c8529d7fa3f64d46daa1ece2d9ac14cab9477d042c84c32ccd0

Calculate the hash of the public key by using keccak256 algorithm

Keccak256(K) = 2a5bc342ed616b5ba5732269001d3f1ef827552ae1114027bd3ecf1f086ba0f9001d3f1ef827552ae1114027bd3ecf1f086ba0f9

Take the last 20 bytes of the generated hash to get the Ethereum address

0x001d3f1ef827552ae1114027bd3ecf1f086ba0f9

This my article explained hash functions well.

What is an Ethereum account?

1. Externally owned accounts (EOA): This is the account we mentioned above which is a combination of public address and private key. You can use these accounts to

  1. Send and receive Ether to/from another account
  2. Send transactions to smart contracts

2. Contract accounts: These accounts don’t have a corresponding private key. These accounts are generated when you deploy your contract to the blockchain. You will see them referred to as just contracts in lot of places (instead of contract accounts). Some key features of a contract (accounts) are

  1. They can send and receive ether just like EOA
  2. They have code associated with them unlike EOA
  3. Transactions have to be triggered by an EOA or another contract

It will get a lot more clearer in the future chapters when we create and use these accounts.

What is an Ethereum wallet?

  1. Non-Deterministic Wallet: This is a type of wallet that uses a random private key and generates a public key from it. You can generate as many public/private key pairs but there is no relation between each pair of keys.
  2. Deterministic Wallet: In this wallet, keys are derived from a single starting point known as a seed. The seed allows a user to easily back up and restore a wallet without needing any other information and can in some cases allow the creation of public addresses without the knowledge of the private key. Seeds are typically serialized into human-readable words in a Mnemonic phrase. If you have used a plugin like metamask, it would have asked you to save the 12 word seed when you first installed it. The Metamask section in the next chapter has a video demo of the deterministic wallet.

Gas, Gas Price and Gas Limit

Gas

Who decides how much Ether to pay for a transaction? This is where it gets interesting and also where lot of developers new to Ethereum get confused. The answer is, the yellow paper has specification on how many units of work a transaction has. For example, if your transaction is to simply add two numbers, that is 3 units of work. If it is multiplication, that would be 5 units of work and so on. This unit of work is called gas.

Gas Price

The higher the gas price you set, the sooner your transaction gets mined. This is because most of the miners sort the transactions in the descending order of gas price and pick the transactions with higher gas price to include in the block. If you set the price low, your transaction will eventually get included in the block but you might have to wait for a bit.

Gas Limit

Don’t confuse this with Block gas limit. Block gas limit is the maximum cap applied to each block in Ethereum. Currently, a block can only include transactions whose total sum of gas is less than 8 million. The reason you have a limit for each block is to prevent someone from just writing an infinite loop in which case the transaction wouldn’t complete it’s execution resulting in block not getting mined.

Byte Code

One of the benefits of this design is that it gives developers the option to use other programming languages to implement smart contracts. Currently, there are a handful of languages like Vyper (similar to Python) that compiles down to the EVM bytecode. If you are a language designer, you can just refer to the Ethereum yellow paper and implement your own programming language for Ethereum!

What is EVM?

When you install and start the geth, parity or any other client, the EVM is started and it starts syncing, validating and executing transactions.

Geth/Parity Clients

Geth

It also comes with a javascript client (geth console) that can be used to connect to the blockchain.

Parity

Anyone can implement the client software and join the Ethereum network. There are clients written in C++ and Python and other languages. You can follow the specs in the yellow paper to implement your own client if you like!

A simple illustration of the Ethereum network with various clients connected to one another.

Web3JS/Truffle

Web3JS

Another library which is worth looking into for interacting with the blockchain is Ethers.js

Truffle

There is another alternative to Truffle called Embark which is worth exploring.

Ganache

Metamask

Etherscan

You can find links to Etherscan frontend for various public networks below:

Mainnet: https://etherscan.io/

Ropsten: https://ropsten.etherscan.io/

Rinkeby: https://rinkeby.etherscan.io/

Kovan: https://kovan.etherscan.io/

Remix

In our opinion, remix is good to quickly test out small contracts but we recommend using an editor like Vim, Atom, Visual Studio or Sublime for development and use truffle framework for compiling and deploying your contracts.

Closing Thoughts

Next Step

You must have had some kind of knowledge of the workings and concepts of Blockchain & Distributed Ledger Technology (DLT)

You should be familiar with any object-oriented programming language (Python, C++, PHP, Java, Rugby, C#)

You should be familiar with web technologies (HTML, CSS and Javascript)

You are familiar with CLI or Command-line Interface

Your laptop should be developer ready, running MAC, Linux or Windows.

IT Professional & Drupal Web Developer. Trainer @ Lagos DrupalVersity. Founder, BlockSpace.Africa, Coordinator, Blockchain Nigeria User Group, 3D Printing guy!