Skip to main content

EOSIO Blockchain dApp Step by Step: Part 3 - Webapp


This is the 3rd part (final) of the blog: EOSIO dApp on Blockchain Step-by-Step: Part 1. In the last part, I’ve developed a Smart Contract for EOSIO platform to simulate an election. This part I will develop a webapp that allows visitors to vote for a candidate.

Below is a quick preview of the webapp:

Source Code Explanation

Firstly, please see below for the overview diagram:

The Frontend

The frontend consists of HTML, CSS, and Javascript. I used SemanticUI as CSS framework for a nice appearance. JQuery is heavily used in Javascript for easy development.

There has only one page (homepage HTML) for this webapp. The homepage has divided into four portions. Below is the screenshot of the portions:
Below is the code fragment of the homepage index.html:
...
  <body>
    <div class="ui container">
      <div class="ui grid">
    ...
        <div id="hints_portion" class="sixteen wide column">
        ...
        </div>
        <div id="input_portion" class="sixteen wide column">
        ...
        </div>
        <div id="voting_portion" class="sixteen wide column">
        ...
        </div>
        <div id="voted_portion" class="sixteen wide column">
        ...
        </div>
    ...
      </div>
    </div>
...

*Click here for the full source code of index.html

The app.js covers the frontend logic. Below is the highlight:
...
// Main Application Object
function App() {
  ...
}
...
// Ajax calls
App.prototype.getInfo = function() {
  return $.ajax({
    type: 'GET',
    dataType: 'json',
    url: '/api/getinfo'
  });
}
App.prototype.unlockWallet = function() {
  return $.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/api/unlock_wallet'
  });
}
...
// Event handlers
App.prototype.onBtnInputNameClicked = function(evt) {
  ...
}
...
// Program startup
App.prototype.start = function() {
  self.getInfo().then(function() {
    return self.unlockWallet();
  }).done(function() {
    ...
  }
}
...
*Click here for the full source code of app.js

As you can see, I used jQuery ajax() and then() to perform several asynchronous calls to the backend. The following section will mention the backend code.

The Backend

The backend is programmed in Python and Flask as the web framework. Flask not only allows us very easy to create a powerful web application but quickly develop RESTful API services. Below is the code highlights of the server.py code:

*Click here for the full source code of server.py

As mentioned above, inside the cleos() function, it spawns new processes to launch cleos command just like in the command line. You may wonder that why not use EOSJS. The fact is there was a problem to create EOSIO accounts in EOSJS. Actually, I tried all efforts in NodeJS codes to create an account in EOSJS but all failed. So I gave up and switched to Python Flask. Although the subprocess is slow and has scalability issues. I think it is appropriate for demonstration purposes though.

This approach makes it easy to invoke the EOSIO Smart Contract. Below code fragment in server.py illustrated how to invoke vote action which the smart contract developed in the last part of the blog:
...
@app.route('/api/vote_candidate', methods=['POST'])
def vote_candidate():
    account = request.form.get('account')
    candidate = request.form.get('candidate')
    param = '\'["' + account + '", ' + candidate + ']\''
    # Invoke the Smart Contract "vote" action
    result = cleos(['push', 'action', 'election', 'vote', param, '-p', account])
    print(result.stderr)
    if result.returncode == 0:
        return jsonify({'result': result.stderr.decode('ascii')})
    else:
        return result.stderr, 500
...

Thus the frontend code app.js to invoke that:
...
App.prototype.voteCandidate = function(account, candidate) {
  return $.ajax({
    type: 'POST',
    data: {
      account: account,
      candidate: candidate
    },
    dataType: 'json',
    url: '/api/vote_candidate'
  });
}
...
  this.voteCandidate(this._account, val).done(function(resp) {
    console.info('Vote AJAX call result');
    console.log(resp);
...

Try It Yourself

I’ve setup a demo server that lets you have a taste of EOSIO blockchain. Browse to http://demo.simonho.net:5000 to try it yourself. But I cannot guarantee the server is available anytime and long-lasting. It just a virtual machine of my home PC though 😊

Conclusion

That’s all for the series of my EOSIO blockchain experiment. The hyperlinks of prior parts: part 1 and part 2.

(Bonus Part 4 is available: Which I used Google App Maker as frontend instead of HTML/CSS/JS used in this part)

Hope You Enjoy it!

The project full source code is hosting on this github repo

Comments

  1. When looking at the 9/6 chart there quantity of} things|are some things} that should seem 1xbet somewhat apparent. Therefore, it solely is sensible to memorize the correct choices for one sort of machine and to all the time play on that same sort of machine . Mobile casinos are optimized for small screens and contact controls for a flawless person experience. Robbie held the ace and received three extra aces on the flip together with three of clubs earning him the $400,000 jackpot. Place a wager, normally $1 to $5 per hand, then press the "Deal button".

    ReplyDelete

Post a Comment

Popular posts from this blog

Build A Simple Sales System using Google Drive

Google Drive is a free-to-use cloud service with a 15 GB limit storage. 15 GB is large enough to store documents, and "program" too. Yes, it's correct. We can program Google Drive. This blog is a step-by-step tutorial to show you how to build a simple P.O.S. system on Google Drive. Create a Google Sheets to define the products 1. Login to Google Drive using your Gmail account and create a Google Sheets: 2. Input the products in the Google Sheets Create a Google Forms for sale input 1. Create a new Google Form 2. Edit the form and the first field Note that leave the option field unchanged. We'll assign it programmatically in below 3. Add a quantity field 4.  Add a last field for the price input How to copy data from Google Sheets to Google Forms? We need to add a script to do that. Google developed Google App Script (GAS) for us to achieve that. Now go back to the Google Sheet we just created above. Then enter to the script editor You'll see the below screen. Then ...

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  popa.qa  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 webpag...

Develop an intelligent Slack bot using Block UI for website administration

In conventional web site administration, web developers build an admin site to perform daily tasks such as query how many members register daily and block a user. The admin site development includes frontend and backend codes. The slack developer can do the same thing without any frontend code. Starting from Feb 2019, Slack provides a very powerful and beautiful UI component (Block UI): In this blog, we will develop a Slack bot to tell you how many users register today, or block a user. Take a look to below video: What is Slack? Slack is a collaboration hub where you and your team can work together. Like Whatsapp group, our team 50% of workers are working remotely and all communicate in Slack workspace. Why Slack? Slack provides SDK for developers to develop applications. Below sections will show you how to develop a Slack Bot (Chatbot application). It works like a colleague to perform backend tasks. The bot can recognize below messages: How many users registered today? Block user NNN ...