본문 바로가기

블록체인 개발

Klaytn Study - caver.js 와 webpack 5 호환 문제 해결

728x90
반응형

Klaytn 스터디를 하는 도중에

caver.js 를 react에서 사용하려는데 실행이 안되서 한참동안 삽질 했다.

아래 내용을 실행하는데, webpack <5 어쩌구 저쩌구

If you want to include a polyfill, you need to:
- add a fallback ‘resolve.fallback: { “http”: require.resolve(“stream-http”) }’
- install ‘stream-http’
If you don’t want to include a polyfill, you can use an empty module like this:
resolve.fallback: { “http”: false }

같은 에러들이 뜨면서 실행이 제대로 되지 않았다.

 

import logo from "./logo.svg";
import { Buffer } from "buffer";
import Caver from "caver-js";
import "./App.css";

const COUNT_CONTRACT_ADDRESS = "0x13FE7f024164B388183175018B8Ed7bfeb7af2c2";
const ACCESS_KEY_ID = "";
const SECRET_ACCESS_KEY = "";
const CHAIN_ID = "1001"; // MAINNET 8217 TESTNET 1001
const COUNT_ABI =
  '[ { "constant": true, "inputs": [], "name": "count", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getBlockNumber", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_count", "type": "uint256" } ], "name": "setCount", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]';

const option = {
  headers: [
    {
      name: "Authorization",
      value:
        "Basic " +
        Buffer.from(ACCESS_KEY_ID + ":" + SECRET_ACCESS_KEY).toString("base64"),
    },
    { name: "x-chain-id", value: CHAIN_ID },
  ],
};

const caver = new Caver(
  new Caver.providers.HttpProvider(
    "https://node-api.klaytnapi.com/v1/klaytn",
    option
  )
);
const CountContract = new caver.contract(
  JSON.parse(COUNT_ABI),
  COUNT_CONTRACT_ADDRESS
);
const readCount = async () => {
  const _count = await CountContract.methods.count().call();
  console.log(_count);
};

const getBalance = (address) => {
  return caver.rpc.klay.getBalance(address).then((response) => {
    const balance = caver.utils.convertFromPeb(
      caver.utils.hexToNumberString(response)
    );
    console.log("BALANCE: " + balance);
    return balance;
  });
};

// 1 Smart contract 배포 주소 파악(가져오기)
// 2 caver.js 이용해서 스마트 컨트랙트 연동하기
// 3 가져온 스마트 컨트렉트 실행 결과(데이터) 웹에 표현하기

function App() {
  readCount();
  getBalance("0xfdb8c7ca38d425b35d84feb2aa5d026c15cf7141");
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          GOOD <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;


이것저것 검색해본 결과

webpack 버전 5 이상에서는 caver.js 가 호환이 되지 않아 따로 어떤 것들을 처리해줘야 한단다.

관련 내용을 클레이튼 포럼에서 찾아서 참고하여 해결하였다.

관련 클레이튼 포럼 참고 링크 : https://forum.klaytn.com/t/caver-js/3520

1.  관련 모듈들 설치.

npm install steam-browserify

npm install crypto-browserify

npm install stream-http

npm install https-browserify

npm install os

 

2. npm run eject 실행 (에러가 발생할 경우 git init, git commit 까지 하면 해결됨.

돌리고 나면 root 폴더에 config 폴더가 자동으로 생성되고, 그 안에 webpack.config.js 파일이 자동 생성된다.

참조 : https://helloinyong.tistory.com/174

 

3.  참조에 있는 내용을 webpack.config.js 파일에 추가해준다. 아래 그림은 직접 파일에 추가해준 내용.

참조 : https://github.com/klaytn/caver-js#using-webpack--5

4. 다음을 install. 이건 꼭 해야되는지는 모르겠음.

npm install webpack

npm install webpack-cli

npm install webpack-dev-server

 

이러고 실행하면 error는 사라졌는데 그림이 뜨지 않았다.

확인해보니 브라우저에서 buffer is not defined 에러가 발생하였다.

이것은 

npm install --save buffer 를 하고

코드 위에 import {Buffer} from 'buffer'; 를 추가하니 해결되었다.

참조 링크 : https://stackoverflow.com/questions/67804053/uncaught-referenceerror-buffer-is-not-defined-in-react

반응형