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

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 ...