const Web3 = require('web3');
const web3= new Web3('http://localhost:8545');
const deployContract = new Web3.eth.Contract();
deployContract.deploy();
위의 내용이 전체적인 코드 내용이다. 이제 세부적인 항목을 작성해보도록 하겠다.
<code />
const Web3 = require('web3');
const fs = require('fs');
const ABI = JSON.parse(fs.readFileSync('./Voting_sol_Voting.abi').toString());
const BYTECODE=fs.readFileSync('./Voting_sol_Voting.bin').toString();
const web3= new Web3('http://localhost:8546');
const deployContract = new Web3.eth.Contract(ABI);
deployContract.deploy({
//배포를 할 때 컴파일한 byte값을 넣음data:BYTECODE,
arguments:[['ingoo1','ingoo2','ingoo3'].map(name=>web3.utils.asciiToHex(name))]
//원래 string값을 못씀 16진수로 바꾸어야 함.//{}가 없으면 return 값을 생략해줄 수 있다!
})//배포를 할 때 생성자를 넣어주는 것임. sol안에 생성자를 넣어주느 것이 아니다.
.send({//어느 주소에서 transaction을 발생시킬겨냐=>ganache의 하나의 주소값을 사용한다. from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA',
gas:6721975,
})//결과값이 프로미스로 떨어져서 then으로 받았다.
.then(newContract=>{
console.log(newContract.options.address);
})
//원래 이런 작업들이 truffle 프레임워크를 이용해서 할 수 있다.// /*
['ingoo1','ingoo2','ingoo3'].map(name=>{
return web3.utils.asciiToHex(name);
})
*/
const deployContract = new Web3.eth.Contract(ABI);블록을 생성할 때 컴파일한 abi의 내용을 컴파일에 넣는다. deploy안에 있는 값은 byte값을 넣어준다. 그래서 arguments
node 에서 나오는 값을 넣어주면 된다. ganache에 나오는 contract crated값을 넣어줘도 된다.
<code />
const Web3 = require('web3');
const fs = require('fs');
const ABI = JSON.parse(fs.readFileSync('./Voting_sol_Voting.abi').toString());
const BYTECODE=fs.readFileSync('./Voting_sol_Voting.bin').toString();
const web3= new Web3('http://127.0.0.1:8545');
const deployContract = new web3.eth.Contract(ABI);
//블록을 생성할 때 컴파일한 abi를 컴파일에 넣었다.// deployContract.deploy({// //배포를 할 때 컴파일한 byte값을 넣음// data:BYTECODE,// arguments:[['ingoo1','ingoo2','ingoo3'].map(name=>web3.utils.asciiToHex(name))]// //원래 string값을 못씀 16진수로 바꾸어야 함.// //{}가 없으면 return 값을 생략해줄 수 있다!// })//배포를 할 때 생성자를 넣어주는 것임. sol안에 생성자를 넣어주느 것이 아니다. // .send({//어느 주소에서 transaction을 발생시킬겨냐=>ganache의 하나의 주소값을 사용한다. // from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA',// gas:'6721975',// })//결과값이 프로미스로 떨어져서 then으로 받았다.// .then(newContract=>{// console.log(newContract.options.address);// })//원래 이런 작업들이 truffle 프레임워크를 이용해서 할 수 있다.// /*
['ingoo1','ingoo2','ingoo3'].map(name=>{
return web3.utils.asciiToHex(name);
})
*///해당 블록주소에 접속해야 한다. 내 contract는 그 주소에 있으니까const contract=new web3.eth.Contract(ABI, '0xf70931b2415b7cfce985aee2e422a5e167ef4a5b');
contract.methods.totalVotesFor('ingoo1').call().then(data=>{
console.log(data);
})//call을 써야지만 promise객체로 실행한다.
contract.methods.vodeForCandiodate('ingoo1').send({from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA'});\
//투표하는 메소드에 넣는 from 값은 처음 생성한 계정의 주소값을 넣어주면 된다. //투표하는 사람이다. 10개의 계정중에 아무거나 넣어도 상관이 없다.
/*가나시 연결을 해야 한다. */const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
//node.js가 아니고 javascript연결때 이렇게 사용한다. const ABI=JSON.parse(`[{"inputs":[{"internalType":"string[]","name":"_candidateNames","type":"string[]"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"candidateList","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"}],"name":"totalVotesFor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"}],"name":"validCandidate","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_candidate","type":"string"}],"name":"vodeForCandiodate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"voteReceived","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]`);
const deployAddress=`0xf70931b2415b7cfce985aee2e422a5e167ef4a5b`;
let VotingContract = new web3.eth.Contract(ABI,deployAddress);
window.addEventListener('DOMContentLoaded',init);
async function init(){
console.log('hello world!');
await VotingContract.methods.vodeForCandiodate('ingoo1').send({from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA'});
VotingContract.methods.totalVotesFor('ingoo1').call().then(data=>{
console.log(data);
})
}
Ganache를 끄고 다시 키면 투표 내용도 날아가고, 스마트 컨트랙트로 배포했던 내용들이 다 날라간다. 컴파일도 다시 해야한다. 코드도 다시 바꾸어야 한다. ganache는 파일에 저장하는것이 아니어서 다 날아간다. 배포할 주소값도 새로 생긴 주소값으로 넣어주어야 한다.
server.js
<code />
/*가나시 연결을 해야 한다. */const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
//node.js가 아니고 javascript연결때 이렇게 사용한다. const ABI=JSON.parse(`[{"inputs":[{"internalType":"string[]","name":"_candidateNames","type":"string[]"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"candidateList","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"}],"name":"totalVotesFor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"}],"name":"validCandidate","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_candidate","type":"string"}],"name":"vodeForCandiodate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"voteReceived","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]`);
const deployAddress=`0xf70931b2415b7cfce985aee2e422a5e167ef4a5b`;
let candidates={"ingoo1":"candidate1","ingoo2":"candidate2","ingoo3":"candidate3"};
let VotingContract = new web3.eth.Contract(ABI,deployAddress);
window.addEventListener('DOMContentLoaded',init);
async function init(){
let candidateNames = Object.keys(candidates);
for(let i=0;i<candidateNames.length;i++){
let name = candidateNames[i];//ingoo1
candidates[name]//candidate1const nameElement = document.querySelector(`#${candidates[name]}`);
nameElement.innerHTML=name;
const countElement=document.querySelector(`#candidateCount${i+1}`);
countElement.innerHTML=await VotingContract.methods.totalVotesFor(`ingoo${i+1}`).call();
}
// console.log('hello world!');// await VotingContract.methods.vodeForCandiodate('ingoo1').send({from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA'});// VotingContract.methods.totalVotesFor('ingoo1').call().then(data=>{// console.log(data);// })
}
const btn = document.querySelector("#btn");
btn.addEventListener('click',btnEvent);
async function btnEvent(){
let candidateName = document.querySelector(`#candidateName`).value;await VotingContract.methods. vodeForCandiodate(candidateName).send({from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA'})
}
/*가나시 연결을 해야 한다. */const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
//node.js가 아니고 javascript연결때 이렇게 사용한다. const ABI=JSON.parse(`[{"inputs":[{"internalType":"string[]","name":"_candidateNames","type":"string[]"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"candidateList","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"}],"name":"totalVotesFor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"}],"name":"validCandidate","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_candidate","type":"string"}],"name":"vodeForCandiodate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"voteReceived","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]`);
const deployAddress=`0xf70931b2415b7cfce985aee2e422a5e167ef4a5b`;
let candidates={"ingoo1":"candidate1","ingoo2":"candidate2","ingoo3":"candidate3"};
let VotingContract = new web3.eth.Contract(ABI,deployAddress);
window.addEventListener('DOMContentLoaded',init);
async function init(){
let candidateNames = Object.keys(candidates);
for(let i=0;i<candidateNames.length;i++){
let name = candidateNames[i];//ingoo1
candidates[name]//candidate1const nameElement = document.querySelector(`#${candidates[name]}`);
nameElement.innerHTML=name;
const countElement=document.querySelector(`#candidateCount${i+1}`);
countElement.innerHTML=await VotingContract.methods.totalVotesFor(`ingoo${i+1}`).call();
}
// console.log('hello world!');// await VotingContract.methods.vodeForCandiodate('ingoo1').send({from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA'});// VotingContract.methods.totalVotesFor('ingoo1').call().then(data=>{// console.log(data);// })
}
const btn = document.querySelector("#btn");
btn.addEventListener('click',btnEvent);
async function btnEvent(){
let candidateName = document.querySelector(`#candidateName`).value;await VotingContract.methods. vodeForCandiodate(candidateName).send({from:'0x7fB9085d9D321106fb9De9Dd95ef0A8776599beA'})
let candidateCount = await VotingContract.methods.totalVotesFor(candidateName).call();
let number = candidateName.charAt(candidateName.length-1)
let countElement = document.querySelector(`#candidateCount${number}`);
countElement.innerHTML = candidateCount;
}