Skip to content

Instantly share code, notes, and snippets.

@Nharu

Nharu/project.md Secret

Last active September 14, 2019 14:17
Show Gist options
  • Save Nharu/3996ac257144cd8277a5da6381bd6f18 to your computer and use it in GitHub Desktop.
Save Nharu/3996ac257144cd8277a5da6381bd6f18 to your computer and use it in GitHub Desktop.
Klaytn study 4주차

Klaytn Study 4주차

<개요>

3주차에 작성하였던 홀짝 게임 스마트컨트랙트를 Baobab에 배포하고, 게임을 할 수 있는 Web UI를 만드려 합니다.

<배포할 스마트컨트랙트 코드 리뷰>

아래는 3주차에 작성하였던 홀짝 게임 스마트컨트랙트 코드입니다.

// Klaytn IDE uses solidity 0.4.24, 0.5.6 versions.
pragma solidity >=0.4.24 <=0.5.6;

contract SippingGame {
    address public owner;
    
    mapping(address=>uint256) isUser;
    
    constructor() public {
        owner = msg.sender;
    }
    
    function getBalance() public view returns (uint) {
        return address(this).balance;
    }
    
    function deposit() public payable {
        require(msg.sender == owner);
    }
    
    function transfer(uint _value) public returns(bool) {
        require(getBalance() >= _value);
        msg.sender.transfer(_value);
        return true;
    }
    
    function bet(bool _input) public payable{
        bool result = true;
        
        if(checkUser(tx.origin) == false){
            return;
        }

        isUser[tx.origin] = getBlockNumber();
        
        if(getBlockNumber()%2 == 0){
            result = false;
        }
        
        if(result == _input){
            transfer(msg.value*2);
        }
    }
    
    function getBlockNumber() public view returns (uint256) {
        return block.number;
    }
    
    function checkUser(address _addr) public view returns(bool){
        if(isUser[_addr] == getBlockNumber()){
            return false;
        }
        else{
          return true;
        }
    }
}

<환경설정>

Node.js 설치

node

NVM(Node Version Manager)을 통하여 노드를 설치합니다. 해당 포스팅에서는 v10.16.3을 설치하였습니다.

truffle

NPM(Node Package Manager)을 통하여 truffle을 설치합니다. 해당 포스팅에서는 v4.1.15를 설치하였습니다.

solidity

에디터로 사용할 VSCode에 Solidity 사용을 위하여 Solidity Extension을 설치합니다.

package.json 설정

{
  "name": "klay-dapp-boilerplate",
  "version": "0.0.1",
  "description": "boilerplate for klaytn-based app",
  "main": "truffle.js",
  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server"
  },
  "dependencies": {
    "caver-js": "^0.0.2-m",
    "connect-privkey-to-provider": "^0.0.3",
    "spin.js": "^4.0.0"
  },
  "devDependencies": {
    "copy-webpack-plugin": "^4.6.0",
    "eslint": "^4.19.1",
    "webpack": "^4.7.0",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.1.4"
  },
  "eslintConfig": {
    "env": {
      "browser": true,
      "node": true
    }
  }
}

위와같이 package.json을 작성합니다. 이를 통해 npm으로 caver.js package를 설치하고, 의존성을 관리합니다.

<Truffle을 이용하여 Baobab에 스마트컨트랙트 배포>

deploy_contract.js

const fs = require('fs')
const SippingGame = artifacts.require('./SippingGame.sol')

module.exports = function (deployer) {
  deployer.deploy(SippingGame)
    .then(() => {
      if (SippingGame._json) {
        fs.writeFile('deployedABI', JSON.stringify(SippingGame._json.abi),
          (err) => {
            if (err) throw err;
            console.log("파일에 ABI 입력 성공")
          }
        )

        fs.writeFile('deployedAddress', JSON.stringify(SippingGame.address),
          (err) => {
            if (err) throw err;
            console.log("파일에 주소 입력 성공")
          }
        )
      }
    })
}

truffle을 통해 스마트컨트랙트를 배포하기 위한 코드를 작성합니다.

truffle.js

// truffle.js config for klaytn.
const PrivateKeyConnector = require('connect-privkey-to-provider')
const NETWORK_ID = '1001' // 바오밥 고유 네트워크 아이디
const GASLIMIT = '20000000'
const URL = 'https://api.baobab.klaytn.net:8651' // 현재 바오밥 풀노드가 돌아가고 있는 네트워크의 주소
const PRIVATE_KEY = '0xe6f37c636abd4c82c06d5b04018edff6ae0627fa0cbe0ce1d949d92acae7018e'

module.exports = {
  networks: {
    klaytn: {
      provider: new PrivateKeyConnector(PRIVATE_KEY, URL),
      network_id: NETWORK_ID,
      gas: GASLIMIT,
      gasPrice: null,
    }
  }
}

truffle의 config 설정을 위한 코드를 작성합니다.

Baobab에 배포

deploy

truffle deploy --network klaytn

위 코드를 터미널에 입력하여 스마트컨트랙트를 배포합니다.

<UI 제작>

ui

다음과 같이 UI를 구성합니다. 해당 페이지에 배포된 컨트랙트의 블록넘버가 홀수인지, 짝수인지 정하고, 정한 곳의 아래에 배팅할 금액을 peb 단위로 입력한 후 베팅 버튼을 누릅니다. 만약 정답을 맞추면 로그인한 Wallet 계정으로 베팅한 금액의 2배에 해당하는 금액이 전송됩니다.

function checkUser(address _addr) public view returns(bool){
    if(isUser[_addr] == getBlockNumber()){
        return false;
    }
    else{
      return true;
    }
}

SippingGame 컨트랙트 코드에 존재하는 다음 코드에 의해서, 한번 정답을 맞춘 블록에 존재하는 컨트랙트는 다시 정답을 맞출 수 없습니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment