최데브는 오늘도 프로그래밍을 한다.

솔리티디 투표 컨트렉트 본문

블록체인

솔리티디 투표 컨트렉트

최데브 2023. 3. 18. 02:21
반응형
pragma solidity >=0.8.2 <0.9.0;

contract Vote {
    //structure
    struct candidator {
        string name;
        uint upVote;
    }

    //variable
    bool live;
    address owner;
    candidator[] public candidatorlist;
    //mapping
    mapping(address=>bool) Voted; //계약자의 주소를 특정해서 bool 로 투표했는지 안했는지를 체크하는 mapping
    //Evnet (브로드 캐스트)
    event AddCandidator(string name);
    event UpVote(string candidator, uint upVote);
    event FinshVote(bool live);
    event Voting(address owner);
    //modifier 지정자  컨트렉트 사람지정
    modifier onlyOwner{
        // 컨트랙트가 생성될때 constructor 서 알아오는
        //컨트랙트 생성자의 주소인 owner 변수와 일치하는지 체크하는 modifier
        require(msg.sender == owner); 
        _; // 이 부분에 함수를 넣는다 라는 명시
    }
    //constuctor 초기화
    constructor() public{
        owner = msg.sender;
        live = true;
        emit Voting(owner); // 처음 컨트렉트가 생성됐을때 컨트렉트의 주인이 누구인지 알려주는 event 생성
    }
    //후보자 등록 함수
    function addCandidator(string memory _name) public onlyOwner{
        //require 의 조건이 맞아야만 그 아래 라인으로 진행한다.
        //이러면 그 아래는 가스를 쓰지 않아서 수수료가 절약된다.
        require(live == true);
        require(candidatorlist.length < 5); // 후보자를 무한히 만들지 않기 위해 5명까지로 제한
        candidatorlist.push(candidator(_name,0));
        //emit event 후보자를 추가했다는것을 외부에 알리는 동작
        emit AddCandidator(_name);
    }

    //투표함수
    function upVote(uint _indexOfCandidator) public{
        require(live == true);
        require(_indexOfCandidator < candidatorlist.length);
        require(Voted[msg.sender] == false);
        candidatorlist[_indexOfCandidator].upVote++;
        //메세지를 보낸 사람의 주소를 가지고 있음 (sender)
        Voted[msg.sender] = true;

        emit UpVote(candidatorlist[_indexOfCandidator].name,candidatorlist[_indexOfCandidator].upVote);
    }
    //아무나 투표를 끝내면 안된다. 컨트랙트를 만든 사람만 닫을 수 있어야한다.
    function FinshVoting() public onlyOwner{
        live = false;
        emit FinshVote(live);
    }

}
반응형

'블록체인' 카테고리의 다른 글

블록체인 공부자료  (0) 2021.05.22
Comments