Less noise, more data. Get the biggest data report on software developer careers in South Africa.

Dev Report mobile

Programming on the Ethereum Blockchain

20 February 2018 , by Wogan May

This article was written for but not as usual by OfferZen - We have started looking into collaborating with experts from South Africa's tech community. They will directly share their insights, learnings and ideas through the blog. If you have an interesting topic in mind and are keen to contribute, please get in touch!

Of all the blockchain projects currently in the mix, Ethereum is by far my favourite. This is for one simple reason: It puts the power to build decentralised applications in the hands of regular developers like me. Here’s my take on why that’s exciting:

Solidity vs. Javascript

But first things first: In a nutshell, Ethereum is a programmable layer built atop a blockchain. It allows you to write, compile and deploy specialized functions (contracts) that will live in the blockchain and respond to messages from external accounts (in other words: people). In this regard, Ethereum is not unlike serverless computing - except for the notable lack of features.

While Solidity (the language used on Ethereum) looks a lot like Javascript, that doesn’t mean it can do everything Javascript can:

  • Contracts are not able to directly access the network, filesystem or devices of the machine they run on.

  • Every contract is completely encapsulated within Ethereum’s Virtual Machine (EVM) and thus only able to communicate with other accounts and contracts on the system.

The EVM is not unlike the Javascript runtime in any browser - it's a tiny execution environment that reads Solidity code and performs actions on the Ethereum blockchain.

Every instance of the Ethereum software on the network, meaning every single node around the globe, runs an instance of this EVM. This is where the magic lies: in Ethereum's decentralised execution.

decentralised execution Ethereum

In practice, smart contracts still only perform very fundamental programming tasks:

  • Contracts have access to storage, can send and receive messages from other accounts and consume gas to operate.
  • They can be initialized with values that are stored as variables.
  • These values can be changed by direct intervention from users or as a result of the execution of other contracts.

Here is a very basic example of a contract, written in Solidity:

pragma solidity ^0.4.0;

contract SimpleStorage {
	uint storedData;

	function set(uint x) public {
    	storedData = x;
	}

	function get() public constant returns (uint) {
    	return storedData;
	}
}

This contract is targeted at Solidity version 0.4, creates a variable to hold an integer (storedData) and then declares a getter and setter function. Fairly basic, but a good example to illustrate how the global state machine works - and what makes Ethereum so useful.

Imagine you wrote something similar in Javascript:

function SimpleStorage() {
	this.storedData;
    
	this.set = function(int) {
    	this.storedData = int;
	}

	this.get = function() {
    	return this.storedData;
	}
}

From there, you could create a new instance of the function (var storage = new SimpleStorage) and call .set() and .get() methods on it directly:

> var storage = new SimpleStorage();
> storage.set(15);
> storage.get(); // “15”

Simple, right? Of course, this would not be very persistent - the moment you close the program, browser or console window, the memory on your machine is cleared and you lose anything stored in the variable.

The power of smart contracts

On Ethereum, each call to the set() function kicks off a database transaction in the background. This database lives directly on the Ethereum blockchain. Every new record in the database is distributed to the rest of the network.

The new value of the storedData variable, along with the message sent to the contract that includes the address of the account that made the change, is permanently recorded on the Ethereum blockchain.

This might not seem like much but thanks to the underlying blockchain, Ethereum becomes incredibly powerful:

Every change in a contract’s state is verified and tracked globally, running on a fault-tolerant network that essentially makes the contract unstoppable. Once deployed, a contract can basically run forever!

So while it looks about as straightforward as an in-memory variable assignment, you’re actually committing an irreversible transaction on a public chain that is then independently verified by a network of miners. This makes it impossible to misrepresent the contents of the number, or the audit trail that led up to the number being what it is:

If you’re using an Ethereum contract to record variables of great importance, like an amount of currency or the legal status of a contract, there’s no way for anyone involved to “fudge” the data.

Ethereum

Building a bank on Ethereum

That means, for example, that we could build our own bank! It’s really straight-forward:

pragma solidity ^0.4.0;

contract Coin {
	// The keyword "public" makes those variables
	// readable from outside.
	address public minter;
	mapping (address => uint) public balances;

	// Events allow light clients to react on
	// changes efficiently.
	event Sent(address from, address to, uint amount);

	// This is the constructor whose code is
	// run only when the contract is created.
	function Coin() public {
    	minter = msg.sender;
	}

	function mint(address receiver, uint amount) public {
    	if (msg.sender != minter) return;
    	balances[receiver] += amount;
	}

	function send(address receiver, uint amount) public {
    	if (balances[msg.sender] < amount) return;
    	balances[msg.sender] -= amount;
    	balances[receiver] += amount;
    	Sent(msg.sender, receiver, amount);
	}
}

This snippet is taken from the official Solidity documentation. Let’s break it down quickly:

address public minter;

This will be the account address of the person or contract that is allowed to create new coins. It’s initialized when you first create the contract and permanently set to the address of the creating account (meaning you). Since this contract defines no way to change the variable after its construction, there is no way to later “hand over” the minting rights at our new bank.

mapping(address => uint) public balances;

This is all the code necessary to create a basic accounting system on Ethereum. It will create a storage structure similar to a hash map and lets you store an integer against an account address. Then the contract declares two functions:

function mint(address receiver, uint amount) public {}

This is fairly straightforward: if the call to this mint() function came from the account that created the contract (the minter), then it will add whatever amount of coins you specify. Finally, you need a way to send coins around:

function send(address receiver, uint amount) public

This function checks if the sender actually has enough balance available to make the specified transaction. It will then “send” the coins by decrementing the senders balance and incrementing the balance of the receiver, before firing off an event to announce that a transfer has taken place.

Granted, this might seem like a trivial example, but it shows the core operations of a good ledger system that can serve as the foundation of a new type of bank - or any organization that needs to keep thorough and traceable records.

Digital rights on Ethereum

Financial transactions are of course not the only thing you can store in this way. You can also set up a system to transfer legally-binding, real-world ownership records - something that Mattereum has built an entire business model around. Smart contracts can help to transparently transfer the rights of properties, songs (as in Ujo’s business model) and shipped goods from one account to another.

Cryptocollectibles

CryptoKitties is one of the world’s first games to be built on blockchain technology. The makers decided to use smart contracts to combine society’s love of cat imagery with rewarding games and the appeal of unique collectibles: Users can not only acquire but also breed digital cats.

Cryptokitties
(This image is a modified version of the official cryptokitty listing page)

The concept is relatively simple, if technically complex:

  • Cats have (c)attributes.
  • The combinations of attributes are guaranteed to be globally unique.
  • New kitties are generated through breeding, which randomly combines attributes from the parents to produce new offspring.

Every CryptoKitty in existence is therefore one-of-a-kind and kittens with great attributes can be worth a lot to the right buyer - just like real-world cats.

Uniqueness through non-fungible tokens

The feature that guarantees the global uniqueness of each kitten - and the unfalsifiable proof of ownership - relies on a set of Ethereum features referred to as ERC721 NFTs or Non-Fungible Tokens.

Fungible tokens are all over the smart contracts mentioned above: Numbers that can be divided into smaller numbers are needed if you want to use them as a currency. Ethereum, however, also allows you to create tokens that cannot be divided. These need to change ownership as complete units.

This possibility has given rise to a new type of digital asset: unique collectibles. The underlying blockchain ensures that only one instance of an asset will ever exist and that the ownership of that asset is secured. Meanwhile, the programmable layer of Ethereum lets you add sophisticated attributes and behavior to the asset.

In the online gaming arena, this opens entire new worlds of possibilities:

  • Game licenses themselves can be stored and transferred across a blockchain, making regionless gifting possible.
  • You could buy virtual land in a virtual world.
  • You can transfer unique items between different games.
  • You could sell in-game assets across different marketplaces.

CurioCards is a great example how this can be explored for digital art but non-fungible tokens can extend to the real world too: A token that’s linked to the possession of a physical asset can now be securely moved across a blockchain, in far less time than a traditional paper-based process might take.

Already, conceptual use-cases are popping up all over the place, including a proposal to enable rentable tokens whilst startup Rentberry has extended their apartment rental business to the Ethereum blockchain.

In Conclusion

Ethereum represents a new kind of programmable asset layer. It enables developers to create digital assets whose ownership works very similarly to physical assets, but can be scaled and distributed at a level only possible in the digital realm. It provides new kinds of interdependent business logic, giving us a preview of what a programmable world might look like in a few years:

  • Smart contracts can enable unstoppable business logic, executing agreements in code with a level of reliability that presently only exists in law.
  • NFTs enable the creation of globally-unique digital assets - a resource with major utility in art, entertainment and business.
  • While present-day projects are mostly experiments, prototypes and toys, the long-term promise of the technology is becoming clearer every day.

And the best part?
The Ethereum project has made all of the above accessible to developers without backgrounds in cryptography or protocol design. All you need to get started are an idea and a basic understanding of Javascript.

Trying it out

  • Remix - Ethereum’s online IDE that lets you build Solidity applications in the browser and execute them in a sandboxed Javascript VM. Anything you build here will operate as-is when deployed to the Ethereum blockchain.

  • Simple Ethereum tutorial - along the step-by-step instructions for deploying your contract to the Ethereum blockchain, this tutorial will help you to build a greeter bot. Try this when you are already comfortable with how the contracts operate, since running them on the public chain will require payment in real Ether.


This article was written by Wogan May (@WoganMay) - a full-stack web developer with an interest in emerging technologies. His background includes digital marketing, B2B application development, cloud-based system architecture and enterprise consulting.

Recent posts

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.