본문 바로가기
JavaScript

[JavaScript] 이더리움 블록 조회하는 간단한 사이트 만들기

by teamnova 2023. 12. 26.

 

오늘은 이더리움의 블록을 조회하는 간단한 사이트를 만들어보겠습니다.

이번 실습에서는 서버로 node.js를 사용하기 때문에, node.js가 설치 되어 있어야 합니다.

인퓨라(https://app.infura.io/dashboard)로 이동하셔서 로그인 하신 후 API key를 발급받으셔야합니다.

web3 api으로 선택하셔서 Ethereum으로 발급된 key를 복사해주세요.

발급받을 때 형식은 'https://mainnet.infura.io/v3/~~~~~~'이라면 정상입니다.

 

 

 

API키 생성
이더리움의 API 키 복사

 

 

 

 

 

 

여기부터는 프로젝트 파일 구조 및 코드입니다.

프로젝트 구조. 파일들을 이미지와 같이 배치하세요.

index.html

<!--public/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ethereum Block Explorer</title>
</head>
<body>
<h1>Ethereum Block Explorer</h1>
<input type="number" id="blockNumber" placeholder="Block Number" />
<button onclick="getBlock()">Get Block</button>
<pre id="result"></pre>
<script>
    async function getBlock() {
        const blockNumber = document.getElementById('blockNumber').value;
        if (!blockNumber) {
            alert('Please enter a block number');
            return;
        }

        try {
            const response = await fetch(`/block/${blockNumber}`);
            const blockString = await response.text();
            const block = JSON.parse(blockString, (key, value) => {
                if (typeof value === 'string' && value.endsWith('n')) {
                    return BigInt(value.slice(0, -1));
                }
                return value;
            });
            console.log(" block : ");
            console.log(block);
            document.getElementById('result').textContent = JSON.stringify(block, null, 2);
        } catch (error) {
            console.error('Error fetching block:', error);
            alert('Error fetching block. Check the console for more details.');
        }
    }
</script>
</body>
</html>

 

 

app.js

// app.js
const express = require('express');
const app = express();
const {Web3} = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/발급받은 키 삽입');

app.use(express.static('public'));
app.get('/block/:blockNumber', async (req, res) => {
    try {
        console.log(" blockNumber : " + req.params.blockNumber);
        const block = await web3.eth.getBlock(req.params.blockNumber);
        console.log(" block : ");
        console.log(block);

        const blockString = JSON.stringify(block, (key, value) =>
            typeof value === 'bigint' ? value.toString() : value
        );
        res.setHeader('Content-Type', 'application/json');
        res.send(blockString);
    } catch (error) {
        console.error(error);
        res.status(500).send(error.toString());
    }
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

 

 

 

package.json

{
  "name": "js-search-block-info-ethereum",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^4.18.2",
    "web3": "^4.2.1"
  }
}