Explore the possibilities of Ethereum's smart contract feature

Get Smart

© Photo by jesse orrico on Unsplash

© Photo by jesse orrico on Unsplash

Author(s):

The Ethereum cryptocurrency system lets you build programs into the blockchain to orchestrate complex transactions and document results. We'll show you how to get started with Ethereum's smart contracts.

Digital currencies have had quite a lot of buzz around them in recent years, with Bitcoin being the most famous. Satoshi Nakamoto, the mysterious creator of Bitcoin, had the idea to use Bitcoin as a store of value, like gold. For that reason, Bitcoin was designed for the limited purpose of trading and holding value.

When Vitalik Buterin and others designed the first version of Ethereum [1], they wanted to extend the blockchain concept to include other kinds of transactions. Ethereum is built around the concept of a smart contract. A smart contract is a program embedded in the blockchain that automatically manages, controls, and documents actions taken for a predetermined purpose. A smart contract allows the creator to implement a contract or agreement without the need for traditional oversight and enforcement.

Bitcoin is thought to have some rudimentary support for smart contracts in the context of its role as a digital currency – to support features such as escrows and multisignature accounts, but Ethereum expands the concept to support a much wider range of transactions and arrangement. For instance, Ethereum was the first blockchain technology to support non-fungible tokens (NFTs) [2], and Ethereum is still the most popular tool for creating NFTs.

This capacity for smart contracts makes Ethereum an ideal candidate for supporting decentralized autonomous organizations (DAOs), blockchain-based insurance, and other systems that require verification of real life activities.

The Ethereum Blockchain

The principle of a blockchain is the same for all cryptocurrencies. If you have spent more than a few hours with programming, you will know about chained lists. The idea is that the first item points to the next, creating a list that grows according to your needs.

With a blockchain, everyone and anyone can download the chain and add to it. How do you make sure the newest block is correct? How do you know that people you do not know haven't changed the earlier blocks? The blockchain has to be tamper proof.

To handle this, every block after the first points backwards with a cryptographic hash. That hash will depend on the contents of the earlier block. Not only that, all blocks' hash values depend on the earlier block all the way back to the first block. That first block is called the genesis block, and the complete system is what is called a Merkle Patricia tree.

Wait, is it a tree or a chain? Actually it is a little of both. If the blockchain were just a chain, any verification would have to go through the entire chain. The entire Ethereum Virtual Machine (EVM) would grind to a halt, and no one could determine the state of the system.

In essence, the whole Ethereum system is one state machine. A state machine is a construct that changes its state depending on input. In this case, the input is every transaction made in the EVM. It sounds odd but the state is not a single value as it is for simple applications. Instead, the state has many values that are constantly changing. The state is expressed in tree form.

Ethereum has three trees that you can follow to verify any actions on the chain. These trees can verify ownership and also verify that the tree itself is correct. The trees are state, transactions, and receipts. Thanks to the trees being separate, it is much easier to use a small part of the chain to verify that everything is correct.

Each tree has a root, stateRoot, transactionsRoot, and receiptsRoot. Their values are in the header of each block of the Ethereum blockchain. This approach enables clients to verify all three without querying the entire tree. A pruned tree is around 1.2TB, and a full tree is around 6TB. As you can see, it is not easy to have a full node.

When you want to use your ether (ETH – the cryptocurrency used with Ethereum), or verify anything about the Ethereum blockchain, you need a client. A full client with a full node will require too much disk space for most systems. A light node requires only a small fraction of the tree and still allows you to make advanced queries on the tree. You can use a light node to balance your own account, check if another account exists, and test run a contract. Testing is important to ensure that you don't fall victim to a fraudulent contract.

The trees have different functions, and you need them for different tasks. Your client needs to use the state tree for checking account-related things and testing contracts.

The transactions tree will be updated often but never edited. In contrast, the state tree changes frequently, because it contains all accounts and their balances.

The receipts tree only keeps a record of the effects of transactions, so it is also updated but not edited. If you want a more hands-on approach to handling Merkle-Patricia trees, check out the tutorial online [3]. You can download the code from the tutorial and play around with it yourself. The first example is in Figure 1, which shows how to initiate a tree.

Figure 1: Code example from the Merkle Patricia tutorial collection.

Transactions

The simplest transaction is to pay someone an amount. You can try this by making a payment between your own accounts – or better yet on a testnet. Each transaction will cost you some amount of gwei (a gwei is the smallest unit of Ethereum currency, equivalent to one billionth of an ether.) The actual cost for a transition will depend on the gas price. According to Wikipedia, "When creating a transaction, the sender must specify a gas limit and gas price. The gas limit is the maximum amount of gas the sender is willing to use in the transaction, and the gas price is the amount of ETH the sender wishes to pay to the miner per unit of gas used."

Ordinary wallets set the gas price automatically in a unit of gwei. When you do more advanced transactions, you can increase the gas price to give miners more incentive to do your job first.

Most people use browser extensions for transactions. MetaMask is a great Ethereum client, and it is very common. In the MetaMask wallet, you can send and sometimes choose the gas price yourself. MetaMask also gives you the chance to speed up the transaction while it is pending. You can also ask for funds by giving out your public address.

For Linux desktop, you have Jaxx, Exodus (Figure 2), and MyCrypto wallets. These wallets have more functions and a fancier interface, which includes graphs for exchanges. More importantly, you can have wallets from different blockchains, not just Ethereum. Note also that transactions happen when a contract is created and during execution of contracts.

Figure 2: When using Exodus on the Linux desktop, you get a QR code for people to send you funds.

Smart Contracts

According to the Ethereum website, "A 'smart contract' is simply a program that runs on the Ethereum blockchain. It's a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain."

Smart contracts can solve many problems. They can do such diverse things as creating new currencies and facilitating crowdfunding. The Basic Attention Token (BAT) system used by digital advertisers for tracking attention time is an example of an Ethereum-based blockchain technology that leverages the power of smart contracts.

The Ethereum documentation goes on to explain "Smart contracts are a type of Ethereum account. This means they have a balance and they can send transactions over the network. However they're not controlled by a user; instead they are deployed to the network and run as programmed. User accounts can then interact with a smart contract by submitting transactions that execute a function defined on the smart contract. Smart contracts can define rules, like a regular contract, and automatically enforce them via the code. Smart contracts cannot be deleted by default, and interactions with them are irreversible."

In Ethereum, smart contracts are special accounts that must first be created (minted) by user accounts. The creator of a contract must have written the code and also must have an account and currency (ether). When the user creates a contract, the code can set values that are immutable once it is on the blockchain.

Once the contract is on the chain, any other users can call it at a cost. The cost will vary depending on the contract. A smart contract could also be an auction for an NFT.

You can imagine how a program would execute an auction. Bids would be received and accepted. Then at some predefined decision point, the program would select the highest bidder as the winner. At that point, all losing bids would revert back to the bidder. After that, the program would transfer the funds to the initiating user. This type of auction can be embedded directly into the blockchain using a smart contract.

A developer needs to write the code for the contract, test it, and then deploy it to the blockchain. The Ethereum community has specialized development tools for coding and deploying smart contracts. Coders can also access a testnet that acts like the main Ethereum blockchain except that it has no value. (Tokens for the testnet are available online [4]). You can also use the testnet to get used to regular transactions (Figure 3).

Figure 3: When you ask for tokens on the testnet, try to do it on Wednesdays. The low power icon means there is too much traffic to give more.

Solidity, the Language!

You can program smart contracts in many languages, but the most common is Solidity [5]. Solidity looks and behaves much like the C language in that you have constructors and functions, and you need to set a variable's type.

Every instance is a contract, and each contract can have one and only one constructor. Functions and values get a visibility setting, telling the compiler which other functions can use them. The public setting, for example, makes a function available to any function on the entire blockchain. As you can see in Figure 4, Solidity also lets you import frameworks. There are other languages under development, but Solidity is a good place to start if you want to learn about programming smart contracts.

Figure 4: On the right, you can see the Solidity source code for importing Zeppelin, a framework for standards.

Development Environments

To truly start developing, you need an IDE; Cakeshop is a good choice. The Cakeshop IDE acts as a daemon, running a local chain that you can do pretty much anything with. (See the box entitled "Setting Up Cakeshop.") You also have the option of putting many nodes up on your local network. In the interface, you will find the basic stuff you need for interacting with a blockchain. You can create accounts and send funds back and forth on the test chain. Follow up by looking at the chain explorer and see how the transaction worked. There is also a sandbox, where you can deploy your own contracts and test all functions.

Setting Up Cakeshop

The developers chose to use Java for Cakeshop. The original place to pick it up is GitHub [6], where you can find a .war file and the source code. Using this binary, you can start it easily enough, but you need to define the nodes. If you just want to see how Cakeshop works, use the snap; it is still in version 0.10.0, so go with a newer version when you have figured out the configuration of the nodes. The snap version has defined nodes built-in, so it starts with a single command.

$ sudo snap install cakeshop

Wait for the install to finish, and run the following command on the command line:

$ cakeshop

With this setup, you can see what address you need to look at to use the web interface. Usually it would be http://172.17.0.1:8080/cakeshop/, but you must look in terminal output to be certain (Figure 5).

You can find more install options on the Cakeshop home page [7]. The page describes several ways to start a Docker instance.

When you have it all installed, you can see all components of a blockchain and even interact with the chain. This blockchain is your own, not the public one! Use the block explorer to investigate what your actions do. You will also have unlimited currency. You can see in Figure 6 what the sandbox looks like.

A smoother way to get started might be to use the Remix IDE online service [8]. Remix lets you load files from your local disk or even directly from GitHub. The features are similar to Cakeshop, but Remix does support plugins. The basic plugin is the Solidity plugin, which gives you full support for the language.

Remix offers many other plugins to choose from, including tutorials, verification tools, and example code. The code covers the simplest storage all the way up to distributed applications. For the really advanced, you also have services to reach outside information (called oracles).

Figure 7 shows the Remix IDE. On the left, you can choose the file explorer, compiler, and whatever plugins you wish to include. To the right, you have the code and a console.

Figure 7: Remix IDE: The sample code above deploys Web3 components.

A Simple Contract

Some basic contracts show up in the default view of Remix. See Listing 1 for an example that shows how the basic syntax works.

Listing 1

A Smart Contract

01 // SPDX-License-Identifier: GPL-3.0
02
03 pragma solidity >=0.7.0 <0.9.0;
04
05 /**
06  * @title Storage
07  * @dev Store & retrieve value in a variable
08  */
09
10
11
12 contract Storage {
13
14     uint256 number;
15
16     /**
17      * @dev Store value in variable
18      * @param num value to store
19      */
20     function store(uint256 num) public {
21         number = num;
22     }
23
24     /**
25      * @dev Return value
26      * @return value of 'number'
27      */
28     function retrieve() public view returns (uint256){
29         return number;
30     }
31 }

This code only contains simple function calls and no constructor, but it is an excellent start for understanding what you need to get right. The top line is not necessary, but many compilers will complain without it. The second line limits which compiler you can use.

Listing 1 has one contract function called Storage; all your code goes inside this function. The first function stores the value in number, and the second function retrieves it.

ETH2 Is Coming Soon

Ethereum has an update coming soon; it goes to version 2.0. The most notable difference is that it goes to a Proof of Stake system instead of Proof of Work system. What that means is that you can use a small computer as a node and help the network validate the blocks. Earlier you had to have a beast of a machine to ever validate and get rewarded.

This sounds great for the little guy, but you now have to have 32 ether to participate. That amount is staked; if you behave well the amount will go up because of rewards. If you misbehave, you can be punished and lose funds. This is to ensure that nobody tries to create fake blocks and ruin consensus.

Conclusion

Ethereum is growing into a formidable force in finance and tech. Being able to use different wallets and services can help you handle your own finances – and maybe even publish your own art.

I should add that the power of Ethereum comes with the need for caution. Smart contracts are visible on the blockchain, and a bug or security hole in the code could lead to exploitation. Back in 2016, nearly $50 million in ether was drained from Ethereum accounts in this kind of attack, although the developers were able to claw the money back through a hard fork of the Ethereum blockchain. Several updates have improved security since that time, but be aware of the need to test your code thoroughly and use secure programming techniques.

Web 3.0 will be based on digital currencies and their surrounding technologies. Hopefully Ethereum will improve the web experience for most users and help balance the power on the web.

Figure 6: In the sandbox, you can both write the code and test what happens when you use the functions.
Figure 5: Cakeshop terminal output: The lion with the cake is a marker so that you can see the address to point your browser.

The Author

Mats Tage Axelsson has a set of modes that he still has not found the keyboard shortcut to change.