블록체인/WEB3 개발

노드 RPC Call을 Infura를 통해 제어해보기

제이제이_은재 2022. 8. 3. 15:56
반응형

💡 노드 RPC Call을 Infura를 통해 제어해보기

 

Ganache를 이용해 로컬 네트워크 환경에 있는 스마트 컨트랙트를 Web3.js로 제어할 수 있다. 이 외에도 테스트넷 또는 메인넷에 있는 노드 RPC Call을 Infura라는 플랫폼을 통해 스마트 컨트랙트를 Web3.js로 제어할 수도 있다. 아래와 같이 진행하면 된다.

 

1. 먼저 Infura 프로젝트에서 ENDPOINTS를 ROPSTEN으로 설정한다.

 

 

 

 

 

2. Ropsten Network로 변경 후 Endpoints를 복사한다. 테스트를 위해 Remix를 통해 Ropsten Network에 Hello World를 배포한다.

 

 

3. 아래와 같이 ABI와 배포된 Contract Address를 복사해 다음과 같은 코드를 만든다.

 

const express = require("express");
const app = express();
const port = 8080;
const Contract = require("web3-eth-contract");

async function helloWorld() {
    try {
        const abi = [
            {
                inputs: [],
                name: "renderHelloWorld",
                outputs: [
                    {
                        internalType: "string",
                        name: "greeting",
                        type: "string",
                    },
                ],
                stateMutability: "pure",
                type: "function",
            },
        ];
        const address = "0x636403b086a25aDF415Bc9A68Ba407f851AFadc0"; // 자신의 컨트랙트 주소
        Contract.setProvider(
            "https://ropsten.infura.io/v3/{자신의 infura api key}"
        );
        const contract = new Contract(abi, address);
        const result = await contract.methods.renderHelloWorld().call();
        console.log(result);
        return result;
    } catch (e) {
        console.log(e);
        return e;
    }
}

app.get("/helloWorld", (req, res) => {
    helloWorld().then((result) => {
        res.send(result);
    });
});

app.listen(port, () => {
    console.log("Listening...");
});

setProvider에 로컬 호스트가 아닌 ropsten.infura.io/v3/~~ 가 들어가는 것도 확인할 수 있고 http://localhost:8080/helloWorld에 접속해 잘 동작하는지도 확인이 가능하다.

 

 

이와 같은 방법을 통해 Infura를 활용하여 Ropsten Network 테스트가 가능하다. 또한 Infura를 결제해 활용한다면 메인넷에서도 사용이 가능하다.

반응형