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

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  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 webpage speed using th

Progressive Web App Wordpress Theme (Part 1/2)

After I read two articles: Progressive Web Apps Are The Next Big Thing and More Surprising Statistics About WordPress Usage . I decided to build a Wordpress theme which integrated Progressive Web Apps (PWA) to see how cool it is when two “Big Thing” mix together. TL;DR To avoid Too Long; Didn’t Read. I break the whole procedure into two blogs. In part 1, I will build a Progressive Web App in the local server. What PWA features to be built here? According to PWA wiki , the PWA will be progressive enhancements. The final webapp will be: Responsive design: I choose Bootstrap 4 because it’s mobile-first design. Contents retrieve from Wordpress CMS via REST API . It’s a natural way the App is developed in Javascript. Offline support: The PWA still can run and display the contents when no Internet connection. Installable on Android home screen: I w