Smart Contract 작성

이 가이드에서 작성할 Dapp은 간단한 election application 입니다. 스마트 컨트랙트 자체에 대한 설명은 아래 블로그글을 참고하세요.

  1. 이 스마트 컨트랙트는 미리 만들어둔 pet-shop truffle box를 이용합니다. 우선 terminal에 새로운 폴더를 만들고, 아래 명령어를 실행하세요.

mkdir election
cd election
truffle unbox pet-shop

2. election.sdl 파일을 만듭니다.

touch contracts/Election.sol
pragma solidity ^0.4.2;

contract Election {
    // Model a Candidate
    struct Candidate {
        uint id;
        string name;
        uint voteCount;
    }

    // Store accounts that have voted
    mapping(address => bool) public voters;
    // Read/write candidates
    mapping(uint => Candidate) public candidates;
    // Store Candidates Count
    uint public candidatesCount;

    event votedEvent (
        uint indexed _candidateId
    );

    function Election () public {
        addCandidate("Pantera");
        addCandidate("X X");
    }

    function addCandidate (string _name) private {
        candidatesCount ++;
        candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
    }

    function vote (uint _candidateId) public {
        // require that they haven't voted before
        // require(!voters[msg.sender]);

        // require a valid candidate
        require(_candidateId > 0 && _candidateId <= candidatesCount);

        // record that voter has voted
        voters[msg.sender] = true;

        // update candidate vote Count
        candidates[_candidateId].voteCount ++;
        
        // trigger voted event
        votedEvent(_candidateId);
    }
}

** copy & paste 했을 때, encoding error가 난다면, 위에 있는 링크로 가서 코드를 가져오세요.

3. truffle을 이용해 ethereum blockchain에 migration하기 위해 migration 파일을 만듭니다.

touch migrations/2_deploy_contracts.js
var Election = artifacts.require("./Election.sol");

module.exports = function(deployer) {
  deployer.deploy(Election);
};

4. 새로운 터미널 창을 띄워서 migration을 진행합니다.

truffle migrate
  • 만약 ethereum client를 찾지 못한다는 error가 발생한다면, ./truffle.js의 port number가 9545인지 확인하세요.

  • 수정후 배포를 하는것이라면 truffle migrate --reset 을 이용하세요.

6. console을 이용해서, 컨트랙트를 확인해 볼 수 있습니다.

truffle console 
Election.deployed().then(function(instance) { app = instance })

Last updated