Ethereum Solidity Compiler


Ethereum contracts are written in the high level language called Solidity and compiled into bytecode using the Solidity compiler. This bytecode is then uploaded on to the blockchain.

As mentioned in the previous blog, Visual Studio Code and several editors provide integrated environment to compile the code. If you want to manually run the compiler then here are the steps for compiling a smart contract.

Download the compiler from the GitHub release site
Based on your platform download the corresponding bits

Open the command line and run the below command to compile our 0xService or any smart contract
%path%\solc.exe --bin --abi --overwrite -o bin Service.sol

As you see in the above we are passing bin and abi arguments to specify to the compiler to create the bin and abi file. The generated files are created in the bin folder as mentioned by the other bin attribute. The overwrite flag is used to overwrite the previously generated abi and bytecodes.

0x Services Objective & Requirements


Below are the objective and requirements of 0x platform

Objective:
Provide a decentralized platform where a client can post a service request and a provider or contractor perform the service in a trustless environment and with escrow payment system.

Requirements:
Client
  • Register and create an account with 0x. 0x creates an user account in Ethereum chain
  • Post a service request in 0x and set its price in Ether or 0x tokens. 0x creates a smart contract on Ethereum chain
  • 0x charges a small amount of fee for creating the contract, this is in addition to the gas required by Ethereum chain. This fee will be paid through 0x tokens
  • Negotiate the price of the service with the provider (out of scope for POC)
  • The contract acts as the escrow account. Fund the contract with the agreed service amount. This funding can be done through Ether or 0x tokens.
  • Once the work is complete authorize payment to the contractor.
  • Settle disputes with help of arbiter

Contractor
  • Register and create an account with 0x. 0x creates an user account in Ethereum chain
  • Apply for a service
  • Perform the requested service (outside of 0x)
  • Request payment for the service
  • Receive payment to the account
  • Raise arbitration if the payment is not received

Arbiter
  • Settle the dispute and authorize the payment from escrow account.
  • 0x acts as the default arbiter. The client can choose his own arbiter.


The below are the out of scope requirements for the current implementation and these can be taken up at a later time.
  • Terms and Conditions of the work which will be checked before the payment is made
  • Termination procedure
  • Intermediate payment or payment schedule where the contractor gets payments based on the payment terms

s

Visibility Modifiers


Solidity exposes state variables and functions to internal and external worlds using the visibility modifiers. There are four types of visibility modifiers public, internal, private and external.

Functions can have all the four visibility modifiers, the default visibility modifier for functions is public. State variables cannot have external visibility modifier and the default modifier is internal.

Below is the brief description and usage of these visibility modifiers for state variables and functions:

public

Public functions are part of the contract interface and can be either accessible within the contract or via messages. Public state variables are accessible similar to the functions.
contract Service {
    address public arbiter; // 0x is the default arbiter for every contract
    address contractor;

    /// @notice Once the service is completed, client pays to the contractor
    function pay() public {
        contractor.transfer(amountPaid);
        amountPaid = 0;
    }
}

For public State variables Solidity automatically generates a getter function. In the above contract, arbiter is defined as public, Solidity generates a function called arbiter which returns the arbiter address.

internal

The internal functions and state variables can only be accessed within the contract or derived contracts. This is similar to protected variables in C# and other object oriented programming.
In the above code, contractor state variable does not have any visibility modifier. As per default configuration, the contract state variable will be on internal scope.

private

Private functions and state variables, like the name indicates, are accessible within the contract they defined. They are not available in the derived contracts.

external

An external function is similar to public function. In addition from being called internally and via transactions, external functions can be called from other contracts. To call an external function internally it needs to be prefixed with this (this.fund()). External functions can access other functions and state variable directly (without the prefix of this)
/// @notice based on the agreement, client will fund the contract
/// this amount will be payed to contractor at the end
function fund() external onlyClient payable {
    amountPaid += msg.value;
}


As mentioned earlier State variables cannot have external visibility modifier. Only functions can have external visibility modifier.

Solidity Constant


Solidity supports to declare constant state variables and functions. A keyword constant is used to define constants in Solidity.

Constant State Variables

State variables can be declared as constant. All constant state variables should be assigned to a constant value at compile time. It can have an expression, but that expression should be evaluated to constant at compile time. Solidity only supports value types and string types as constants. Here is an example of defining constant static variable from Ethereum documentation. Currently in our contract we do not need this constant variables.

contract C {
    uint constant x = 32**22 + 8;
    string constant text = "abc";
    bytes32 constant myHash = keccak256("abc");
}

Constant Functions

Constant function are those functions which does not modify the state of the contract. These functions are used to return values from the contract. In our 0x service contract we defined a constant function which returns the address of the contractor.
/// @notice Get the contractor assigned to the service
/// @return contractor address
function getContractorAddress() public constant returns (address) {
    return contractor;
}

Ethereum Solidity Function Parameters


Solidity functions, like any other programming language, take input parameters and return output parameters. They can also return arbitrary number of parameters as output (this is similar to Tuples in C# 7). 

Input Parameters

The input parameters are defined same as variables. A function can take multiple number of input parameters. In our service if we want to hire a contractor we specify the contract address as the input parameter.
/// @notice hiring the contractor to perform the work
/// @param _contractor ethereum address of the contractor
function hire (address _contractor) onlyClient {
    contractor = _contractor;
}

Output Parameters

Solidity functions support multiple ways of returning parameters. The function return type should be declared with returns keyword. In our service if we want to return the contractor address, then we would write as below:
/// @notice Get the contractor assigned to the service
/// @return contractor address
function getContractorAddress() public constant returns (address) {
    return contractor;
}

Similar to other languages we can use the keyword return to return the function output. Solidity supports named parameters we can provide name of the return parameter as shown below:
/// @notice Get the contractor assigned to the service
/// @return contractor address
function getContractorAddress() public constant returns (address _contractor) {
    _contractor = contractor;
}

In the above code we provided variable name to the return parameter, _contractor. Assigning value to the variable will automatically return its value.

Solidity supports returning values. It internally uses tuple types, i.e. a list of objects of potentially different types whose size is a constant at compile-time. Those tuples can be used to return multiple values at the same time. The functionality is similar to tuples in C# 7. Let’s return all the addresses in our Service Contract
/// @notice Get the addresses of client, contractor and 0x platform
/// @return client, contractor and platform address
function getAllAddresses() public constant returns (address, address, address) {
    return (client, contractor, platform);
}


Ethereum Solidity Comments


Similar to JavaScript, Solidity supports single line comments (//) and multi-line comments (/*…*/) as shown below

// This is a single-line comment.

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

Solidity contracts can also have a special form of comments for documentation. This documentation type of comments is called Ethereum Natural Specification Format (Natspec). Natspec format uses doxygen tags. It can have either one or multiple lines starting with /// or a multiline comment starting with /** and ending with */. Here is how we are using Natspec documentation in our service contract.

/// @title contract between client and contractor.
contract Service {
    address contractor; // address of the hired contractor

    /// @notice Hiring the contractor to perform the work
    /// @param _contractor Ethereum address of the contractor
    function hire (address _contractor) onlyClient {
        contractor = _contractor;
    }

    /// @notice Get the contractor assigned to the service
    /// @return contractor address
    function getContractorAddress() public constant returns (address) {
        return contractor;
    }
}

In the above code we documented the title of the contract. We also documented the two functions along with their parameters. This documentation comments are parsed by Natspec client and create documentation json files.

Ethereum Solidity


Solidity is a contract-oriented, high-level programming language for writing smart contracts which run on Ethereum Virtual Machine. Solidity language is statically typed and follows object-oriented principles.  It supports inheritance, libraries and complex user-defined types. Solidity’s syntax is similar to that of ECMA Script (JavaScript) syntax making it familiar for existing web developers.

Here is the Hello World solidity code we looked earlier.
pragma solidity ^0.4.14;

contract HelloWorld {

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

Solidity code is compiled to bytecode that is executable on the EVM. We can use solc, the solidity compiler, or developer editors such as Visual Studio Code to compile and generate the bytecode. Here is the bytecode for the above Hello World sample.

6060604052341561000c57fe5b5b6101498061001c6000396000f300606060405263ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663cfae3217811461003a575bfe5b341561004257fe5b61004a6100ca565b604080516020808252835181830152835191928392908301918501908083838215610090575b80518252602083111561009057601f199092019160209182019101610070565b505050905090810190601f1680156100bc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100d261010b565b5060408051808201909152600c81527f48656c6c6f20576f726c6421000000000000000000000000000000000000000060208201525b90565b604080516020810190915260008152905600a165627a7a723058205168b085c257b42e405c11a8e900935fd85bd351767a3ed78211b54b7c6df2e10029

Solidity also uses an application binary interface (ABI). ABI defines the structure and methods used in the contract. Ethereum internally uses ABI for encoding and decoding data into and out of transactions. We can use this ABI during contract deploying and also to decode the data passed with transactions. Here is the ABI for our Hello World code.

[{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]


Ethereum Solidity Compiler

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