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.


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() {

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.

No comments:

Post a Comment

Ethereum Solidity Compiler

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