Functions - Structure of an Ethereum Smart Contract


Functions are the executable units of code within a contract. Again these are similar to the functions in the object oriented world.

A contract can have the following types of functions
  • Member functions
  • Constructor
  • Default function
  • Constant functions

Member functions

These are the functions which modify the state variables of the contract and performs transactions that are stored in the block chain. These functions typically don’t have return values.

// hiring the contractor to perform the work
function hire (address _contractor) {
    contractor = _contractor;
}


In the above code the client of the service requestor finalized the contractor and is hiring the contractor to perform the service. As you see this function is updating the contractor state variable.

Constructor

A constructor is a special type of member function. The constructor is called only once for the life of the contract and during the initialization of the contract. Hence you can have all your initialization logic in this constructor. As show below I am storing the client address, one who creates the contract (msg.sender is the account which initializes the contract) and the 0x platform address which can be used to arbitrage between client and contractor.

// creates the service for the client
// 0x will be platform provider
function Service (address _platform) {
    client = msg.sender;
    platform = _platform;
} 

Default function

Default function is a function which does not have a function name. This function is invoked whenever a contact is called with a function name that does not exist. For example if user calls a function called “close” and this close function does not exist in the contract, then the default function will be called. In our code we don’t want users to call functions that don’t exist, hence throwing an exception.

//default function
function() {
    throw;
}   

Constant function

A constant function is used in scenarios where you want to read the state variables of the contract and don’t want to update their state. Constant functions prevent updating the state variables of the contract. In our 0x contract we will have a validate function which checks the terms and conditions of our smart contract. For this POC the actual validation is out of scope. So let’s assume that the validation is always successful and return true as shown below:

// validate the terms of the contract
function validate() constant returns (bool) {
    // for POC we are doing additional validations
    return true;
}

This blog is part of Structure of an Ethereum Smart Contract, please refer to it for more details.

Version Pragma - Structure of an Ethereum Smart Contract

This pragma directive tells the compiler to use the correction version to compile the contract and to reject compiling with an incompatible compiler. This annotation ensures that our code is always compiled correctly as we intended.

The version pragma is used as follows:

pragma solidity ^0.4.14;


This directive is optional, but is highly recommended to annotate every source file with this version pragma. The version pragma uses semantic versioning and is denoted by [major, minor, patch] tuple. As shown above 0.4.14.

In the above version directive we used caret range to specify the supported compilers. The caret range allows compiler greater than the specified version and does not allow compiler greater than the left most non-zero digit. In our definition the left most non-zero digit is 4 (0.4). So the caret range allows compiler greater than the specified version (0.4.14) and does not allow greater than the left most non-zero digit (0.5.0). In other words, only compiler with version >= 0.4.14 and < 0.5.0 be allowed to compile to compile our contract code. This version pragma directive can also include prerelease tags such as alpha, beta. Below are examples of caret ranges:
  •  ^0.4.14 := >=0.4.14 and <0.5.0
  •  ^1.2.3 := >=1.2.3 and <2.0.0
  •  ^0.2.3 := >=0.2.3 <0.3.0
  •  ^0.0.3 := >=0.0.3 <0.0.4

The solidity compiler can use complex rules for identifying the correct compiler version. But this may be rarely used. Unless you want to target a specific version range, you don’t need to go that complex.

This blog is part of Structure of an Ethereum Smart Contract, please refer to it for more details.

Ethereum Mist supersedes Wallet


Ethereum Mist now replaces the Ethereum Wallet. Here is the Ethereum wiki on wallet:

“Ethereum Wallet is just a Mist implementation enabled to access a single dapp – the wallet dapp, this is due to missing features in Mist itself and so that we are able to release earlier. So the wallet is Mist, in wallet mode”

As you see Ethereum Wallet is a stop gap solution while Mist is being built out. With Mist is getting ready for production release, we may as well be using Mist instead of Wallet.

Mist is a cross platform hybrid desktop application using web interface. It is built with electron. It will be easy for the web developers to debug using the Mist browser.


Ethereum Mist Browser with private chain


You can connect Ethereum Mist browser to the private chain and take advantages of the mist features. Here are the simple 2 steps to connect the mist browser to the private chain:
  • Start the private chain. Refer to my blog Ethereum Dev Chain - Private Chain for more details.
  • Run the Mist. It automatically connects to the private chain that is running on the same machine

That’s all. Now we can have the mist connected to the test chain as shown below:

Please note that on the windows machine, I had to run the geth and mist with administrative permissions


Ethereum Wallet with private chain

 
You can connect Ethereum wallet to the private chain and take advantages of the wallet features. Here are the simple 2 steps to connect the wallet to the private chain:
  • Start the private chain. Refer to my blog Ethereum Dev Chain - Private Chain for more details.
  • Run the Ethereum wallet. It automatically connects to the private chain that is running on the same machine


That’s all. Now we can have the wallet connected to the test chain as shown below:

Please note that on the windows machine, I had to run the geth and wallet with administrative permissions


Hello World Ethereum Smart Contract with VS Code and Solidity


In my previous blog we have created our first Hello world app using Remix Solidity IDE.

In this blog, I will go over how to use Visual Studio Code to compile the Hello World contract and deploy the contract on a private chain and Rinkeby chain. Please refer to my other related blogs for setting up Visual Studio Code, Private Chain and connecting to Rinkeby Testnet.

Let’s start by opening Visual Studio Code and open a folder in VS Code. If required create the folder. The folder is required because VS code compiles the code and creates the abi and bytecode here.

Create a new file in this folder called HelloWorld.sol with the below code:
pragma solidity ^0.4.11;

contract HelloWorld {

    function greet() public constant returns (string) {
        return "Hello World!";
    }
}

Compile this smart contract by pressing F5 key. This creates a bin folder with abi and bin (bytecode). Here are the contents of the abi and bin file:
abi:
[{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]

bin(bytecode):
6060604052341561000c57fe5b5b6101498061001c6000396000f300606060405263ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663cfae3217811461003a575bfe5b341561004257fe5b61004a6100ca565b604080516020808252835181830152835191928392908301918501908083838215610090575b80518252602083111561009057601f199092019160209182019101610070565b505050905090810190601f1680156100bc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100d261010b565b5060408051808201909152600c81527f48656c6c6f20576f726c6421000000000000000000000000000000000000000060208201525b90565b604080516020810190915260008152905600a165627a7a723058205168b085c257b42e405c11a8e900935fd85bd351767a3ed78211b54b7c6df2e10029

Now let’s start the private chain as mentioned in my blog Ethereum Dev Chain - Private Chain

Here are the steps to be followed in the JavaScript console to deploy the contract:
  • Unlock the account so that Ether can be used for gas
> personal.unlockAccount(eth.accounts[0], "password")
true
In the above command I am using the first account. If required you can specify any other account
  • Define the abi & bytecode variables. Prefix the bytecode with “0x”
var abi = [{ abi generated by the compiler }]
var bytecode = “0x<bytecode generated by compiler>”
  • Deploy the contract
> var contract = eth.contract(abi)
  • Find the gas estimate for deploying the contract
eth.estimateGas({ data: bytecode} )
This gives the gas required to deploy the contract. Currently it’s value is 138902. Specify this value in the next step while creating an instance of this contract
  • Now create an instance of this contract.
> var instance = contract.new({
......    from:eth.accounts[0],
......    data:bytecode,
......    gas:138902}, function(err, contractInstance){
......     if(!err) {
.........        if(!contractInstance.address) {
............            console.log("Tx Hash: " + contractInstance.transactionHash) // The hash of the transaction
............        } else {
............            console.log("Address: " + contractInstance.address) // the contract address
............        }
.........     }
...... else {
......... console.log(err)
......... }
...... });
Tx Hash: 0x57228ccd8013aa17b134c3f76147a1c5a74f40f98c7bc352e484f42581e30355
undefined
> Address: 0x44408814564648d05d4cfcf12397151cfee0af52
The contract creation is an asynchronous function. Once the contract is mined, the call back function returns the transaction hash and address at which the contract is deployed.
  • Wait till the contract is mined and address is shown in the console
  • Now invoke the greet function
> instance.greet()
"Hello World!"

With above steps we successfully deployed the contract onto a private chain and invoked it. Here is the complete JavaScript console code:
personal.unlockAccount(eth.accounts[0], "password")
var abi = [{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]
var bytecode = "0x6060604052341561000c57fe5b5b6101498061001c6000396000f300606060405263ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663cfae3217811461003a575bfe5b341561004257fe5b61004a6100ca565b604080516020808252835181830152835191928392908301918501908083838215610090575b80518252602083111561009057601f199092019160209182019101610070565b505050905090810190601f1680156100bc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100d261010b565b5060408051808201909152600c81527f48656c6c6f20576f726c6421000000000000000000000000000000000000000060208201525b90565b604080516020810190915260008152905600a165627a7a723058205168b085c257b42e405c11a8e900935fd85bd351767a3ed78211b54b7c6df2e10029"

var contract = eth.contract(abi)
var gas = eth.estimateGas({ data: bytecode} )

var instance = contract.new({
   from:eth.accounts[0],
   data:bytecode,
   gas:gas}, function(err, contractInstance){
    if(!err) {
       if(!contractInstance.address) {
           console.log("Tx Hash: " + contractInstance.transactionHash) // The hash of the transaction
       } else {
           console.log("Address: " + contractInstance.address) // the contract address
       }
    }
    else {
        console.log(err)
    }
});

//wait for the mining to be completed
instance.greet()

I generally use Rinkeby during the UAT environment. Let’s run the above script in the Rinkeby environment and check it. Please refer to my other blog on how to connect to Rinkeby chain, Setting up Ethereum Rinkeby Testnet

I deployed the contract on Rinkeby network and here is the screenshot of this contract:


Nethereum – A .NET Library for Ethereum


Nethereum is the .Net integration library for Ethereum, it allows you to interact with Ethereum clients like geth, eth or parity using RPC. The library has very similar functionality as the Javascript Etherum Web3 RPC Client Library (from GitHub documentation).

Nethereum is the open source library that is actively built at GitHub.

I am using Nethereum to programmatically deploy the smart contracts and send transactions to these contracts. In this blog, I will walk through setting up the Visual Studio deployment environment. Below are the simple two-step process to setup the Visual Studio Development Environment using Nethereum

Step 1: Create an ASP.NET Core Web Application

Step 2: Install the Nuget Package Nethereum.Geth

Now we are ready to use C# with Ethereum.


Ethereum Solidity Compiler

Ethereum contracts are written in the high level language called Solidity and compiled into bytecode using the Solidity compiler. This ...