EOSIO Smart Contracts Tutorial

Blockgenic
Coinmonks
8 min readApr 29, 2018

--

0. Required Background Knowledge

  • C / C++ Experience
  • Linux / Mac OS Experience
  • Command Line Knowledge

1. Basics of EOSIO Smart Contract

1.1. Communication Model

EOSIO Smart Contracts communicate with each other in the form of actions and shared memory database access. There are two communication modes that can be defined within a contract:

  • Inline. Inline is guaranteed to execute with the current transaction or unwind; no notification will be communicated regardless of success or failure. Inline operates with the same scopes and authorities the original transaction had.
  • Deferred. Defer will get scheduled later at producer’s discretion; it’s possible to communicate the result of the communication or can simply timeout. Deferred can reach out to different scopes and carry the authority of the contract that sends them.

Discover and review best Blockchain softwares

1.2. Action vs Transaction

A action represents a single operation, whereas a transaction is a collection of one or more actions. A contract and an account communicate in the form of actions. Actions can be sent individually, or in combined form if they are intended to be executed as a whole.

1.3. Transaction Confirmation

Receiving a transaction hash does not mean that the transaction has been confirmed, it only means that the node accepted it without error, which also means that there is a high probability other producers will accept it.

By means of confirmation, you should see the transaction in the transaction history with the block number of which it is included.

2. Starting a Private Blockchain

You can start your own single-node blockchain with this single command:

Assuming everything worked properly, you should see a block generation message every 0.5 seconds.

This means your local blockchain is live, producing blocks, and ready to be used.

3. Creating a Wallet

A wallet is a repository of private keys necessary to authorize actions on the blockchain. These keys are stored on disk encrypted using a password generated for you. This password should be stored in a secure password manager.

For the purpose of this simple development environment, your wallet is being managed by your local nodeos via the eosio::wallet_api_plugin we enabled when we started nodeos. Any time you restart nodeos you will have to unlock your wallet before you can use the keys within.

It is generally not secure to use your password directly on the commandline where it gets logged to your bash history, so you can also unlock in interactive mode:

For security purposes it is generally best to leave your wallet locked when you are not using it. To lock your wallet without shutting down nodeos you can do:

You will need your wallet unlocked for the rest of this tutorial.

Import the master key for the eosio account into your wallet. The master key can be found in the config.ini file in the config folder for nodeos. In this example, the default config folder is used. On MacOS, this will be in ~/Library/Application Support/eosio/nodeos/config.

4. Loading the Bios Contract

The Bios contract enables you to have direct control over the resource allocation of other accounts and to access other privileged API calls. In a public blockchain, this contract will manage the staking and unstaking of tokens to reserve bandwidth for CPU and network activity, and memory for contracts.

The code defines how the contract runs and the abi describes how to convert between binary and json representations of the arguments. The result of this command sequence is that cleos generated a transaction with two actions, eosio::setcode and eosio::setabi. It can be read as: The action setcode as defined by eosio was executed by eosiocontract with {args...}

The last argument to this call was -p eosio. This tells cleos to sign this action with the active authority of the eosio account, i.e., to sign the action using the private key for the eosioaccount that we imported earlier.

5. Creating Accounts

Now that we have setup the basic system contract, we can start to create our own accounts. We will create two accounts, user and tester, and we will need to associate a key with each account. In this example, the same key will be used for both accounts.

To do this we first generate a key for the accounts.

Then we import this key into our wallet:

5.1. Create Two User Accounts

Next we will create two accounts, user and tester, using the key we created and imported above. The create account subcommand requires two keys, one for the OwnerKey (which in a production environment should be kept highly secure) and one for the ActiveKey.

We can query all accounts that are controlled by our key:

6. Deploy Token Contract

The eosio.token contract enables the creation of many different tokens all running on the same contract but potentially managed by different users. Before we can deploy the token contract we must create an account to deploy it to.

Then we can deploy the contract which can be found in ${EOSIO_SOURCE}/build/contracts/eosio.token

6.1. Create the EOS Token

You can view the interface to eosio.token as defined by contracts/eosio.token/eosio.token.hpp

To create a new token we must call the create(...) action with the proper arguments. This command will use the symbol of the maximum supply to uniquely identify this token from other tokens. The issuer will be the one with authority to call issue and or perform other actions such as freezing, recalling, and whitelisting of owners.

The concise way to call this method, using positional arguments:

Alternatively, a more verbose way to call this method, using named arguments:

This command created a new token EOS with a pecision of 4 decimials and a maximum supply of 1000000000.0000 EOS.

6.2. Issue Tokens to Account “User”

Now that we have created the token, the issuer can issue new tokens to the account user we created earlier.

This time the output contains several different actions: one issue and three transfers. While the only action we signed was issue, the issue action performed an "inline transfer" and the "inline transfer" notified the sender and receiver accounts. The output indicates all of the action handlers that were called, the order they were called in, and whether or not any output was generated by the action.

Technically, the eosio.token contract could have skipped the inline transfer and opted to just modify the balances directly. However, in this case, the eosio.token contract is following our token convention that requires that all account balances be derivable by the sum of the transfer actions that reference them. It also requires that the sender and receiver of funds be notified so they can automate handling deposits and withdrawals.

If you want to see the actual transaction that was broadcast, you can use the -d -j options to indicate "don't broadcast" and "return transaction as json".

6.3. Transfer Tokens to Account “Tester”

Now that account user has tokens, we will transfer some to account tester. We indicate that user authorized this action using the permission argument -p user.

7. Deploy Exchange Contract

Similar to the examples shown above, we can deploy the exchange contract. The exchangecontract provides capabilities to create and trade currency. It is assumed this is being run from the root of the EOSIO source.

7.1. Deploy Eosio.msig Contract

The eosio.msig contract allows multiple parties to sign a single transaction asynchronously. EOSIO has multi-signature (multisig) support at a base level, but it requires a synchronous side channel where data is ferried around and signed. Eosio.msig is a more user friendly way of asynchronously proposing, approving and eventually publishing a transaction with multiple parties' consent.

The following steps can be used to deploy the eosio.msig contract.

8. Deploy Hello World Contract

We will now create our first “hello world” contract. Create a new folder called “hello”, cd into the folder, then create a file “hello.cpp” with the following contents:

hello/hello.cpp

You can compile your code to web assembly (.wast) as follows:

Now generate the abi:

Create an account and upload the contract:

Now we can run the contract:

At this time the contract allows anyone to authorize it, we could also say:

--

--

Coinmonks
Coinmonks

Published in Coinmonks

Coinmonks is a non-profit Crypto Educational Publication.

Blockgenic
Blockgenic

Written by Blockgenic

We are a firm focused on Enterprise adoption of blockchain technology. EOS Block Producer name: ‘blockgenicbp’. www.blockgenic.io