[BlockChain] 스마트 컨트랙트 배포

2022. 12. 5. 21:50·개발/BlockChain
728x90
반응형

1. controll/client.js, controll/compile.js 작성

(1) client.js

// npm i web3
const Web3 = require("web3");
let instance;

class Client {
  constructor(_url) {
    // instance의 내용이 있으면 내용이 이미 있는 instance 반환
    if (instance) return instance;

    // instance 내용이 없으면 동적 할당으로 생성한 Client 클래스 객체에 web3 생성
    this.web3 = new Web3(_url);
    // 생성후에 instance 변수에 Client 클래스 객체 할당
    instance = this;
  }
}

module.exports = { Client };

(2) compile.js

const solc = require("solc");
// fs-extra : node fs 모듈에 없는 추가적인 file 시스템 함수를 사용할수 있다.
// 종합버전이라고 생각하면 된다.
const fs = require("fs-extra");
const path = require("path");

class Contract {
  static compile(_filename) {
    const contractPath = path.join(__dirname, "../contracts", _filename);
    const source = fs.readFileSync(contractPath, "utf8");
    let solcInput = {
      language: "Solidity",
      sources: {
        contract: {
          content: source,
        },
      },
      settings: {
        optimizer: {
          enabled: true,
        },
        outputSelection: {
          "*": {
            "*": ["*"],
          },
        },
      },
    };

    solcInput = JSON.stringify(solcInput);
    // solc.compile : sol 파일을 컴파일 해주는 함수
    let contractObject = solc.compile(solcInput);
    contractObject = JSON.parse(contractObject);

    for (const key in contractObject.contracts) {
      const contractName = "HelloWorld";
      const contract = contractObject.contracts[key][contractName];
      const bytecode = contract.evm.bytecode.object;
      const abi = contract.abi;
      const obj = { abi, bytecode };
      const _path = path.join(__dirname, "../upload", `${contractName}.json`);
      fs.outputJSONSync(_path, obj);
      return [abi, bytecode];
    }
  }
}
Contract.compile("test.sol");
module.exports = { Contract };

2. keysotre

.puppeth/node/keysotre 폴더에 있는 UTC-- 파일 복사해오기

(1) privatekey.js

// keystore 파일 복사해서 가져오기

const keythereum = require("keythereum");
const path = require("path");

// keystore에 있는 address복사해서 가져오기  "0x복사한값"
const address = "0xadeb60c74af826c84ae94703e67d25a9a7e24e3d";

// 이 경로는 키파일 들어있는 폴더 상위까지 경로
const dir = path.join(__dirname);

// 키파일의 계정 정보 객체 만들기
const keyObject = keythereum.importFromFile(address, dir);
// importFromFile 계정 정보 만들어 주는 함수 매개변수 (주소, 경로)

const privateKey = keythereum.recover("1234", keyObject).toString("hex");
console.log("0x" + privateKey);

3. 배포

(1) geth 열기

뒤쪽 password.txt는 newAccount()로 계정만들시 입력했던 비밀번호를 넣어둔 파일이다.

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) index.js 작성

const client = new Client("ws://127.0.0.1:8001");

const contract = new client.web3.eth.Contract(abi);

const txObject = { data: bytecode };
const Address = "0xadeb60c74af826c84ae94703e67d25a9a7e24e3d";
async function init() {
  // deploy() : 반환값이 promise 객체
  // 트랜잭션이 처리 될때까지 기다린다.
  const instance = await contract.deploy(txObject).send({ from: Address });
  // 배포하고 메소드나 변수들을 가져와야하는데
  // 필요한게 contract address
  // instance 객체 안에 options.address 에 contract address가 들어있다.
  const CA = instance.options.address;
  console.log(CA);

  // 컨트랙트 조회해서 함수와 변수 가져오기
  // 필요한게 abi와 contract address
  const deployed = new client.web3.eth.Contract(abi, CA);
  // getter로 value값 가져옴
  deployed.methods
    .value()
    .call()
    .then((data) => {
      console.log(data);
    });

  deployed.methods.setValue("adsfasdf").send({ from: Address });
}
init();
// 오류나면 잔액이 없는 거니까 miner.start(1) 해준다
728x90
반응형

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

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바