[BlockChain] truffle로 스마트컨트랙트 배포하기

2022. 12. 5. 22:06·개발/BlockChain
728x90
반응형

1. geth

geth --datadir node --http --http.addr "127.0.0.1" --http.port 8000 --http.corsdomain "*" \--http.api "admin,eth,debug,miner,net,txpool,personal,web3" --syncmode full --networkid 1234 \--port 30300 --ws --ws.addr "127.0.0.1" --ws.port 8001 --ws.origins "*" \--ws.api "admin,eth,debug,miner,net,txpool,personal,web3" \--allow-insecure-unlock --unlock "0,1" --password "./node/password.txt"

2. truffle

트러플 :  Dapp 개발을 하는데 도와주는 블록체인 프레임워크

블록체인에서 스마트컨트랙트를 컴파일하고 배포할때 복잡한 구조를 추상화 시켜주는 역할이다.

트러플을 사용해서 이더리움 디앱 개발을 쉽게 할수 있다.

npm i truffle

트러플 초기화

npx truffle init

초기화를 하면 폴더들이 생긴다

contracts : 스마트 컨트랙트 코드를 작성하는 폴더

migrations : 배포 관련 코드를 컨트랙트별로 모으는 폴더

test : 스마트 컨트랙트 테스트 코드 작성하는 폴더

truffle-config.js : 트러플 환경설정 파일

build : 컨트랙트 코드를 컴파일하면 build폴더안에 컴파일한 내용을 가지고 있는 json파일이 생성된다.

 

컴파일 명령어

npx truffle compile

 

컴파일은 contracts폴더에 스마트컨트랙트 코드를 작성하고 실행할 것이다.

 

3. truffle-config.js

기타 주석들 다 날려주고 아래와 같이 작성했다.

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      // ws port 입력
      port: 8001,
      network_id: "*",
      websockets: true,
    },
  },
  compilers: {
    solc: {
      version: "0.8.17",
    },
  },
};

host : 주소

port : 포트번호

network_id : 모든 네트워크에서 접근 설정

이 3가지는 필수적으로 적어줘야 한다.

4. contract 작성

/contracts/HelloWorld.sol

// SPDX-License-Identifier:MIT
pragma solidity ^0.8.17;

contract HelloWorld{
    string public value;
    constructor(){
        value = "hi";
    }

    function setValue (string memory v) public{
        value =  v;
    }
}

5. 배포

/migrations/2_deploy_HelloWorld.js

const helloWorld = artifacts.require("HelloWorld");

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

배포관련 코드를 작성하는 파일 이름 양식 : 번호_내용_컨트랙트이름.js

 

배포 명령어

npx truffle migration

6. 배포한 컨트랙트 확인

트러플 콘솔창을 사용해서 명령어로 확인할 수 있다.

npx truffle console

배포한 컨트랙트 CA확인

HelloWorld.address

배포된 상태변수 가져오기

hello.value.call()

배포된 setValue 실행시키기

hello.setValue('dfiajdf');

setValue함수를 호출 후 실행해서 트랜잭션을 발생시키고 txpool에 담겨있는 트랜잭션을 처리(마이닝)해서 확인한다.

 

인스턴스 담아주기

HelloWorld.deployed().then(instance => hello = instance)

hello라는 변수에 인스턴스를 담아줬다.

7. test

/test/HelloWorld.test.js

const helloWorld = artifacts.require("HelloWorld");

contract("HelloWorld", (account) => {
  console.log(account);

  let hello;
  describe("hello contract", () => {
    it("contract", async () => {
      hello = await helloWorld.deployed();
    });
    it("get value", async () => {
      console.log(await hello.value.call());
    });
    it("set value", async () => {
      await hello.setValue("dasdf");
      console.log(await hello.value.call());
    });
  });
});

테스트 코드 실행 명령어

npx truffle test

test실행 후 txpool에 pending되어있는 트랜잭션을 마이닝 해줘야 넘어간다.

 

728x90
반응형

'개발 > BlockChain' 카테고리의 다른 글

[BlockChain] 메타마스크 토큰추가  (1) 2022.12.06
[BlockChain] ganache, react, express로 메타마스크 연결하기  (0) 2022.12.05
[BlockChain] 스마트 컨트랙트 배포  (0) 2022.12.05
[BlockChain] solidity 컴파일  (1) 2022.12.05
[BlockChain] geth  (0) 2022.11.28
'개발/BlockChain' 카테고리의 다른 글
  • [BlockChain] 메타마스크 토큰추가
  • [BlockChain] ganache, react, express로 메타마스크 연결하기
  • [BlockChain] 스마트 컨트랙트 배포
  • [BlockChain] solidity 컴파일
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
    • 팀플
  • 링크

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
TeTedo.
[BlockChain] truffle로 스마트컨트랙트 배포하기
상단으로

티스토리툴바