Node.js Web3.js 로 이더리움 테스트넷 Rinkeby연결하기 (by INFURA) - Ganache 단점
본문 바로가기
Block Chain

Node.js Web3.js 로 이더리움 테스트넷 Rinkeby연결하기 (by INFURA) - Ganache 단점

by 쏠수있어ㅤ 2022. 3. 28.
반응형

이더스캔과 같은 익스플로어(explorer)를 만드는데 ganache로 가상 블록체인을 띄웠더니 여러 단점들이 있었다. 

 

1. 하나의 블록에 하나의 트랜잭션만 가능하다. 

2. ganache 터미널창을 실수로 끄게되면 또는 컴퓨터 전원을 끄게되면 해당 블록들과 트랜잭션들이 모두 날아간다.  

-> 만약 ganache 블록체인 상에 스마트 컨트랙트를 일으켜 토큰 발행을 했다면 이것도 날아가버린다. 

 

그래서 이더리움의 여러 테스트넷 중 이더리움 측에서 직접 만든 Rinkeby 테스트 넷을 사용하게 되었다. 

이를 위한 전제 조건은 

 

1. Ethereum test net node (우리는 Infura.io를 사용할 예정) 

2. 최신 Node.js 설치 (나의 node version : v16.13.1) 

3. Web3 설치 

 

이렇게 세 가지이다. 모두 설치 및 세팅이 되어 있는 상태에서 이제 Infura.io 사이트에 가서 무료 회원가입 후 web3 provider로 연결할 주소를 구하면 된다. 

 

이더리움 새 프로젝트를 만들고 settings에 들어가 ENDPOINTS를 Rinkeby로 변경한다. 

그러면 바로 아래에 두 가지 (https, wss 용) 의 주소가 나오고 나는 https 주소를 사용했다. 이를 복사해서 web3 를 연결하는 코드에 넣어주면 된다. 

 

참고한 코드 👇

const Web3 = require("web3");
const ethNetwork = 'https://rinkeby.infura.io/v3/YOUR_PROJECT_ID';

try {
        const web3 = new Web3(new Web3.providers.HttpProvider(ethNetwork));
        console.log("Connection Successfull!");
        console.log("Latest Block Number: ");
        web3.eth.getBlockNumber().then(console.log);
}
catch(e) {
        console.log("Connection Error!", e);
}

 

사용한 나의 코드 👇

import Web3 from "web3";

const ethNetwork = 'https://rinkeby.infura.io/v3/YOUR-PROJECT-ID';  //<- 자동으로 되어있음

const getWeb3 = () =>
  new Promise((resolve, reject) => {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    window.addEventListener("load", async () => {
        const provider = new Web3.providers.HttpProvider(
            ethNetwork
        );
        const web3 = new Web3(provider);
        console.log("No web3 instance injected, using Local web3.");
        resolve(web3);
    });
  });

export default getWeb3;

YOUR-PROJECT-ID 부분은 복사할 때 이미 자동으로 내 ID로 설정되어 있다. 

이렇게 하니 연결되어 테스트넷의 블록들, 트랜잭션들을 마음껏 사용할 수 있었다.  후 이제 속이 쉬원

 

 

 

 

 

 

 

 

References : https://codeforgeek.com/how-to-connect-to-the-ethereum-network-using-node-and-web3/

 

How to Connect to the Ethereum Network using Node and Web3 | CodeForGeek

In order to build a decentralized application, we need to connect to the Ethereum (or other) blockchain. In this tutorial, we are going to learn how to

codeforgeek.com

 

반응형

댓글