Explore the possibilities of Ethereum's smart contract feature

Get Smart

© Photo by jesse orrico on Unsplash

© Photo by jesse orrico on Unsplash

Article from Issue 256/2022

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.


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.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Welcome

    It is easy to write columns on the scary and annoying stuff, which seems to happen every day, but it is perhaps more important to point out the positive things when they happen, and the Ethereum Merge looks like a very positive thing.

  • The Impact of Crypto Mining

    With climate change wreaking havoc across the planet, we were just beginning to think about how we could use our technology to conserve fuel and reduce our carbon footprint. Then along came crypto mining.

  • Ring Secure Communication

    In the last few years, secure text, voice, and video transmission have become major areas of free software development. One of the leaders in this field is Ring.

  • Interview – Meet Apache Creator Brian Behlendorf

    Apache developer, Brian Behlendorf, talks about Hyperledger and blockchains.

  • Welcome

    Is blockchain finally getting interesting? I guess it always has attracted some attention – if not as an investment at least as a generator of headlines.

comments powered by Disqus