Skip to main content

EOSIO Blockchain dApp Step by Step: Part 2 - Smart Contract

This is the 2nd part of the blog: EOSIO dApp on Blockchain Step-by-Step: Part 1. The last blog described the EOSIO setup processes steps-by-steps. This part will develop a Smart Contract for EOSIO platform.


The purpose of the smart contract is to simulate an election. I created an EOSIO user to host the smart contract. Created two citizen users to vote for a candidate. The voting records keep saving in the EOSIO blockchain. In this example, all operations are operating in command mode. Let’s get started.

Develop the Smart Contract

EOSIO executes the smart contract which is developed in WebAssembly standard. So I developed the election smart contract in C++. Below is the full source code of election.cpp:

Note the last line EOSIO_ABI() is a macro statement to generate ABI file automatically rather than write it manually. ABI file is to define the apply action handler. Which tells the EOSIO the definition of the handlers inside the smart contract.

EOSIO provides multi-index database API for us to persist data into the blockchain. In the above election smart contract, I defined two multi_index (similar to SQL table): candidates and voters. Actually which are two arrays to store the two struct: candidate and voter. I used C++ STL to manipulate the multi_index such as add, update, delete.

Note that the two struct are marked with /// @abi table at the beginning. This is to tell EOSIO abi generator to generate the ABI tables into the election.abi file. Which is very convenient.

To compile the election smart contract:
$ eosiocpp -o election.wast election.cpp
The WAST and WASM files are generated respectively. But it is not enough for EOSIO. We need to generate the ABI file as well:
$ eosiocpp -g election.abi election.cpp

Optional Files for Visual Studio Code

To enhance the development experience, I’ve created a properties file c_cpp_properties.json for Visual Studio Code (VSCode) to tell it how to find the header files. The file needs to be stored in .vscode directory as below:

The file content of .vscode/c_cpp_properties as below:
  "configurations": [
      "name": "Linux",
      "includePath": [
      "defines": [],
      "compilerPath": "/usr/bin/clang++-4.0",
      "cStandard": "c11",
      "cppStandard": "c++17",
      "intelliSenseMode": "clang-x64"
  "version": 4

Start the EOSIO

The machine is continuously using the virtual machine which was well configured (mentioned in part 1). To start the single-node Testnet server:
$ nodeos -e -p eosio --plugin eosio::wallet_api_plugin --plugin eosio::chain_api_plugin --plugin eosio::history_api_plugin --access-control-allow-origin=* --contracts-console
Click here for more info on the nodeos parameters.

Create the Accounts

The next task is to unlock the default wallet. EOSIO stores the keypairs in the wallet. It needs to be unlocked every time when the server restart or every 15 minutes. To unlock the wallet:
$ cleos wallet unlock --password ${wallet_password}

We need to create owner keypairs and active keypairs respectively. Then import that private keys to the wallet. Type below command:
$ cleos create key # Create an owner key
$ cleos create key # Create an active key
$ cleos wallet import ${private_owner_key}
$ cleos wallet import ${private_active_key}
Don’t forget to record those keypairs in somewhere

The next task is to create a new account election to hold the smart contract. Type below command:
$ cleos create account eosio election ${public_owner_key} ${public_active_key}
In addition, create two citizens for voting simulation:
$ cleos create account eosio voter1 ${public_owner_key} ${public_active_key}
$ cleos create account eosio voter2 ${public_owner_key} ${public_active_key}

Deploy the Smart Contract

Type below command to upload the election smart contract:
$ cleos set contract election ../election -p election
The resulting screenshot:

Run the Smart Contract

We can try to run the contract.

1. Run the version action:
$ cleos push action election version '' -p election
We can inspect the console output from nodeos:

2. Adding election candidates:
$ cleos push action election addc '["Hillary Clinton"]' -p election
$ cleos push action election addc '["Donald J. Trump"]' -p election
3. Shows the candidates database which is storing in the blockchain:
$ cleos get table election election candidate
The resulting screenshot:

4. Simulate voting (both voters are voted to Donald J. Trump):
$ cleos push action election vote '["voter1", 1]' -p voter1
$ cleos push action election vote '["voter2", 1]' -p voter2

If voter1 votes again:
$ cleos push action election vote '["voter1", 0]' -p voter1
EOSIO returns exception:

5. See the election result:
$ cleos get table election election candidate

As you can see, the vote count of candidate “Donald J. Trump” is 2. That means the Election Smart Contract was working!

That’s all for this part.

In the next part, I will create a web app for demonstrating the interaction between web visitors and the blockchain.

The source code host at this github repo


Popular posts from this blog

Create An Online Store Theme Used By MyCMS

MyCMS is an open-source Content Management System to generate static online shop website. You can use my hosting to input your products, or you can download the source codes and host it in your own server (running NodeJS). Please refer to my Github repo for the detailed installation instructions. This blog is a step-by-step tutorial that shows you how to create an online-shop theme. In this tutorial, it’s using my hosting to input the shop details and products. If you’re hosting the MyCMS by yourself, just change the domain name to yours will do. Introducing MyCMS Before making the theme, you’ll need to use MyCMS to configure the demo shop and input two demo products. MyCMS generates a static website via a theme. The generated static website is NO server program required. You can put the website files (HTML/CSS/JS) to any CDN, hosting. Shop Configuration You must prepare below settings Before using MyCMS: Setting Description Example Store name Your store name will be displayed in t

How I make a web-components based dynamic Javascript page at the top of Google Search

Introduction Everybody wants their website shown at the first position of Google search. SEO (Search Engine Optimization) is a big topic. I just helped my client's website shows the database records at the top search rankings (at least several Chinese generic keywords). See the three example questions all are listed at top ranking: Website background: My client's website  is a traditional Chinese Q&A site that lets members ask and answer questions. All answers and questions are storing in the database server. Step 1: Create The Project This blog illustrates the problems and the steps to fix that with project source codes. Below is the description of the basic project: NodeJS backend (server.js) Develop an API ( /get-database-records ) to simulate getting database records Web-components frontend (index.html) An example component IndexPage  make use of  LitElement to render database records To start the server type: npm start Then I check the webpage speed using th

Progressive Web App Wordpress Theme (Part 2/2)

This is the 2nd part of the blog: Progressive Web App Wordpress Theme Part 1 . Last time the Progressive Web App performs in the local server properly. This part will integrate it with WordPress Theme. Test it in real WordPress server, and Android phone as well. Let’s get started. Produce a Wordpress Basic Theme As WordPress Theme Development document mentioned , it does require at least three basic files. I store those files in directory /wp-files were under the project root. 1. Theme Stylesheet /wp-files/style.css : /* Theme Name: PWAWP-Theme Theme URI: Author: Simon Ho Author URI: Description: Progressive Web App Wordpress Theme Version: 1.0 License: GNU General Public License v2 or later License URI: Text Domain: pwawordpress Tags: pwa, one-column This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others.