728x90
1. 초기설정
npx truffle init
다른 터미널로 가나쉬 실행
npx ganache-cli
truffle-config.js
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*",
},
},
compilers: {
solc: {
version: "0.8.17",
},
},
};
2. 스마트 컨트랙트
/contracts/Voting.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Voting{
string[] public candidateList;
mapping(string=> uint8) public votessReceived;
constructor(string[] memory candidateNames){
candidateList = candidateNames;
}
// 후보자 표 갯수 확인
function totalVotesFor(string memory candidate) public view returns(uint8){
require(validCandidate((candidate)));
return votessReceived[candidate];
}
// 후보자 투표해주는 함수
function voteForCandidate(string memory candidate) public{
require(validCandidate((candidate)));
votessReceived[candidate] += 1;
}
// 후보자 있는 후보자인지 확인 검증
function validCandidate(string memory candidate) private view returns(bool){
for(uint i = 0 ; i < candidateList.length; i++){
if(keccak256(abi.encodePacked(candidateList[i])) == keccak256(abi.encodePacked(candidate))){
return true;
}
}
return false;
}
}
3. 배포
/migrations/2_deploy_Voting.js
const Voting = artifacts.require("Voting");
module.exports = function (deployer) {
deployer.deploy(Voting, ["후보자1", "후보자2", "후보자3"]);
};
배포
npx truffle migration
4. 테스트
/test/voting.test.js
const Voting = artifacts.require("Voting");
describe.only("Voting", () => {
let deployed; // 배포 컨트랙트 객체
let candidateList; // 후보자 리스트
it("deployed", async () => {
deployed = await Voting.deployed();
});
it("후보자 리스트 확인", async () => {
const req = [
deployed.candidateList.call(0),
deployed.candidateList.call(1),
deployed.candidateList.call(2),
];
candidateList = await Promise.all(req);
console.log(candidateList);
});
it("투표, 투표수 확인", async () => {
await deployed.voteForCandidate(candidateList[1]);
await deployed.voteForCandidate(candidateList[1]);
await deployed.voteForCandidate(candidateList[0]);
await deployed.voteForCandidate(candidateList[0]);
for (const key of candidateList) {
let count = await deployed.totalVotesFor(key);
console.log(`${key} : ${count}`);
}
}).timeout(10000);
});
728x90
'개발 > BlockChain' 카테고리의 다른 글
[BlockChain] ERC20 Token 만들기 (0) | 2022.12.06 |
---|---|
[BlockChain] 사과 판매 앱 만들기 (0) | 2022.12.06 |
[BlockChain] 메타마스크 토큰추가 (0) | 2022.12.06 |
[BlockChain] ganache, react, express로 메타마스크 연결하기 (0) | 2022.12.05 |
[BlockChain] truffle로 스마트컨트랙트 배포하기 (0) | 2022.12.05 |