Ethereum Tutorials

SMART CONTRACTS

Common Practices

As they say, if you want to learn programming, take disassembler and look how others do it :)

If you look through etherscan.io for "verified contracts", you can learn from large number of existing examples. There are certain patterns that are hard to miss: most of the contracts use standard parent classes.

There are few - just few - classes that are used over and over again as parent classes for different contracts. Let's look at some of them.

SafeMath

contract SafeMath {

    /* function assert(bool assertion) internal { */
    /*   if (!assertion) { */
    /*     throw; */
    /*   } */
    /* }      // assert no longer needed once solidity is on 0.4.10 */

    function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
      uint256 z = x + y;
      assert((z >= x) && (z >= y));
      return z;
    }
    ......

The contract takes care of overflow/underflow problem and allows you to overload math. operations. Ethereum Virtual Machine (EVM) does not have built-in overflow protection: if you add two integers together and the result exceeds the max integer value (2^256-1), an overflow happens.

An underflow happens way more often as you do something like that:

uint balance = 3;
uint withdraw = 4;
uint new_balance = balance - withdraw;	// as we try going below zero, we get a REALLY large positive

... and is handled by function

safeSubtract(uint256 x, uint256 y) internal returns(uint256) 
{
    assert(x >= y);
    uint256 z = x - y;
    return z;
}

And so on. Depending on the contract's needs, some of these functions can be omitted.

Token

			
contract Token {
    uint256 public totalSupply;
    function balanceOf(address _owner) constant returns (uint256 balance);
    function transfer(address _to, uint256 _value) returns (bool success);
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
    function approve(address _spender, uint256 _value) returns (bool success);
    function allowance(address _owner, address _spender) constant returns (uint256 remaining);
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

A nice wrapper for a required set of functions. It means you do not want to forget including one of them, if you want your contract to be compatible with certain Web interface. In other words, a standartized HTML page, one relying on ONLY functions of Token class, will be able to handle ANY contract that exposes these functions. To understand better why it can be so important, imagine a stock exchange, where by "stock" we mean a Token-derived class.

StandardToken

As most of these interfaces can be implemented in a trivial way, here comes another standard parent class:

contract StandardToken is Token {
    function transfer(address _to, uint256 _value) returns (bool success) {
      if (balances[msg.sender] >= _value && _value > 0) {
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
      } else {
        return false;
      }
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
      if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
        balances[_to] += _value;
        balances[_from] -= _value;
        allowed[_from][msg.sender] -= _value;
        Transfer(_from, _to, _value);
        return true;
      } else {
        return false;
      }
    }

    function balanceOf(address _owner) constant returns (uint256 balance) {
        return balances[_owner];
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
      return allowed[_owner][_spender];
    }

    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;
}

As one would expect, Token can be extended by adding some code - if the code is standard and well-tested, why invent something new every time?

ERC20

ERC20 is a very important and to some extent, revolutionary protocol. It defines a set of commands that a token should implement; by "token" here I mean Ethereum ICO tokens (which explains why ERC20 is so important). ERC20 compliant tokens all have the same functions, with the same names, that take the same arguments; these tokens are compatible with standartized token exchange systems and are, de-facto, standard.

					
/**
 * @title ERC20Basic
 * @dev Simpler version of ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/179
 */
contract ERC20Basic {
  uint256 public totalSupply;
  function balanceOf(address who) constant returns (uint256);
  function transfer(address to, uint256 value) returns (bool);
  event Transfer(address indexed from, address indexed to, uint256 value);
}

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
contract ERC20 is ERC20Basic {
  function allowance(address owner, address spender) constant returns (uint256);
  function transferFrom(address from, address to, uint256 value) returns (bool);
  function approve(address spender, uint256 value) returns (bool);
  event Approval(address indexed owner, address indexed spender, uint256 value);
}

/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances. 
 */
contract BasicToken is ERC20Basic {
  using SafeMath for uint256;

  mapping(address => uint256) balances;

  /**
  * @dev transfer token for a specified address
  * @param _to The address to transfer to.
  * @param _value The amount to be transferred.
  */
  function transfer(address _to, uint256 _value) returns (bool) {
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

  /**
  * @dev Gets the balance of the specified address.
  * @param _owner The address to query the the balance of. 
  * @return An uint256 representing the amount owned by the passed address.
  */
  function balanceOf(address _owner) constant returns (uint256 balance) {
    return balances[_owner];
  }

}

/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
contract StandardToken is ERC20, BasicToken {

  mapping (address => mapping (address => uint256)) allowed;


  /**
   * @dev Transfer tokens from one address to another
   * @param _from address The address which you want to send tokens from
   * @param _to address The address which you want to transfer to
   * @param _value uint256 the amout of tokens to be transfered
   */
  function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
    var _allowance = allowed[_from][msg.sender];

    // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
    // require (_value <= _allowance);

    balances[_to] = balances[_to].add(_value);
    balances[_from] = balances[_from].sub(_value);
    allowed[_from][msg.sender] = _allowance.sub(_value);
    Transfer(_from, _to, _value);
    return true;
  }

  /**
   * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
   * @param _spender The address which will spend the funds.
   * @param _value The amount of tokens to be spent.
   */
  function approve(address _spender, uint256 _value) returns (bool) {

    // To change the approve amount you first have to reduce the addresses`
    //  allowance to zero by calling `approve(_spender, 0)` if it is not
    //  already 0 to mitigate the race condition described here:
    //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
    require((_value == 0) || (allowed[msg.sender][_spender] == 0));

    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
    return true;
  }

  /**
   * @dev Function to check the amount of tokens that an owner allowed to a spender.
   * @param _owner address The address which owns the funds.
   * @param _spender address The address which will spend the funds.
   * @return A uint256 specifing the amount of tokens still avaible for the spender.
   */
  function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
    return allowed[_owner][_spender];
  }

}

There are, of course, additional protocols built on top of ERC20, for example, BDD (Board of Derivatives) protocol and so on.

Ownable

contract Ownable {
  address public owner;

  /**
   * @dev The Ownable constructor sets the original `owner` of the contract to the sender
   * account.
   */
  function Ownable() {
    owner = msg.sender;
  }

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }

  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param newOwner The address to transfer ownership to.
   */
  function transferOwnership(address newOwner) onlyOwner {
    if (newOwner != address(0)) {
      owner = newOwner;
    }
  }
}

This contract (and all contracts derived from it) stores the original owner's addres and allows you to limit access to some contracts functionality to owner only.

Oraclize

Oraclize is probably the most confusing of all possible "parents" - for as long as you realize that it has nothing to do with Oracle database. Instead it focuses on receiving data from other contracts.

In the blockchain, an oracle is a party which provides data. The problem of any contract is that it can not access just ANY data: time, random numbers, stock rates, weather... they are all unavailable. Instead of trusting a single source of data (what if it is compromised?) or multiple partially-trusted sources (it is slow, what if we need real time data feed?), Oraclize group came up with the "proof of autenticity".

We are not going into details, let's look at the interface instead. Here is a simple contract working with Forex data (credits to https://docs.oraclize.it/#diams--ethereum):

pragma solidity ^0.4.11;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract ExampleContract is usingOraclize {

    string public EURGBP;
    event updatedPrice(string price);
    event newOraclizeQuery(string description);

    function ExampleContract() payable {
        updatePrice();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        EURGBP = result;
        updatedPrice(result);
    }

    function updatePrice() payable {
        if (oraclize_getPrice("URL") > this.balance) {
            newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
        } else {
            newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
            oraclize_query("URL", "json(http://api.fixer.io/latest?symbols=USD,GBP).rates.GBP");
        }
    }
}

First, we create a contract, and immediately call the updatePrice() to get the initial data. Second, a callback is invoked. As you can see, the next query to Oraclize is called from within the callback. On one hand, it is good, as we have a contract working without interruptions. On the other hand, will it be wise to call for price update every moment we can, if, say, we need a DAILY chart of the Forex pair?

The next contract (the same source) fixes the problem, by calling for updates at a predefined intervals (60 seconds):

pragma solidity ^0.4.11;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract ExampleContract is usingOraclize {

    string public EURGBP;
    event updatedPrice(string price);
    event newOraclizeQuery(string description);

    function ExampleContract() payable {
        updatePrice();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        EURGBP = result;
        updatedPrice(result);
        updatePrice();
    }

    function updatePrice() payable {
        if (oraclize_getPrice("URL") > this.balance) {
            newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
        } else {
            newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
            oraclize_query(60, "URL", "json(http://api.fixer.io/latest?symbols=USD,GBP).rates.GBP");
        }
    }

To get more info about Oraclize interface, please refer to an exellent Tutorial.

As I mentioned more than once in this tutorial, Ethereum world is not very well organized, so if you want to find complete and up to date info on anything, including standard parent contracts, you will have to do a lot of research. In our case, looking through etherscan.io for "verified contracts" is probably the easiest way.







(C) snowcron.com, all rights reserved

Please read the disclaimer