Skip to content

Instantly share code, notes, and snippets.

@maheshmurthy
Created March 4, 2019 22:09
Show Gist options
  • Save maheshmurthy/ce1e61d595a0f2555172d416f4adb7b7 to your computer and use it in GitHub Desktop.
Save maheshmurthy/ce1e61d595a0f2555172d416f4adb7b7 to your computer and use it in GitHub Desktop.
ethers.js with web3 provider
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"}]')
provider = new ethers.providers.Web3Provider(web3.currentProvider);
signer = provider.getSigner();
contract = new ethers.Contract('0x5735731eEbDA5BE1eEe9f0b119B9374a63b0f507', abi, signer)
candidates = {"Rama": "candidate-1", "Nick": "candidate-2", "Jose": "candidate-3"}
function voteForCandidate(candidate) {
candidateName = $("#candidate").val();
console.log(candidateName);
contract.voteForCandidate(ethers.utils.formatBytes32String(candidateName)).then((f) => {
let div_id = candidates[candidateName];
contract.totalVotesFor(ethers.utils.formatBytes32String(candidateName)).then((f) => {
$("#" + div_id).html(f);
})
});
}
$(document).ready(function() {
candidateNames = Object.keys(candidates);
for(var i=0; i<candidateNames.length; i++) {
let name = candidateNames[i];
contract.totalVotesFor(ethers.utils.formatBytes32String(name)).then((f) => {
$("#" + candidates[name]).html(f);
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment