Writing Software Contracts for Ethereum — Part 2

Satish Manohar Talim
Coinmonks
8 min readAug 4, 2017

--

(Updated on 3rd Feb. 2018)

  • In Part 1 we talked about the basics of Blockchain.
  • In Part 3 we will setup our private blockchain using geth.

What are Smart Contracts?

1. Smart-contracts are a way for people all across the globe to do business with each other even if they don’t speak the same language or use the same currency. Smart contracts help you exchange money, property, shares, or anything of value in a transparent, conflict-free way, while avoiding the services of a middleman.

2. The best way to describe smart contracts is to compare the technology to a vending machine. Ordinarily, you would go to a lawyer or a notary, pay them, and wait while you get the document. With smart contracts, you simply drop a cryptocurrency into the vending machine (i.e. ledger), and your driver’s license, or whatever drops into your account. More so, smart contracts not only define the rules and penalties around an agreement in the same way that a traditional contract does, but also automatically enforce those obligations.

3. Smart contracts are a series of instructions, written using the programming language “Solidity”, which work on the basis of the IFTTT logic aka the IF-THIS-THEN-THAT logic.

4. You can use smart contracts for all sort of situations that range from financial derivatives to insurance premiums, breach contracts, property law, credit enforcement, financial services, legal processes and crowd funding agreements.

Smart Contract — image courtesy Blockgeek

Three companies to watch are:

Ethereum software: geth, eth, pyethapp

The official Ethereum clients are all open source — that is you can see the code behind them, and tweak them to make your own versions. The most popular clients are:

1. geth (written in a language called Go) https://github.com/ethereum/go-ethereum geth is the entry point into the Ethereum network (main-, test- or private net), capable of running as a full node (default) archive node (retaining all historical state) or a light node (retrieving data live).
2. eth (written in C++) https://github.com/ethereum/cpp-ethereum
3. pyethapp (written in Python) https://github.com/ethereum/pyethapp

These are all command-line based programs (think green text on black backgrounds) and so additional software can be used for a nicer graphical interface.

A popular Ethereum browser is the Mist browser which is fast and a secure way of interacting with the Ethereum network.

The most widely used Ethereum client (geth) is written in Go, which means there should be a nice ecosystem for interacting with Ethereum and smart contracts using Go with nice features such as code-generation and reusable helpers from shared libraries. We shall explore this in the forthcoming articles.

Smart Contract languages: Solidity / Serpent, LLL

There are three common languages smart contracts are written in, which can be compiled into smart contracts and run on Ethereum Virtual Machines. They are:

  1. Solidity — looks a little bit like Javascript. This is currently the most popular and functional smart contract scripting language.
  2. Serpent — similar to the language Python, and was popular in the early history of Ethereum. However, it is due for retirement soon.
  3. LLL (Lisp Like Language) — similar to Lisp and was only really used in the very early days. It is probably the hardest to write in.

All the above languages can be compiled into EVM bytecode.

Let’s understand and start learning the Solidity language

Solidity is a contract-oriented, high-level language whose syntax is similar to that of JavaScript and it is designed to target the Ethereum Virtual Machine (EVM).

Solidity Language itself is a tool that we use to generate machine-level code that can execute on the EVM, it’s a language with a compiler which takes our high-level human-readable code and breaks it down into simple instructions. Here’s a list of all available opcodes.

Solidity is statically typed (the type of the variable will be determined at compile time and not at run time), supports inheritance, libraries and complex user-defined types among other features.

Solidity has .sol as a file extension.

To learn Solidity you don’t need an Ethereum node to write and deploy smart contracts. The best way to try out Solidity for small contracts right now, is using Remix — a browser-based IDE with integrated compiler and Solidity runtime environment without server-side components.

A Simple Smart Contract On Ethereum

Let us begin with a simple smart contract example MessageContract.sol where we learn how to write Getters and Setters in Solidity.

MessageContract.sol

Using Remix

Click on the + button at the top left

Load Remix and you will see on the left side a button to load new solidity files; in the center you have the code window and on the right side you can see the control elements that has tabs for Run, Compile etc. Now click on the + button at the top left and give the name as MessageContract.sol Press OK.

Copy the above code i.e. MessageContract.sol into Remix’s middle window.

Click on the Run button on the top right and it will show you the current environment. We will use the JavaScript VM where everything is local and in memory only. Also, you can see that it gives you several accounts for testing. Now, click on the pink colored Create button.

Click on the Create button to execute your code

You should see a getMessage button in blue (that’s the getter) and the setMessage in pink (that’s the setter). Enter “some text” in double quotes in the setMessage text area and press the setMessage button. The new value is now set. If you press the getMessage button you should now see “some text”.

Let us try and understand what we are doing inside the above program.

Understanding Solidity

pragma:

Source files can (and should) be annotated with a so-called version pragma to reject being compiled with future compiler versions that might introduce incompatible changes.

The version pragma is used as follows:

pragma solidity ^0.4.0;

Such a source file will not compile with a compiler earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0 (this second condition is added by using ^).

Structure of a Contract:

The Solidity docs say “Contracts in Solidity are similar to classes in object-oriented languages” that resides at a specific address on the Ethereum blockchain.

  • Each contract can contain declarations of State Variables, Functions, Function Modifiers, Events, Structs Types and Enum Types (more on these later).
  • Furthermore, contracts can inherit from other contracts. An interesting read is related to the second biggest ETH theft of all time that was basically triggered by inheritance (via delegation).

Code Layout:

  • Indentation — Use 4 spaces per indentation level.
  • Tabs or Spaces — Spaces are the preferred indentation method. Mixing tabs and spaces should be avoided.
  • Source File Encoding — UTF-8 or ASCII encoding is preferred.
  • Comments — Single-line comments (//) and multi-line comments (/*…*/) are possible.
// This is a single-line comment.

/*
This is a
multi-line comment.
*/

Naming Conventions:

  • Contracts and libraries should be named using the CamelCase style (CamelCase is a naming convention in which a name is formed of multiple words that are joined together as a single word with the first letter of each of the multiple words capitalized so that each word that makes up the name can easily be read. The name derives from the hump or humps that seem to appear in any CamelCase name. In UpperCamelCase, the first letter of the new word is upper case, allowing it to be easily distinguished from a lowerCamelCase name, in which the first letter of the first name is lower case.). In the code above, we have contract MessageContract
  • Function Names should use mixedCase (lowerCamelCase name). In the code above, we have a function getMessage()

String Literals:

  • String literals are written with either double or single-quotes, for example “Hello World”
  • A convention is that strings should be quoted with double-quotes instead of single-quotes.

string:

  • It’s a dynamic sized unicode string assumed to be UTF-8 encoded.
  • In Solidity one requires to mention the type of variable, in our case string message.

Statement:

A basic statement would setup a variable (message in our case) and give it a value. This type of a statement is called an assignment statement because it sets a value on a variable.

string message = “Hello World”;

All statements must end in a semicolon (;).

Functions:

For short function declarations, it is recommended:

  • for the opening brace of the function body to be kept on the same line as the function declaration.
  • The closing brace should be at the same indentation level as the function declaration.
  • The opening brace should be preceded by a single space.

When declaring short functions with a single statement, it is permissible to do it on a single line. For example:

function shortFunction() { doSomething(); }

There are four types of visibilities for functions: external, public, internal or private, where the default ispublic. Do note that different visibility levels will not “hide” your code from others, but just prevent other contracts from calling them. The visibility specifier is given after the type for state variables and between parameter list and return parameter list for functions.

State Variables:

There are three types of visibilities for state variables: public, internal or private, where the default is internal (these functions and state variables can only be accessed internally i.e. from within the current contract or contracts deriving from it).

State variables can be declared as constant. In this case, they have to be assigned from an expression which is a constant at compile time.

The compiler does not reserve a storage slot for these constant state variables, and every occurrence is replaced by the respective constant expression (which might be computed to a single value by the optimizer).

Not all types for constants are implemented at this time. The only supported types are value types and strings.

The visibility specifier is given after the type for state variables and between parameter list and return parameter list for functions.

Note: If you make your state variables public — the compiler will create getters for you automatically.

Resources

Videos:

Links:

Credits

Thank you Michael Kohl for reviewing this article and offering suggestions. Much appreciated.

Get Best Software Deals Directly In Your Inbox

--

--

Satish Manohar Talim
Coinmonks

Senior Technical Evangelist at GoProducts Engineering India LLP, Co-Organizer GopherConIndia. Director JoshSoftware and Maybole Technologies. #golang hobbyist