Getting started with smart contracts on EOSIO

Overview of smart contract development

Getting started with smart contracts on EOSIO

Clone eosio from : https://github.com/EOSIO/eos with –recursive flag

Buid eosio: EOSIO community give an automated build script for select environments

1. Amazon 2017.09 and higher
2. Centos 7
3. Fedora 25 and higher (Fedora 27 recommended)
4. Mint 18
5. Ubuntu 16.04 (Ubuntu 16.10 recommended)
6. Ubuntu 18.04
7. MacOS Darwin 10.12 and higher (MacOS 10.13.x recommended)

Image for a successful build using eosio-build.sh..

EOSIO

Smart contracts for EOSIO are coded in c++, Usually (for most of the smart contracts) you have to specify a header file with the declaration of functions(that correspond to smart contract actions) and a .cpp source file with their definitions. A .abi file (Application Binary Interface) is also created that holds all the actions that the Smart contract has. This file is needed by external systems for executing the smart contract operations.

EOSIOCPP

EOSIO provide a compilation tool called, eosiocpp and recommend it be used for the compilation of the smart contracts.

EOSIO ships with its standard c++ libraries, i.e When you clone the source, you will notice that a folder: {$PROJECT_ROOT}/contracts/libc++ ⇒ This directory has all the standard c++ library headers and this is where eosiocpp looks for the included standard header files.

EOSIO-1

A detour to .wasm

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications. It is meant to enable executing code nearly as fast as running native machine code. It was envisioned to complement JavaScript to speed up performance-critical parts of web applications and later on to enable web development in languages other than JavaScript.WebAssembly does not attempt to replace JavaScript, but to complement it.[4] It is developed at the World Wide Web Consortium (W3C) with engineers from Mozilla, Microsoft, Google and Apple.

More on wasm can be found here: https://webassembly.org/

Smart contract overview

Smart contracts are self-executing contracts with the terms of the agreement between buyer and seller being directly written into lines of code. The code and the agreements contained therein exist across a distributed, decentralized blockchain network. Smart contracts permit trusted transactions and agreements to be carried out among disparate, anonymous parties without the need for a central authority, legal system, or external enforcement mechanism. They render transactions traceable, transparent, and irreversible.

Before we jump on the deploying our escrow smart contract, there are a couple of preliminary things that are needed to be carried on. The official documentation page for EOSIO has this in a very clear and precise manner: https://developers.eos.io/eosio-cpp/docs/introduction-to-smart-contracts

Assuming that you were able to execute the steps mentioned in the above link, let’s proceed further with our smart contract under discussion.

ESCROW SMART CONTRACT

@breif: An escrow is basically a buffer where the token(currency) involved in the transaction is temporarily held until we know that the transaction can be completed without dispute. The operation under focus for this article is estransfer ( i.e escrow transfer); which is the operation used to transfer the fund from the sender to the escrow. This operation is complemented by esrelease which releases the funds from the escrow to the recipient.

First, define the class for your smart contract in the header file.


All the member functions corresponding to the actions, should be made public and they should be declared in the .abi file of the smart contracts.

Since our escrow smart contracts also issues the tokens needed for transactions it needs to have a table to store the data corresponding to the issued token and the balance for any account of that token. This is done using the multi_index container as provided by the EOSIO library (which is modelled after boost::multi_index_container) as follows:

Tables:

The two tables defined are accounts and stat. The accounts table is made up of different account objects each holding the balance for a different token. The stat table is made up of currency_stats objects (defined by struct currency_stats) that holds a supply, a max_supply, and an issuer. Before continuing on, it is important to know that this contract will hold data into two different scopes. The accounts table is scoped to an EOSIO account, and the stat table is scoped to a token symbol name.

According to the ‘eosio::multi_index’ definitions, code is the name of the account which has write permission and the scope is the account where the data gets stored.

The scope is essentially a way to compartmentalize data in a contract so that it is only accessible within a defined space. In the token contract, each EOSIO account is used as the scope of the accounts table. The accounts table is a multi-index container which holds multiple account objects. Each account object is indexed by its token symbol and contains the token balance. When you query a users’ accounts table using their scope, a list of all the tokens that user has an existing balance for is returned.

This is our smart contract’s header file.

.cpp implementation

The actions are implemented in the .cpp source file

The definition of our estransfer action starts off with some assertion checks:

First, assert checks if the sender and receiver accounts are not same, then we check that the transaction has an authority of the sender, authority for a transaction can be specified by using -p <account_name> flag with cleos.

 Next, we fetch the table corresponding to the current token.

These lines notify the specified accounts after a successful transaction

This is followed by some more checks

Finally, we call the two most important utility functions, add_balance, and sub_balance, the former adds the tokens to a specified account and the later deducts it.
https://gist.github.com/akhiltiwari-tr/15aa69e85246a835ff4c757f6ee97a92

Let’s look at sub_balance in a little more detail:

First, we fetch the table of accounts objects, the account being that of the sender in estransfer. This is followed by a few checks, if all the checks pass, modify the account’s balance by subtracting the value to be transferred and if the number of tokens to be transferred are equal to the total available tokens in the accounts we essentially delete the entry for the sender account from the accounts table.

Here is our escrow.cpp file in entirety.

This is the structure of the ABI file that documents the actions of the smart contract.

Here is the escrow.abi file:

Working with our escrow smart contract using cleos (command line utility as provided by EOSIO)

First, we need to set the contract and create a token

EOSIO

Second, we can check at the moment if any account has some token balance for the token we just created, the result should not surprise you.

EOSIO 4

Once the escrow smart contract is set and the token balance has been created, we can push the action for issuing this token to some user “ned”

EOSIO-5

Now, when we check the account for “ned” we can see the token balance for this account

blog-6

Now, we are in a situation to transfer funds from “ned” to “jon” (R+L=J)

EOSIO-7

We have used the account “escrow” with which we had deployed the smart contract as our Escrow for this transaction.

Then, we can check the balance for “escrow”

EOSIO-8

This is the final table structure after pushing the release action.

Eosio-9

 

REFERENCES:

One stop developer’s doc: https://developers.eos.io/

Great resource for understanding token contract: https://medium.com/coinmonks/understanding-the-eosio-token-contract-87466b9fdca9

Resource for pushing actions using eosjs lib: https://steemit.com/devs/@eos-asia/eos-smart-contracts-part-1-getting-started-ping-equivalent-in-eos

 

 

 

 

 

How to write your first smart contract in solidity

The problem with learning to code on ethereum smart contracts is to know where to start from. After just learning about blockchains and ethereum, you try to google, in the hopes of getting started but you are stymied looking at dozen possible options with complicated stuff you don’t understand. You wanted to make a Dapp that would eventually go on a blockchain, but can’t even begin to begin.

Well, there is a good news. Creating a smart contract doesn’t have to be that daunting. With just a basic understanding of any object oriented language (C++, C, java, etc), the right tools and set-up at your disposal, you could easily create simple to complex smart contracts and test them out in little to no time- without needing to get into the pain of knowing how to deploy the contracts (though you will eventually need to know about the Dapp frameworks and tools)

Follow this link (https://remix.ethereum.org/) to browser-solidity to kickstart your journey to coding smart contracts.  All the codes will be written in solidity in this tutorial. Browser-solidity is mostly used for debugging code but it is more than enough to get a start. We assume you have basic understanding of blockchains and how they work. In this demonstration :-

  1. You will learn how to use browser-solidity.
  1. And how to write a simple token sale contract and call its methods.

When we’re done you’ll know exactly how to write some deep looking smart contract code, ready to dive into the complicated task of actually deploying the contract to a live blockchain.

  1. Getting started with browser-solidity

After you click on the browser solidity link (make sure you use that link), you will find a default smart contract named ‘ballot.sol’ (don’t worry if you don’t) in an interface as shown below.

 

The panel on the right has a few options that you should know about in order to call the contract functions properly:-

    1. The Contract Tab is where the transactions take place. You can select the development environment, the accounts and the gas limit and value.
      1. The environment tab allows you to select between running the contract on a web3 provider , injected Web3 and javascript VM. A web3 provider connects to an actual node or a localhost. The injected Web3 uses the environment provided by mist. We will use javascript VM where everything is local and in memory of browser-solidity.
      2. You can select the user accounts available, according to your environment in the accounts list. Selecting an account from the list is equivalent to ‘logging into’ the account. Transactions will take place from the account thereon. The addresses can be copied by using the button adjacent to the dropdown.
      3. Gas limit sets the maximum gas allowed for each transaction.
      4. Value corresponds to msg.value, or the ethers, the default cryptocurrency used in the ethereum blockchain, that will be transferred with each payable function. The default currency we will use here is Wei. Make sure that the amount you enter in the value box trails by the tag ‘wei’. For ex-: ‘10 wei’.

 

  1. The settings tab deals with compiler related options. You don’t need to deal with it, unless you want to change the compiler version or if you need to compile the code (when auto compile is switched off)
  2. Under the files tab you have option to publish all your files to a public github gist or to copy it to another browser-solidity instance.
  3. The debugger will allow you to run the code line by line in case you get stuck somewhere with your smart contract. It will become a very powerful tool when you start writing your own smart contracts.

Our first job would be to start the javascript VM which allows us to simulate a blockchain inside the browser-solidity interface.

Under the contract tab, in the environment drop down list, select javascript VM.

When you are done you will be able to see  5 accounts in the accounts drop down list below having ample amount of ethers each (don’t worry if all of them don’t). You will be needing them in order to access the smart contracts.

To add or open contracts, you can access the panel on the left.

The third icon from the left in this panel connects you to a localhost. It will allow you to synchronise the changes that you make in browser solidity to your local files. You can find the steps to set it up by clicking on it.

  1. A Simple Token Sale Contract

You won’t be needing the Ballot.sol smart contract which you find in browser-solidity by default. Delete it and add a new file (by double clicking Ballot.sol in the left panel) naming it TokenSale.sol.

A token sale can be thought to be similar to an IPO (Initial public offering), where the token contract is owned by an XYZ company and anyone can buy tokens/shares. In simple words, this will be a smart contract where users can buy shares of that company. This tutorial will cover just the basics, i.e buying of the tokens, without complicating the code.

We are now ready to start writing the contract.

A contract resembles a class which has a few methods.. We have 3 methods here, to buy tokens, to check the token balance and to check the ether balance. This will look pretty simple for someone acquainted with any OOP language.

Make sure you understand the code line for line before copying it, to make future implementations easier.

You can find below the code for a very simple Token Sale contract with inline comments explaining each line:

Other little points to note in the code-

  1. msg.value points to the ‘value’ in Contract tab dialog box. That is, when you call the function, msg.value will be equal to the amount you have entered in the ‘value’ dialog box.
  2. msg.sender is the account you have selected from the drop down list.

After you paste this code into the solidity interface, it will automatically compile it. If that doesn’t happen, go to the settings tab and click on compile. Hopefully now, post the compilation, there will be some ethers in each of the
5 accounts. That should do it for you.

Go back to the ‘Contract’ tab.

First, you will have to create the contract using the create button. This will fire up the contract, displaying all the public variables and functions

When the contract is created, you would be able to see a launch debugger and copy address option,  along with the simulated ‘transaction’ and ‘execution’ gas costs. We will go through them one by one :-

  1. The launch debugger opens up the debugger tab allowing you to understand the flow of the code. It becomes easy to identify errors when you face one.
  1. The copy address button sounds self explanatory. It will copy the address of the voting smart contract. Useful for sending ether to the contract, etc. In this case, you will copy the address of the contract to check the ether balance using the checkBalance function after tokens have been bought.
  1. Transaction costs are the costs for sending the contract code to the ethereum blockchain depending on the size of the contract.
  1. Execution costs cover the costs for storing global variables and the runtime of the method calls.

Now, you will also be able to view the public variables and external functions that were created with the contract.
The legend under the ‘value’ dialog box in the right panel shows you what each colour denotes.
The ‘payable’ tag that we added to the buyTokens function makes our function a ‘Transact (payable)’ type function.

Lets start to call the functions.

  1. Select any of the addresses from the dropdown list to make them the transacting account to start buying tokens.
  1. After selecting the address, enter the amount you want to spend to buy tokens in the ‘value’ dialog box. 1 wei fetches you 10 tokens (set by the tokenSwap variable). Write the respective value in wei (for ex:- 10 wei) in the value dialog box. Make sure you write ‘Wei’ after the amount. And make sure the amount is lesser than or equal to 1000 wei.
  1. Now call the function by simply clicking on the buyTokens function.

You will be able to see the transaction and execution costs associated.

Subsequently, you can check if tokens have been deposited to the account by simply copying the address with which you bought the tokens and passing it (“with double quotes”) in the balanceOf function.

The working of the modifier can also be checked by putting a value of over ‘1000 wei’ and you can see it shoots an error. Launch the debugger to see that the code flow gets stuck at the modifier.

You can also check if your contract has received the money (from other accounts buying tokens) in a similar manner by copying the tokenSale contract address (created during initially firing up of the contract) and using the checkbalance function, pretty straigtforward now.

And there it is, if you have been able to call the above methods, you have made a simple smart contract and studied its functionalities in a matter of minutes.

In further posts, we will demonstrate how to make more complicated contracts that will be deployed to a local blockchain, also making the frontend to invoke the functions. We hope this post helped you in getting a very rudimentary understanding of how smart contracts are created, along with some basic solidity functionalities.

You can now change gears and have a further look at the solidity documentation here (http://solidity.readthedocs.io/en/latest/) and have a deeper read on ethereum by using this link (https://github.com/ethereum/wiki/wiki/White-Paper).