Browsed by
Tag: solidity

Weekend workshop in NYC

Weekend workshop in NYC

The blockchain academy in NYC invited me to work with them on their teaching materials for developers, IT professionals and programmers. We also decided to take the opportunity to give few condensed workshops on smart contracts and Ethereum in NYC during the weekends.

The next (and probably last) one will take place on Oct 21-22 in Rise New York, 43 W 23rd St. Chelsea.

Here’s a video we’ve created after our previous session:

For more details:
https://www.theblockchainacademy.com/store/FBFKTG2t

Modifiers – Go With The Flow

Modifiers – Go With The Flow

What is a modifier

Modifiers are a neat feature in Solidity that allows us to change the flow of our code execution. The modifiers (as the name suggest) can modify the code of a function.

Look at the following contract:

contract A{
    
    uint public number;

    modifier zeroNum(){
        number = 0;
        _;
    }

    function plusNumber(uint _input){
        number = number + input;
    }  
}
In the code above, the modifier zeroNum is executed right before the rest of the function. It reset the number value back to zero. If it wasn’t for that modifier, the numbers would have just continue to add up.
Modifiers are mostly used as a gateways in our smart contracts:
contract B{

    address public owner = msg.sender;

    modifier onlyOwner(){
        assert(msg.sender == owner);
        _;
    }

    function register()onlyOwner(){
    //Do stuff
    }
}

In this example, only the owner of the smart contract can execute the rest of the function code.

Here’s another example in which the modifier that prevents anyone below the age of eight-teen to register:

contract C{

    address public owner = msg.sender;
    string public name;
    uint public age;

    modifier onlyOwner(){
        assert(msg.sender == owner);
        _;
    }

    modifier notMinors(uint _age){
        require(_age>18);
        _;
    }

    function register(string _name, uint _age)onlyOwner() notMiner(_age){
        name = _name;
        age = _age;
    }
}

The underscore.

Each modifier contains an underscore, this is where the rest of the code is inserted. The underscore can also be nested inside the modifier.
contract D{
    
    uint public input;
    uint public number;

    modifier onlyOwner(uint _input){
        assert(msg.sender == owner);
        input = _input + 1;
        _;
        input = _input + 2;
    }

    function doStuff(uint _input) onlyOwner(_input){
        number = input +1; //At the time of the code execution
    }
}

The difference between require and assert

Two powerful commands are assert and require. Both aren’t necessarily related to modifiers; in fact you can use these two in any function. However, they’re beneficial when trying to follow the execution flow of the code. Both will perform some logical test and will either allow the code to continue or throw the code. Throwing is the process by which the states of the EVM is reverted to the ones before the code execution. Also, currently throwing takes all of the gas associated with that transaction. In the future, the require command will refund the users of their unused gas and might even return some value.

Multiple modifiers

We can use more than one modifier in function. Modifiers will be loaded and nested according to their order.
function doStuff() modifierOne() modifierTwo() modifiersThree(){
    //TO DO
}

Predefined modifiers in Solidity:

 
public       - called by everyone
external     - Can only be called by external function (or by "this.functionName")
private      - can only be called by functions within the contract or from its derivatives 
internal     - Can only be called internally 

payable      - can accept Ethers
constant     - don't send transactions function is executed locally

Side note – The difference between require and assert

Two powerful commands are: assert and require. Both aren’t necessarily related to modifiers; in fact you can use these two in any function. However, they’re beneficial when trying to follow the execution flow of the code. Both will perform some logical test and will either allow the code to continue or throw the code. Throwing is the process by which the states of the EVM is reverted to the ones before the code execution. Also, currently throwing takes all of the gas associated with that transaction. In the future, the require command will refund the users of their unused gas and might even return some values.
For now there's no change (both throws). In the future:
require - revert but won't take all gas. It will refund the user and return a value
assert - like the old throw - revert changes and consume all gas
Ethereum developer Working environment

Ethereum developer Working environment

If you want to create smart contracts and dApps using Ethereum, you first must have a working environment. Here I’ll share with you my personal setup and why I choose to use it.

The big picture

Our working environment should contain three main components:

Local Machine

Keep it as light as possible

1.       Google Chrome (or Chromium for Linux users)

2.       MetaMask and/or Ethereum node of your choice

3.       Optional – SSH client and terminal

Digital Ocean Droplet

This is your real working environment. Where your code will run

System requirements:

·       Ubuntu 16.04 x64

·       1 CPU

·       1 GB RAM

·       1 GB SWAP

We’ll install:

·       NodeJS

·       NPM

·       truffle

·       testRpc

·       Optional – Chai

·       Optional – Meteor

C9 IDE/ SSH Terminal

 

Register to C9 IDE. We’ll only use it as a browser based terminal with SSH capacities.

 

This is how our working environment looks like:

Creating the Digital Ocean Droplet:

  1. Create your digital ocean account. Use the following link to get 10 USD voucher. Pay attention; the subscription is auto renewing. If by the end of the first month you don’t want to be charged again, you should manually change your billing settings.
  2. Once logged in press Create -> Droplets. Choose the one that has:
    1 CPU 64 bits
    1 GB RAM
    Ubuntu 16.04 X64
  1. Name your droplet and press the Create button
  2. After few minutes you should get an email with your Droplet IP address and root password.

Connecting to your Droplet using the c9.io terminal and SSH (Optional – can also be achieved using a locally installed SSH client and terminal):

  1. Create a free account at c9.io
  2. SSH into your droplet by typing ssh root@YourIPAddress
  3. When you first log into your droplet, you’ll be asked to change your root

Set your Digital Ocean Droplet:

Create SWAP file 1 GB of RAM isn’t enough.
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Add SUDO user Don’t always work as root!
adduser shlomi sudo
Change your user account
su shlomi
cd /home/sholmi
Install NodeJS and NPM This is the framework on which we’ll develop our app.
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo apt-get install -y build-essential
sudo apt-get install npm
Install Truffle and TestRPC
npm install -g truffle
npm install -g testrpc

The relation between Truffle and testRPC:

testRPC creates a mock Ethereum blockchain. It saves you a lot of time when testing your smart contract. Because you’re the owner of the blockchain, you can mine new blocks instantly. Usually, when using Ethereum, you’ll have to wait for new blocks to be mined whenever you check you smart contract and while block time is much faster in Ethereum than it’s in Bitcoin, it might still be very distracting to have a test case that contains more than 2-5 interaction with the blockchain.

Another great benefit of using testRPC is the fact that it immediately creates multiple accounts with balances so that you can test the use of your smart contract by multiple users.

TestRPC TIP:

When you first deploy testrpc you’ll be giving a mnemonic 12 words phrase. If you write this phrase down, you can later re-deploy your restRPC with the same accounts.

Working with truffle:

Create a working folder and initialize your truffle project
mkdir myProject
cd myProject
truffle init
Make sure testRPC runs in the background
testrc -m "tortoise fall alarm push dream proof
 broccoli size draft betray view gather"
Test your project
truffle migrate
truffle test

Tip for metamask and testRPC:

We can set metaMask to work with our own private testRPC node simply by adding it into our custom rpc list. Open metaMask and change to custom RPC. Then add
http://yourDropletIPAddress:8545  //You might need to open port 8545
And voila, Now metaMask is set to work with your own private blockchain!
Get your Bitcoin address using Ethereum smart contract

Get your Bitcoin address using Ethereum smart contract

Ethereum and Bitcoin are both using the same type of encryption, the ECC (Elliptic Curve Cryptography) over the same graph (256k1). While it’s not really recommended, the same key pair can be used both for Bitcoin and Ethereum.

A simple Solidity code can be used to get the Bitcoin address of a public key. Such a code can run locally (as a constant function) on the Ethereum Virtual Machine to save gas, or as a regular Ethereum transaction.

The code in this example requires the user to insert their public key in its uncompressed format as an input; then it produces the binary address that matches that uncompressed public key for the main Bitcoin network. The code can be easily modified to work with compressed public keys as well (just remove the yPoint and add the side of the ECC graph). The code can also be amended to give the binary address of other testnet/namecoin.

 

How to create a Bitcoin address

The most basic process of deriving Bitcoin address from a public key is set in the following technical documentation.

 As you can clearly see, there’s very little to it than just hashing and appending.

Recreating the process in Solidity

First, let’s generate a random keypair using bitaddress.org. Under the tab “wallet details” we can see the uncompressed public key.

The public key
xPoint = C4BB8E42F7DA5504A456C16BE533549DA4FE580279382478F3365FF7CCBF032D
yPoint = 68A73547E809F1ABFAA51D10019E8AC682D1205448042326E9E3B91841CB9FA7

Now let’s create our smart contract in Solidity:

pragma solidity ^0.4.11;

contract BitValid{
	
	bytes32 constant mask4 = 0xffffffff00000000000000000000000000000000000000000000000000000000;
	bytes1 constant network = 0x00;


	function getBitcoinAddress(
			bytes32 _xPoint,
			bytes32 _yPoint)
			constant
			returns(
				bytes20 hashedPubKey,
				bytes4 checkSum,
				bytes1 network)
	{
		hashedPubKey 	= getHashedPublicKey(_xPoint, _yPoint);
 		checkSum 	= getCheckSum(hashedPubKey);
 		network 	= network;
	}

	function getHashedPublicKey(
			bytes32 _xPoint,
			bytes32 _yPoint)
			constant
			returns(
				bytes20 hashedPubKey)
	{
		var startingByte = 0x04;
 		return ripemd160(sha256(startingByte, _xPoint, _yPoint));
	}

	function getCheckSum(
			bytes20 _hashedPubKey)
			constant
			returns(
				bytes4 checkSum)
	{
		var full = sha256((sha256(network, _hashedPubKey)));
		return bytes4(full&mask4);
	}
}

The function getBitocinAddress() takes the x and y coordinate of the public key from the user, both are 32 bytes long (the uncompressed public key) and will return 3 variables, the hashed public key (bytes20), the checksum (bytes4) and the network starting byte (bytes1).

The network starting byte is currently hard codded to 0x00 (the main starting code). You can change this code to work with any other test network.

The hashed public key is obtained by hashing the public key (both x and y coordinates) with the starting byte 0x04 twice (as described in the technical documentation). Once with sha256 and then again with ripemd160. The finale result is 20 bytes long.
function getHashedPublicKey(
		bytes32 _xPoint,
		bytes32 _yPoint)
		constant
		returns(
			bytes20 hashedPubKey)
{
	var startingByte = 0x04;
	return ripemd160(sha256(startingByte, _xPoint, _yPoint));
}
After we got the hashed public key, we’ll prepend the network byte to it and hash it again twice using the sha256 function. The result of 32 bytes long is used to construct the checksum, a special 4 bytes that are used to allow another user to verify that the Bitcoin address they’re sending to is indeed a valid address.
bytes32 constant mask4 = 0xffffffff00000000000000000000000000000000000000000000000000000000;

function getCheckSum(
		bytes20 _hashedPubKey)
		constant
		returns(
			bytes4 checkSum)
{
	var full = sha256((sha256(network, _hashedPubKey)));
	return bytes4(full&mask4);
}
We don’t need all of the 32 bytes, only the first 4 bytes, but slicing variables is a hard thing to do in Solidity. Luckily, Solidity does allow for easy bit manipulation and masking. You’ll need to create a mask of 32 bytes to match the 32 bytes of the sha256 output. This mask should take only the first 4 bytes, as they’re the real checksum.
The full result (32 bytes) = 0x4c30ed507a508af52063560ff8f1c09e66be0587868a0b8ca21ab337440e4e8e
Mask for the first 4 bytes = 0xffffffff00000000000000000000000000000000000000000000000000000000
checksum = 0x4c30ed50

The results

At the end of the day, we have the following three components to return to the user, the network byte (currently hard coded), the hashed public key and the checksum. These are the three components that make up a Bitcoin address.

However, this isn’t the last step. In Bitcoin, a special type of encoding is used called base58. The current code doesn’t convert the result into base58 (I’ll leave it for another day), so we’ll be forced to do this step manually.

The following website provides some tools to convert our bytecode into base58. This is basically the final Bitcoin address.

At the end of the day

Using Solidity to retrieve the Bitcoin address that matches a specific public key (and therefore, a private key as well) might be useful when you’re trying to create a smart contract that maps some events between entities on both blockchains and I suspect might have some value when dealing with identities. The procedure isn’t cheap on gas but can be done locally using the EVM. It’s a shame that there’s no access to the bytecode of the transactions in Solidity since it could have made the process of finding the Bitcoin address of the message sender automated.

Proof of data integrity – Solidity code

Proof of data integrity – Solidity code

Update:

I’ve simplified to code to take more advantage of the boolean data type Ethereum offers.

Now the mapping is (bytes32=>bool) instead of (bytes32=>bytes32).

The boolean array is used to prove the existence of a single document. The root of the tree is stored once and is hashed again with the new input.

The complete code can be found on Github. The old test files can be used on this code as well

struct tree{
    bytes32 root;
    mapping(bytes32=>bool) dataExist;
}

bytes32 public empty;

mapping (address=>tree) public users;    
****

function addData(
			uint256 _input,
			address _user)
			returns (bool success)
{
	var data   = keccak256(_input);        
	var oldRoot = getUserRoot(_user);
    var newRoot = hashTheTwo(data, oldRoot);

    users[_user].dataExist[data] = true;

    users[_user].root = newRoot;

    return true;
}
****

function checkDataIntegrity
        (uint256[] _data, 
        address _user)
        constant         
        returns (bool complete){ 

	var oldRoot = empty;                         
    
    for (uint i = 0; i < _data.length; i++) {     
        var data = keccak256(_data[i]);
        if(users[_user].dataExist[data]){
            var root = hashTheTwo(data, oldRoot);
            oldRoot = root;
            continue;             
        }else{
            return false;
        }
    }

    if(root == getUserRoot(_user)){
    	return true;
    }else{
    	return false;
    }
}
Contract: test 01
    The first stage is Deploying Data
      ✓ Deploys the Data contract
      ✓ Register account 0 user (69ms)
    Adds three datas to account 0 user tree
      ✓ get account 0 user root - should be undefined (79ms)
      ✓ Adds the first data 1 (108ms)
      ✓ Adds the second data 2 (86ms)
      ✓ Adds the third data 5 (79ms)
    Check data integrity
      ✓ Pass the complete array [1, 2, 5] - expect true (122ms)
      ✓ Pass the  array [1, 2] - expect false (93ms)
      ✓ Pass the  array [1, 5, 2] - expect false (83ms)


  9 passing (818ms)
    

Storing data on the blockchain

Current blockchain architecture allows us to decentralized valuable information. The most obvious example is the blockchain itself, which is nothing more than just a database that each user can interact with. The users can download a copy of the blockchain, parse it and extract any information that is meaningful to them, to add information to that database, to check its integrity and so on.

But adding information directly to the blockchain is a problematic process. For one, it’s highly expensive. Whether you’re using Bitcoin or Ethereum as the blockchain on which to store your data, you’ll soon find out that any attempt to save more than a few bytes of data at a time can get ridiculously expensive. For that reason, many have started to use the blockchain as a method to “proof existence” of said document. In this process, instead of publishing the full document on the blockchain, the document is hashed using a prespecified hashing algorithm. This practice means that the owner of the document uses the blockchain not as a mean to store his or hers document, but to prove:

  1. Ownership over the said document (As long as he keep the private key from which the transaction was deployed)
  2. The existence of the said document at a specific point in time (by looking at the block header timestamp)
  3. The integrity of that specific document, as each minor change to the original file, will result in an entirely different hash.

By keeping the document yourself, you’re also able to better handle your privacy, as now instead of publishing your own private documents on a public blockchain for all to see, you’re only posting the result of a hash function, which is extremely difficult to Didact the contains of the original document from.

Such a system might be sufficient for sporadic use. But what happens if we want to create a system that new documents are continuously added to it. And we want to be able to prove the integrity of each individual document, both by itself and in conjunction to those preceding it?

 

Binary trees.

Binary trees are not a new thing in blockchains. Merkle trees and roots are used in Bitcoin and Ethereum to store and organize transactions and to allow for merged mining. In Ethereum the trees are also used to access the storage (variables) and states of the blockchain.

One of the great characteristics of binary trees is the ability to use them, plus some hashing algorithm to prove the integrity of the data stored in it.

Let’s have a look at the most common example, the Bitcoin Merkle tree. In this tree, each leaf represents one transaction. These transactions are hashed together again and again until finally, the final hash (the root) is produced. Storing the root require much less space than when storing all of the transactions data. But if I want to check that a specific transaction is indeed a part of a specific block, I can reconstruct that said block Merkle root by myself. In this case, that means that instead of storing all of the transactions that took place in the blockchain, I maintain only copies of the transaction that is relevant to me (and usually it requires less than a half of the transactions in a block).

In Bitcoin this tree is used both to proof the integrity of the block and to make it easier to validate transaction without having a full copy of the blockchain

 

My proposal 

Knowing the advantages of binary trees, hashing, key encryptions, and filled with the motivation to create a user specific database that will allow him/her to maintain control over his/hers private information, while still being able to prove their ownership over the information and the integrity of that information, I decided to play a little with different Solidity codes. The idea was to use mapping as the mean of creating pairs of leaves and root.

 

Each leaf is hashed with the previous root to produce the new root of the tree

Each root is the hashed of all of the chain that lies bellow its level, plus the new leaf added. This way, each attached leaf if linked and chained with the rest.

pragma solidity ^0.4.6;

contract Data{
    
    struct tree{
        bytes32 root;
        mapping(bytes32=>bytes32) leafAndRoot;
    }

    bytes32 public empty;                                           // Hard codded         
    
    mapping (address=>tree) public users;
    
    function newUser(){                                             // To do - Modifer "onlyNewUser" 
        users[msg.sender];
    }
    
    function addData(
            uint256 _data,              // To do - serialize data/non empty
            address _user)
            returns (bool success){  
        
        var leaf    = keccak256(_data);   // Hashing the input
        var oldRoot = getUserRoot(_user);
        var newRoot = hashTheTwo(leaf, oldRoot);
        
        users[_user].leafAndRoot[leaf] = newRoot;
        users[_user].root = newRoot;

        return true;
    }
    
    function getRoot(
            uint256 _leafData,      // The input is in plain uint256 and hashed format to allow for future UI to be devloped
            address _user)
            constant 
            returns (bytes32 root){ // The root of specific leaf
        
        var leaf = keccak256(_leafData);                                            // Hashing the input
        return users[_user].leafAndRoot[leaf];
    }
    
    function getUserRoot(
                address _user)
                constant
                returns (bytes32 root){ // The higest (last) root      
        return users[_user].root;
    }

    function hashTheTwo
                (bytes32 _a, // To do - serialize data/non empty
                bytes32 _b)  // To do - serialize data/non empty
                constant
                returns (bytes32 hashed){         
        return keccak256(_a, _b);
    }
    
    function checkDataIntegrity
            (uint256[] _data, // To do - serialize data/non empty
            address _user)
            constant         // Run localy
            returns (bool complete){ 
         
         

        var oldRoot = empty;                         // Hard codded                        
        for (uint i = 0; i < _data.length; i++) {    // Reconstructing the tree     
            var data = keccak256(_data[i]);          // Hashing the input
            var root = hashTheTwo(data, oldRoot);
            
            if(root == getRoot(_data[i], _user)){         
                oldRoot = root;
                continue;
            }else{
                return false;
            }
        }        

        if (oldRoot == getUserRoot(_user)){
            return true;
        }else{
            return false;
        }
    }
}

For each new user, a new struct object is created containing two parts, The latest root in the tree, and the tree itself. The tree maps from bytes32 (the data/leaf) to the bytes32 of the root. That way a user can look up for a specific information and, if the root is valid, attest that the said information is indeed present in the database, while others cannot tell what the real information is just by looking at the blockchain.

Currently, due to input limitations in solidity, the easiest way to input and parse and the array is by using u/int array. Future implementation might include bytes32[] array or even direct string array as input.

All the input values are hashed to get a uniform 32 bytes result and to increase privacy.

function hashTheTwo(
        bytes32 _a,
        bytes32 _b)
        constant
        returns (bytes32){         // To do - serialize data/non empty
    return keccak256(_a, _b);
}

The data is then hashed together with the highest existing root to receive the new root of the tree (If the tree is empty, meaning no root exist yet, the first leaf is hashed with empty bytes32 variable).

The new root is then stored in a dedicated variable to allow adding extra information without manually looking for the latest existing root.

function addData
        (uint256 _data,
        address _user)
        returns (bool){                 // To do - serialize data/non empty
    
    var leaf    = keccak256(_data);     // Hashing the input
    var oldRoot = getUserRoot(_user);
    var newRoot = hashTheTwo(leaf, oldRoot);

    users[_user].leafAndRoot[leaf] = newRoot;
    users[_user].root = newRoot;

    return true;
}

When trying to prove the authenticity of a single entry, it’s enough to just check for the existence of a (none empty) root that corresponds to that specific piece of information.

function getRoot(
            uint256 _leafData,
            address _user)
            constant
            returns (bytes32){ // The root of specific leaf

    var leaf = keccak256(_leafData);                                            // Hashing the input
    return users[_user].leafAndRoot[leaf];
}

// Can also be rewtiren to give bool result

function isExist(
            uint256 _leafData,
            address _user)
            constant
            returns (bool exist){
            
    var leaf = keccak256(_leafData);                                            // Hashing the input
    if(getRoot(_leafData, _user) != 0x00){
        return true;
    }else{
        return false;
    }            
}

Proving the existence of the entire database is done by providing all the pieces in their proper order and reconstructing the finale root. If the results match the one stored on the blockchain, that means that the owner of that data array has a complete copy of that array.

function checkDataIntegrity(
            uint256[] _data,
            address _user)
            constant
            returns (bool){ 
     
     // To do - serialize data/non empty
     // Run localy

    var oldRoot = empty;    // Hard codded                        
    for (uint i = 0; i < _data.length; i++) {

        var data = keccak256(_data[i]);         // Hashing the input
        var root = hashTheTwo(data, oldRoot);

        if(root == getRoot(_data[i], _user)){   // Reconstructing the tree 
            oldRoot = root;
            continue;
        }else{
            return false;
        }
    }        

    if (oldRoot == getUserRoot(_user)){
        return true;
    }else{
        return false;
    }
}

The complete code plus test file can be found on my github page

Contract: test 01
    The first stage is Deploying Data
      ✓ Deploys the Data contract
      ✓ Register account 0 user (69ms)
    Adds three datas to account 0 user tree
      ✓ get account 0 user root - should be undefined (79ms)
      ✓ Adds the first data 1 (108ms)
      ✓ Adds the second data 2 (86ms)
      ✓ Adds the third data 5 (79ms)
    Check data integrity
      ✓ Pass the complete array [1, 2, 5] - expect true (122ms)
      ✓ Pass the  array [1, 2] - expect false (93ms)
      ✓ Pass the  array [1, 5, 2] - expect false (83ms)


  9 passing (818ms)
    

What can I do with it?

I can use the above system to prove that I’m in control over my own data, that I have the original data and that I maintain a complete copy of my database. Such a system can be combined with other types of encryptions to prove that the data is both belongs to me, complete, and recognized by other authorities.

I prove that I have a my complete medical file, I prove that the said message belongs to me and that it was signed by myself and by the doctor
ICO – Simple. Too simple.

ICO – Simple. Too simple.

important notice, please read!

This post blog is for educational purposes only. Solidity and Ethereum are bleeding edge technologies and should be treated with respect. Make sure to properly educate yourself before attempting to implement any code you might find online. I can attest that the code provided here is without a doubt not secure. It’s (at the very least) susceptible to overflow attacks, short address attacks and transferFrom double spend attacks. This is actually a very good example to my point because, while being open to such attacks, my code does adhere to the ERC20 standard. Use this code to get yourself familiarized with the basics, and then keep on learning.

 

All that glitters is gold.

As of April 2017, there’re 161 ICOs listed on TokenMarket, one of the leading token platforms. Of these 161 ICOs, 118 were still active. Almost every new company in the blockchain ecosystem choose ICO as its main source of fund raising.

Offering shares in the form of coins is a great way for raising funds and for potential investors to invest in many of the new and exiting new projects out there. But here’s something most don’t know: Most ICOs are nothing more than copy-past of the same code that was used in a dozen of previous ICOs – AND RIGHTFULLY SO.

The reason the same code is used again and again (with moderate variations) lies at the fact that this code was developed and tested by professionals, and it provides many useful features both to the creators of 3rd party apps (like wallets and exchanges) but also to the end users, who can be somewhat assured that the tokens they’ve just bought can be used and exchanged with relative ease.

 

So what’s the problem?

It seems as if many of these companies also promise (or at least gives the vague impression) that the coins that they’re offering represents a substantial part of the final product. “Buy PizzaCoin at only 57 PZC per 1 ETH and you’ll be able to use these 57 PZC in our PizzApp store.” This promise alludes to the fact that such smart contracts/apps are already developed (or at the very least are in a finale stage of development). Which is usually not the case. While I can understand those who buys tokens in the hope that in the future they might be worth more on the market (speculates) I also believe that a substantial part of the investors in ICOs hope to utilize these coins in their respective apps. They just don’t know how generic the coin really is.

Also, many of these generic contracts sometimes issue coins in a rate that has very little economic reason behind it (what does it mean to get 57PZC? Is that mean that each coin will be equal one pizza in the future? Will the price of future pizza will be determinate in a coin exchange? How do you calculate the cost of operating and maintaining a smart contract that doesn’t exist yet?).

I have absolutely no doubt that many companies actually using the raised funds in a responsible manner. They’re working hard to deliver a real final product, and I’m sure that there’re also many investors who understand that these ICOs tokens are usually nothing more than a financial assets (at least at this early stage) and the fact that they’re issued using a generic contract is not a surprise to them, but there are many others who don’t. And for them, I dedicate this post.

I hope you’ll find it useful.

ERC20 Tokens

 

Step one – Secure operators

Ethereum Virtual Machine (EVM) is susceptible to overflows and memory offsets. Fortunately, that can be solved quite easily by implementing some simple function to perform basic operations. Zeppelin team provided us with the SafeMath contract that provides us with the functions safeAdd, safeMul, safeDiv, safeSub and assert (The other functions are not relevant for this tutorial). Using the assert function, the SafeMath functions results are checked to make sure that they adhere to what is expected of them. For example: The function safeAdd receives two unsigned integers (a, b) and sum them together to get the result c. While both a and b are uint (not negative numbers) there’s still a chance that due to an overflow, the final result c will be lower than the sum of its components. That’s why the SafeMath function also checks to make sure that c is indeed larger then a.

 

Step two – ERC20 functions signatures

In late 2015 Fabian Vogelsteller, one of the mist wallet developers, suggested the creation of a unified token template called ERC20. The idea was that by providing a unified architecture for tokens – wallets creators, exchanges, and other service providers could produce a product that will support these token right out of the box, without having the need to recreate a unique wallet for each new token that is issued over the Ethereum protocol. It was suggested that the following functions will become the standard for every new token contract.

function totalSupply() constant returns (uint256 totalSupply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _recipient, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _recipient, 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 _recipient, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);

 

While this standard isn’t fully accepted (and enforced), many token developers adhere to it as it provides them with many benefits, especially regarding interacting with other Ethereum services.

The functions signature suppose to match the basic functionality that is expected from every token smart contract.

  • function totalSupply: Display the total supply of your tokens.
  • function balanceOf: Display the amount of tokens each account has.
  • function transfer: Send value (amount of tokens) to address (recipient). The sender address is usually msg.sender.
  • function approve: Give permission to another account to trade tokens on your behalf. Used mostly when splitting your tokens to multiple wallet accounts and/or exchanges.
  • function transferFrom: Just like transfer, only in this case the user needs to specify the sender address as well.
  • function allowance: Display the amount of tokens that can be spent on behalf of the token owner by each approved address
  • event Transfer: Indexing all transactions by sender and recipient, also specify the transferred amount of tokens.
  • event Approval: Indexed all approved accounts by owner and spender account address, also specify the amount of tokens the sub spender can spend.

 

Step three – write your functions

Simple and straight forward. We need to start to populate our functions. Pay attention that these functions need to match the function signatures mentioned above.

mapping(address => uint256) balances;

uint256 public totalSupply;

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

function transfer(address _to, uint256 _value) returns (bool success){
    balances[msg.sender] = safeSub(balances[msg.sender], _value);
    balances[_to] = safeAdd(balances[_to], _value);
    Transfer(msg.sender, _to, _value);
}

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

function transferFrom(address _from, address _to, uint256 _value) {
    var _allowance = allowed[_from][msg.sender];
    
    balances[_to] = safeAdd(balances[_to], _value);
    balances[_from] = safeSub(balances[_from], _value);
    allowed[_from][msg.sender] = safeSub(_allowance, _value);
    Transfer(_from, _to, _value);
}

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

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

The totalSupply function was replaced by a simple uint public totalSupply.

 

Step four – Finalizing the token

Add the following parameters to your token contract:

string public name = "ShlomiCoin";
string public symbol = "SCO";
uint public decimals = 3;
uint256 public INITIAL_SUPPLY = 10000;
uint256 totalSupply;

Insert the token constructor function:

function ShlomiCoin() {
  totalSupply = INITIAL_SUPPLY;
  balances[msg.sender] = INITIAL_SUPPLY;  // Give all of the initial tokens to the contract deployer.
}

And finally mash it all together to get your token contract. (Full code on Github).

 

Make sure your token works correctly

Check your contract by opening your mist wallet, or go to wallet.ethereu.org (Web interface for your ethereum node). Under CONTRACTS you should see TOKENS. Just press WATCH TOKEN and insert your token address into the popup window. You should now see that you’re indeed the proud owner of 10,000 Shlomi coins.

Pay attention, this is a standard ERC20 token, but it’s not supporting crowd-selling yet. However, making sure that your token is working and is on per with the latest standard is a significant step on the way to create a stable ICO.

Add the token address to your “watched tokens” list

 

Under the Send tab, you can access your tokens and send them almost as if they were regular ethers

 

 

Get yourself a cup of coffee and get ready to offer your contract to the public.

 

The offering

Now that we know that we have a smart contract that works and is on per with modern standards, it’s time to offer it to the public.

This step is slightly less rigid than the previous one as there’re many ways and parameters in which one ICO is different from the other. Some might place a cap on the sale; some might have a time limit on the coin offering or have a different price for each step of the sell, some might send the etheres directly to the company issuing the ICO while others might split the ethers or freeze them or even destroy them. Sometimes the buyer might get the token immediately and sometimes only after a certain time passed – You get the picture. While ERC20 attempts to provide a uniform token standard, ICOs are the wild west.

But for this example, I decided to create an ICO which:

  1. Have uniform price throughout the sell.
  2. Stays open for exactly one week since being deployed.
  3. Immediately issue the tokens to the buyers.
  4. Sends the etheres to the owner (deployer) of the ICO contract (only one address).

 

Step one – Creating tokens function

A simple createTokens function will:

  1. Make sure that the transaction value isn’t empty (the buyer added ethers to the transaction).
  2. Calculate the amounts of tokens to be issued (price * amount).
  3. Update the new totalSupply variable with the new amount that was recently created.
  4. Adds the new tokens into the buyer (msg.sender) balance.
  5. Send the ethers to the owner of the ICO contract.

 

function () payable {
	createTokens(msg.sender);
}

function createTokens(address recipient) payable {
	if (msg.value == 0) {
	  throw;
	}

	uint tokens = safeDiv(safeMul(msg.value, price), 1 ether);
	totalSupply = safeAdd(totalSupply, tokens);

	balances[recipient] = safeAdd(balances[recipient], tokens);

	if (!owner.send(msg.value)) {
	  throw;
	}
}

This function will be called automatically when ever someone sends money to the ICO contract by using the fallback function (function ()).

 

Step two – Create a modifier to prevents buyers from sending ethers after the offering period ended.

uint256 public endTime;

modifier during_offering_time(){
	if (now >= endTime){
		throw;
	}else{
		_;
	}
}

 

Step three – add time limit, owner address and price to your token constructor

function ShlomiICO() {
	totalSupply = INITIAL_SUPPLY;
	balances[msg.sender] = INITIAL_SUPPLY;  // Give all of the initial tokens to the contract deployer.
	endTime = now + 1 weeks;
	owner = msg.sender;
}

And finally mash it all together to get your token contract. (Full code on Github).

You can now launch your ICO token and interact with it using mist (or any other compatible wallet). This token will work just like any other ERC20 token with one exception if during the time of offering someone will send it one ether, which senders will receive 500 tokens into their account, while the owner of the ICO contract will get that one ether into his/hers ether account.

 

Simple too simple.

Two points that I want to emphasis here, the first one is that this code is extra simplistic. There’re many more features, security mechanism, distributions schemes and functionalities that can be incorporated into both ERC20 contracts and ICOs. I don’t want to disparage anyone who issues tokens and offers them to the public. This is indeed hard work that requires a lot of research, careful planing and high level of expertise. IT REALLY ISN’T MEANT FOR ANYONE!

However, the code presented here is the real thing, it’s not the best example, but that’s the scaffolding on which most ICOs are based upon. Usually, there’s no actual mechanism that will incorporate these coins into a working application/smart contract – at least not at the time of ICO.

Ethereum dApp front end. Display variables.

Ethereum dApp front end. Display variables.

Catching up

Few weeks ago I created a video tutorial describing the basics of creating Ethereum decentralized application (dApp). I created the app in the tutorial by using meteor, web3.js add-on for meteor and metamask. The video can be found here:

Now it’s time to expend on the previous video and see other ways to extracts more advanced information out of the blockchain.

The smart contract

For this example I’ve created a simple Ethereum smart contact. This smart contract contains one public string variable called name and one function called changeName:

contract demo{
    
    string public name = "Shlomi";
    
    function changeName(string _newName){
        name = _newName;
    }
}

I’ve transmitted this contract to the Modern test-net using metamask, and the contract can now be found under the address: 0x53a95ce8fcdd9080ba7c26711207e45382ae4180

Solidity creates get_variable functions for public variables!

A nice feature in Solidity is the ability to call public variables as if they are functions. The result of the function call can then be transferred to another callback function, e.g:

myContract.name(function(err, res){
  alert(res)
})

This is highly useful when dealing with web development as it allows for an easy way to interact with light clients (such as metamask) and helps to provide a better user experience (We can, for example define more user friendly error messages in case we can’t properly interact with the blockchain). In our code, once the “function” name is called, the web3 object myContract will look for a variable called name that is stored at the blockchain at address 0x53a9... Then the result (In this case, my name Shlomi) will be passed to the anonymous callback function and then presented in a pop-up window.

And this is how you set the web3 object

(In the previous video I explained how to install meteor with the Ethereum web3 package)

In order to interact with smart contract we usually need 3 parameters.

  1. The address of the smart contract we want to interact with. You can get the address for your own contract by scanning the blockchain for your own Ethereum address and the list of transactions associated with it.
  2. The Interface or ABIarray. I usually prefer to refer to this parameter simply as ABI, so from here on it will be simply called ABI.

    In the web3 documentation it's called ABIarray. In the the solidiy web compiler it's called Interface.
    In the web3 documentation it’s called ABIarray. In the the solidiy web compiler it’s called Interface.
  3. The bytecode or data. I prefer to refer to this parameter as Data. So from here on it will be simply called Data.

 

The ABI and Data are usually provided by the compiler you’re working with. (I’m using solidity-browser It’s a great tool for beginners!)
Now we can declare the web3 object myContract. Using two of the three parameters: The contract address and the contract ABI (The data will be used later).

contractAddress = "0x53a95ce8fcdd9080ba7c26711207e45382ae4180"

ABI = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_newName","type":"string"}],"name":"changeName","outputs":[],"payable":false,"type":"function"}]

Frozeman:template-var. Easy way to display variables from callback functions.

This part actually has nothing to do with Ethereum, but because we’re going to use many (many) callback functions, it’s always nice to have an easy way to display the result in a more html friendly manner. Template-var gives us the option to set variables directly from within the callback function.

First we need to add it to our meteor project. The package can be found here.

Now what we need to do is to initialize the template object. In our helpers methods we’ll add the following code:

var template = Template.instance();

Once our template was declared, we can simply use it in our callback function.

Template.hello.helpers({
  counter() {
    var template = Template.instance();

    myContract = web3.eth.contract(ABIArray).at(contractAddress);

    myContract.name(function(err, res){
      TemplateVar.set(template, "name", res);
    })
  },
});

The first argument is the template that we’ve just declared. The second is the name of the variable, and the third is the value that we want the argument to have. In our case it’s the result of the name “function”.

One last step

In our html file, we need to call to our templateVar instance by inserting:

 
The string stored at the "name" variable is: {{counter}} {{TemplateVar.get "name"}}.

Now whenever we’ll load our app, the variable name will incorporated in our project as if it was part of the original html file.