Caver js의 decryptKey를 호출할 경우 다음과 같은 오류가 발생합니다

ReferenceError: Buffer is not defined
at decryptKey (index.js:1453:1)
at Accounts.decrypt (index.js:1434:1)
at Object.handleLogin (CustomCaver.js:71:1)
at onClick (NftTestPage.js:91:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070:1)
at executeDispatch (react-dom.development.js:8243:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:8275:1)

혹시 아래 해당문서를 참고하셨나요?

개인정보를 제외한 사용하신 코드를 같이 공유해주시면 답변에 도움드릴수있을것같습니다.

1 Like

아래와 같은 코드를 사용 중입니다.
/**

  • caver-js 라이브러리는 Klaytn 노드에 연결하게 해줍니다.

  • ‘rpcURL’ 값을 변경하여 특정 Klaytn 노드에 연결할 수 있습니다.

  • Klaytn 풀노드를 운용 중이라면 rpcURL을 운용 중인 풀노드의 URL로 설정하세요.

  • ex) rpcURL: ‘http://localhost:8551

*/

const Caver = require(“caver-js”);

const Util = require("…/common/Util");

const { parse } = require(“url”);

const config = {

rpcURL: “https://api.baobab.klaytn.net:8651/”,

};

const cav = new Caver(config.rpcURL);

// const agContract = new cav.klay.Contract(DEPLOYED_ABI, DEPLOYED_ADDRESS);

const auth = {

accessType: “keystore”,

keystore: “”,

password: “”,

};

const start = async function () {

const walletFromSession = sessionStorage.getItem(“walletInstance”);

if (walletFromSession) {

try {

  cav.klay.accounts.wallet.add(JSON.parse(walletFromSession));

  this.changeUI(JSON.parse(walletFromSession));

} catch (e) {

  sessionStorage.removeItem("walletInstance");

}

}

};

const handleImport = async function (event, onSuccess, onFail) {

const fileReader = new FileReader();

fileReader.readAsText(event.target.files[0]);

fileReader.onload = (event) => {

try {

  const isValid = checkValidKeystore(event.target.result);

  console.log(isValid);

  if (isValid) {

    auth.keystore = event.target.result;

    onSuccess();

  } else {

    onFail();

    return;

  }

} catch (event) {

  console.log(event);

  onFail();

  return;

}

};

};

exports.handleImport = handleImport;

const handlePassword = async function (event) {

auth.password = event.target.value;

};

exports.handlePassword = handlePassword;

const handleLogin = async function (onSuccess, onFail) {

if (auth.accessType === “keystore”) {

try {

  onSuccess();

  console.log(auth.keystore);

  console.log(auth.password);

  const privateKey = cav.klay.accounts.decrypt(

    auth.keystore,

    auth.password

  ).privateKey;

  // integrateWallet(privateKey);

} catch (e) {

  console.log(e);

  onFail();

}

}

};

exports.handleLogin = handleLogin;

const handleLogout = async function () {

this.removeWallet();

window.location.reload();

};

exports.handleLogout = handleLogout;

const generateNumbers = async function () {

var num1 = Math.floor(Math.random() * 50 + 10);

var num2 = Math.floor(Math.random() * 50 + 10);

sessionStorage.setItem(“result”, num1 + num2);

// $("#start").hide();

// $("#num1").text(num1);

// $("#num2").text(num2);

// $("#question").show();

// document.querySelector("#answer").focus();

// this.showTimer();

};

exports.generateNumbers = generateNumbers;

const submitAnswer = async function () {};

exports.submitAnswer = submitAnswer;

const deposit = async function () {

// var spinner = this.showSpinner();

// const walletInstance = this.getWallet();

// if (walletInstance) {

// if ((await this.callOwner()) !== walletInstance.address) return;

// else {

// var amount = $("#amount").val();

// if (amount) {

// agContract.methods

// .deposit()

// .send({

// from: walletInstance.address,

// gas: “200000”,

// value: cav.utils.toPeb(amount, “KLAY”),

// })

// .once(“transactionHash”, (txHash) => {

// console.log(txHash: ${txHash});

// })

// .once(“receipt”, (receipt) => {

// console.log((#${receipt.blockNumber}), receipt); //Received receipt! It means your transaction(calling plus function) is in klaytn block

// spinner.stop();

// alert(amount + " KLAY를 컨트랙에 송금했습니다.");

// location.reload();

// })

// .once(“error”, (error) => {

// alert(error.message);

// });

// }

// return;

// }

// }

};

const callOwner = async function () {

// return await agContract.methods.owner().call();

};

const callContractBalance = async function () {

// return await agContract.methods.getBalance().call();

};

const getWallet = function () {

if (cav.klay.accounts.wallet.length) {

return cav.klay.accounts.wallet[0];

}

};

const checkValidKeystore = function (keystore) {

const parsedKeystore = JSON.parse(keystore);

const isValidKeystore =

!Util.checkEmpty(parsedKeystore.version) &&

!Util.checkEmpty(parsedKeystore.id) &&

!Util.checkEmpty(parsedKeystore.address) &&

!Util.checkEmpty(parsedKeystore.keyring);

console.log(isValidKeystore);

return isValidKeystore;

};

const integrateWallet = function (privateKey) {

const walletInstance = cav.klay.accounts.privateKeyToAccount(privateKey);

cav.klay.accounts.wallet.add(walletInstance);

sessionStorage.setItem(“walletInstance”, JSON.stringify(walletInstance));

changeUI(walletInstance);

};

const reset = function () {

this.auth = {

keystore: "",

password: "",

};

};

const changeUI = async function (walletInstance) {

console.log(“change UI”);

// $("#loginModal").modal(“hide”);

// $("#login").hide();

// $("#logout").show();

// $("#game").show();

// $("#address").append(

// “
” + “

” + "내 계정 주소: " + walletInstance.address + “

// );

// $("#contractBalance").append(

// “

” +

// "이벤트 잔액: " +

// cav.utils.fromPeb(await this.callContractBalance(), “KLAY”) +

// " KLAY" +

// “

// );

// if ((await this.callOwner()) === walletInstance.address) {

// $("#owner").show();

// }

};

const removeWallet = function () {

cav.klay.accounts.wallet.clear();

sessionStorage.removeItem(“walletInstance”);

this.reset();

};

const showTimer = function () {

var seconds = 3;

// $("#timer").text(seconds);

// var interval = setInterval(function () {

// $("#timer").text(–seconds);

// if (seconds <= 0) {

// $("#timer").text("");

// $("#answer").val("");

// $("#question").hide();

// $("#start").show();

// clearInterval(interval);

// }

// }, 1000);

};

// const showSpinner = function () {

// var target = document.getElementById(“spin”);

// return new Spinner(opts).spin(target);

// };

const receiveKlay = function () {};

var opts = {

lines: 10, // The number of lines to draw

length: 30, // The length of each line

width: 17, // The line thickness

radius: 45, // The radius of the inner circle

scale: 1, // Scales overall size of the spinner

corners: 1, // Corner roundness (0…1)

color: “#5bc0de”, // CSS color or array of colors

fadeColor: “transparent”, // CSS color or array of colors

speed: 1, // Rounds per second

rotate: 0, // The rotation offset

animation: “spinner-line-fade-quick”, // The CSS animation name for the lines

direction: 1, // 1: clockwise, -1: counterclockwise

zIndex: 2e9, // The z-index (defaults to 2000000000)

className: “spinner”, // The CSS class to assign to the spinner

top: “50%”, // Top position relative to parent

left: “50%”, // Left position relative to parent

shadow: “0 0 1px transparent”, // Box-shadow for the lines

position: “absolute”, // Element positioning

};

코드상의 문제는 없어보이지만, 해당 에러가 브라우저내 버퍼가 정의되지 않았다는 부분 같습니다.

npm install --save buffer

위와 같이 브라우저 버퍼 페키지를 설치하고

(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
(window as any).process = {
  version: ''
};

이런식으로 광역변수에 Buffer를 정의해주시면 해결되지 않을까 생각됩니다.
일단 caver쪽 문제는 아닌것 같습니다.

제가 참고한 문서는 다음과 같습니다.

Angular 6 Uncaught ReferenceError: Buffer is not defined - Stack Overflow

웹팩5와 buffer 호환성 문제인 것으로 밝혀졌습니다.

2 Likes