pragma solidity ^0.8.0;
contract Voting {
/*
필요 기능
1 후보자 초기화
2 각 후보자에게 투표 가능
3:후보자들의 각 투표 개수
*/
// ['ingoo1', 'ingoo2', 'ingoo3']
string[] public candidateList;
mapping(string => uint) public voteReceived;
constructor(string[] memory _candidateNames) public {
candidateList = _candidateNames;
}
function voteForCandidate(string memory _candidate) public {
voteReceived[_candidate] += 1;
}
// 후보자 명을 넣어주면 결과값이 투표 개수를
function totalVotesFor(string memory _candidate) view public returns(uint){
return voteReceived[_candidate];
}
// String 비교
function validCandidate(string memory _candidate) view public returns(bool) {
// string to byte
// keccake256() 메서드 안에 byte 값 넣기
for (uint i = 0; i < candidateList.length; i++) {
if (keccak256(bytes(candidateList[i])) == keccak256(bytes(_candidate))) {
return true;
}
}
return false;
}
/*
arr = ['1', '2', '3'];
searchText = '4'
// 완전탐색 0(n)
function check(txt) {
for (let i = 0; i < arr.length; i++); {
if (arr[i] == txt) {
return true;
}
return false;
}
}
console.log(check(serachText));
*/
}
soljs --abi --bin [파일명] // 솔리디티 코드 컴파일 * Voting_sol_Voting.abi, Voting_sol_Voting.bin 자동 생성 됨
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();
let web3 = new Web3('http://127.0.0.1:8545');
// 블록 생성 할 때 솔리디티 컴파일한 abi파일을 인자값으로
const deployContract = new web3.eth.Contract(ABI);
deployContract.deploy({
// 배포를 할 때 솔리디티 컴파일한 byte값을 넣음
data: BYTECODE,
arguments: [['ingoo1', 'ingoo2', 'ingoo3'].map(name => web3.utils.asciiToHex(name))], // { } 대괄호 없으면 return 생략 가능
})
.send({
from: '0x7fE68fFb0395EFb89D3F9f163215eAe3C92f823d', // Available Accounts 첫번째, 가나슈 껐다키면 수정
gas: '6721975',
}, (error, result) => {
console.log(error);
})
.then(newContract=>{
console.log(newContract.options.address);
})
여기까지 작업하고 node deploy로 실행 // newContract.options.address 값 가져오기 const deployContract부터 주석 처리 후 뒤에 아래 내용 추가
const contract = new web3.eth.Contract(ABI, '0x31dc15fd778b1d3bd66f9f621f8797dd1a0fe1d5') // Contract created, 가나슈 껐다키면 수정
contract.methods.voteForCandidate('ingoo1').send({
from: '0x71a1ef22df159fD4B9147d6B21eC04cD0511A583', // Available Accounts 중 0번 제외 아무거나, 가나슈 껐다키면 수정
})
contract.methods.totalVotesFor('ingoo1').call().then(data => {
console.log(data);
})
여기까지 작업하고 node deploy 재실행 실행 할 때마다 블록이 추가되어 숫자가 하나씩 쌓이는게 확인 됨 // 0, 1, 2..... 가나쉬에서는 GAS가 계속 소모되고 있음 (아래) * 가나슈를 재부팅 하면 쌓였던 블록들이나 배포했던 내용들이 다 사라지고, 컴파일도 다시 해야함 * 코드도 수정이 필요하며 해당 내용은 아래 index.js 파일 내 주석으로 달아 놓음