Loading...
Vietnam Geography App
Loading...
Vietnam Geography App
Học cách phát triển smart contracts và ứng dụng phi tập trung (DApps) trên Ethereum.
Tạo ứng dụng bỏ phiếu phi tập trung với smart contract
Functional voting DApp với transparent, immutable voting records
// Voting Smart Contract
pragma solidity ^0.8.0;
contract Voting {
struct Candidate {
uint id;
string name;
uint voteCount;
}
mapping(uint => Candidate) public candidates;
mapping(address => bool) public voters;
uint public candidatesCount;
event VotedEvent(uint indexed candidateId);
constructor() {
addCandidate("Alice");
addCandidate("Bob");
}
function addCandidate(string memory _name) private {
candidatesCount++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
function vote(uint _candidateId) public {
require(!voters[msg.sender], "Already voted");
require(_candidateId > 0 && _candidateId <= candidatesCount, "Invalid candidate");
voters[msg.sender] = true;
candidates[_candidateId].voteCount++;
emit VotedEvent(_candidateId);
}
}
// Web3.js Integration
const Web3 = require("web3");
const contract = require("../build/contracts/Voting.json");
class VotingService {
constructor() {
this.web3 = new Web3(Web3.givenProvider || "http://localhost:7545");
this.contract = null;
this.account = null;
}
async init() {
const networkId = await this.web3.eth.net.getId();
const deployedNetwork = contract.networks[networkId];
this.contract = new this.web3.eth.Contract(
contract.abi,
deployedNetwork && deployedNetwork.address
);
const accounts = await this.web3.eth.getAccounts();
this.account = accounts[0];
}
async vote(candidateId) {
return await this.contract.methods.vote(candidateId)
.send({ from: this.account });
}
async getCandidates() {
const candidatesCount = await this.contract.methods.candidatesCount().call();
const candidates = [];
for (let i = 1; i <= candidatesCount; i++) {
const candidate = await this.contract.methods.candidates(i).call();
candidates.push(candidate);
}
return candidates;
}
}