The most detailed teaching you how to build the simplest Dapp voting system with a front end

A very practical reference https://blog.csdn.net/weixin_45629315/article/details/113469323 has been very detailed (hereinafter referred to as its tutorial ), and the operation is simple, but for those who have never been in touch with Dapp development and have never used Remix For programmers of /Ganache/solidity, it is still unclear how to do certain operations, so here are more details through screenshots~

1. Open the Windows developer model

I don’t know if this step is useful. It may be helpful to open the developer mode of windows because of other projects.
insert image description here
insert image description here

2. The Firefox browser loads the MetaMask plug-in

insert image description here
insert image description here
insert image description here

The red box in the picture below is "Remove", because I have already loaded the MetaMask tool. If the MetaMask plugin has not been installed, then the red box is a "Load" button
insert image description here

3. Login to MetaMask

  • new account

There are two options to log in to MetaMask for the first time, one is to create a new account, and the other is to import an account. I clicked on the new account and went all the way to next. Be sure to write down the mnemonic (this is also special for MetaMask, Ethereum, blockchain, or Web3. Where they log in instead of passwords and verification codes, they log in with mnemonic words. Once an account is created, it cannot be destroyed~), and the mnemonic words are 12 English words. Next, you can create a new Account account (this Account account cannot be destroyed once it is established), and you must write down its Key (private key), so that you can retrieve it later. The network here
insert image description here
is the main Ethereum network, and there is no money in the account. ETH, how to use the local network, how to import accounts with ETH, in part 4

  • Importing Accounts
    How to import accounts is explained after part 4

4. Start Ganache

Follow the tutorial to download the Ganache installation package on the official website. After installation, there are two buttons on the startup interface, select QUICKSTART (don’t worry about silent-plants (ethereum) first)
insert image description here
Ganache has built a private local Ethereum network, the network address and port number are in red In the box, the mosaic part is 10 accounts, and each account has a balance of 100ETH. Later, we will import an account into MetaMask
insert image description here

There is a "Save" button in the blue box (I have saved it here so there is no save button), so write down a Workspace, the name of Workspac is silent-plants, next time you start Ganache, click silent-plants in the picture below (ethereum), enter the corresponding workspace, and reuse those 10 accounts
insert image description here

5. MetaMask and Ganache connection

Refer to Part 6 of the tutorial https://blog.csdn.net/sanqima/article/details/120406660

MetaMask add network
insert image description here

As shown in the figure below: "Network Name" self-definition
insert image description here

"New RPC URL" is the address of Ganache in the red box in the figure below
insert image description here

"Chain ID" is 1337 by default, and "Currency Symbol" is ETH

Click Save, MetaMask connects to the local private network, select the local private network in the following position
insert image description here

6. Import MetaMask into Ganache account

Click the circle avatar in the upper right corner → click "Import Account"
insert image description here
to paste the private key, return the private key to MetaMask
insert image description here
in Ganache and paste it, click "Import", the import is successful
insert image description here
insert image description here

insert image description here

Under the supplementary explanation:

There are two kinds of accounts in MetaMask, the first one is newly created (Account1 in the picture below, there is no "Imported" button on the right), and the second is an imported account (Account2 in the picture below, there is an "Imported" button on the right) , select Account2 to switch to this account
insert image description here

The first type of account cannot be deleted or removed after it is created. The second type of account can be removed from MetaMask, and the account cannot be completely deleted. This is because the account on the Ethereum/blockchain cannot be completely deleted once it is created.

The way to delete is to click the three-dot button on the right side of Account2 as shown in the figure below, click "Delete Account", then Account2 will be removed from MetaMask
insert image description here

7. Connect MetaMask to Remix

At this time, MetaMask is not connected to Remix.
insert image description here
Click MetaMask under the Remix website → click the three origins in the upper right corner → click "Connected Websites"

insert image description here
In the pop-up dialog box, select "Manually connect to the current site"

insert image description here
Select Account2 → click "Next"
insert image description here
and click "Connect"
insert image description here

connection succeeded!
insert image description here

8. Remix deployment contract

This part is consistent with the tutorial~

9. Connect the front end and deploy the smart contract to the Web

The tutorial didn’t mention where to write html and javascript codes. I’ve been writing them in Remix, but I don’t know how to run them. It’s actually very simple, not that complicated~

Create a new index.html file in the local folder, and the location can be placed anywhere.
insert image description here
The html code is as follows

<!DOCTYPE html>
<html>
<head>
    <title>Hello World DApp</title>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
</head>
<body class="container">
<h1>A Simple Voting Application</h1>
<div class="table-responsive">
    <table class="table table-bordered">
        <thead>
        <tr>
            <th>Candidate</th>
            <th>Votes</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>Alice</td>
            <td id="candidate-1"></td>
        </tr>
        <tr>
            <td>Bob</td>
            <td id="candidate-2"></td>
        </tr>
        <tr>
            <td>Cary</td>
            <td id="candidate-3"></td>
        </tr>
        </tbody>
    </table>
</div>
<input type="text" id="candidate" />
<a href="#" onclick="voteForCandidate()" class="btn btn-primary">Vote</a>
</body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="./app.js"></script>
</html>

Create a new js file named app.js, and place it in the same folder as index.html
insert image description here

The js code is as follows:

web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
abi = JSON.parse('[{"constant":true,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"totalVotesFor","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"validCandidate","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"votesReceived","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"candidateList","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"voteForCandidate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"candidateNames","type":"bytes32[]"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]')
VotingContract = web3.eth.contract(abi);

//部署的合约地址
contractInstance = VotingContract.at('0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

candidates = {
    
    "Alice": "candidate-1","Bob": "candidate-2","Cary":"candidate-3"}

function voteForCandidate() {
    
    
    console.log(candidate);
    candidateName = $("#candidate").val();
    console.log(candidateName);
    contractInstance.voteForCandidate(candidateName, {
    
    from: web3.eth.accounts[0]}, function() {
    
    
        let div_id = candidates[candidateName];
        console.log(contractInstance.totalVotesFor.call(candidateName).toString());
        $("#" + div_id).html(contractInstance.totalVotesFor.call(candidateName).toString());
    });
    console.log(contractInstance.totalVotesFor.call(candidateName).toString());
}

$(document).ready(function() {
    
    
    candidateNames = Object.keys(candidates);
    for (var i = 0; i < candidateNames.length; i++) {
    
    
        let name = candidateNames[i];
        let val = contractInstance.totalVotesFor.call(name).toString()
        $("#" + candidates[name]).html(val);
    }
});

What is not mentioned in the tutorial is that the name of the js file in the figure below in the html file must be the same as the name of the js file. Modify the
insert image description here
first line of the js file to be the Ganache address.
insert image description here
insert image description here
Modify the address of the newly created contract in the js file as shown in the figure below, which is the contract address deployed by Remix. Not the account address of Ganache!

insert image description here
insert image description here
Open index.html with Firefox browser, or open index.html with other browsers. Deploy the contract to the Web successfully!
insert image description here

Github source code

https://github.com/ningmengzhihe/Vote.git

Interested friends are welcome to like, follow and collect

Guess you like

Origin blog.csdn.net/ningmengzhihe/article/details/127048200