[BlockChain] 스마트컨트랙트로 투표 Dapp 만들기

2022. 12. 6. 10:08·개발/BlockChain
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] 메타마스크 토큰추가  (1) 2022.12.06
[BlockChain] ganache, react, express로 메타마스크 연결하기  (0) 2022.12.05
[BlockChain] truffle로 스마트컨트랙트 배포하기  (1) 2022.12.05
'개발/BlockChain' 카테고리의 다른 글
  • [BlockChain] ERC20 Token 만들기
  • [BlockChain] 사과 판매 앱 만들기
  • [BlockChain] 메타마스크 토큰추가
  • [BlockChain] ganache, react, express로 메타마스크 연결하기
TeTedo.
TeTedo.
  • TeTedo.
    TeTedo 개발 일기
    TeTedo.
  • 전체
    오늘
    어제
    • 분류 전체보기 (319)
      • 개발 (274)
        • Article (4)
        • 정리 (21)
        • Spring Boot (17)
        • JPA (2)
        • JAVA (6)
        • Database (4)
        • 자료구조 (11)
        • 알고리즘 (32)
        • React (20)
        • Docker (10)
        • node.js (18)
        • Devops (11)
        • Linux (4)
        • TypeScript (3)
        • Go (10)
        • HyperLedger (4)
        • BlockChain (43)
        • html, css, js (48)
        • CS (3)
        • AWS (3)
      • 모아두고 나중에 쓰기 (3)
      • 팀프로젝트 (18)
        • SNS(키보드워리어) (9)
        • close_sea (9)
      • 개인프로젝트 (1)
        • Around Flavor (1)
        • CHAM (13)
        • ethFruitShop (5)
      • 독서 (0)
        • 스프링부트와 AWS로 혼자 구현하는 웹 서비스 (0)
  • 블로그 메뉴

    • 홈
    • 개발일기
    • CS
    • 실습
    • 코딩테스트
    • 웹
    • Go
    • node.js
    • 팀플
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    30일챌린지
    30일 챌린지
    js
    mysql
    블록체인
    erc20
    node
    CSS
    하이퍼레저
    도커
    node.js
    go언어
    컨테이너
    nodejs
    명령어
    프로그래머스
    React
    go
    html
    ERC721
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
TeTedo.
[BlockChain] 스마트컨트랙트로 투표 Dapp 만들기
상단으로

티스토리툴바