블록체인/WEB3 개발

서버에서 Web3.js 라이브러리 사용하기

제이제이_은재 2022. 8. 2. 17:40
반응형

 

💡 서버에서 Web3.js 라이브러리 사용하기

 

- web3.js 공식문서

- web3.js 콘텐츠 레퍼런스 코드

 

✓ 서버 구축하기

 

프로젝트를 위한 폴더 beb-sprint-web3js를 생성 후 터미널에서 npm init 명령어를 통해 노드 프로젝트를 시작한다.

mkdir beb-sprint-web3js
cd beb-sprint-web3js
npm init

 

npm을 통해 express와 web3를 설치한다.

 

npm install express
npm install web3

 

프로젝트에 Index.js 파일을 만들어 다음 내용을 입력한다. 

 

const express = require("express");
const app = express();
const port = 8080;

app.get("/", (req, res) => {
    res.send("Hello Node.js!");
});
app.listen(port, () => {
    console.log("Listening...");
});

 

package.json 파일에서 sciprts 항목에 start를 추가한다. 

 

"scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

npm start로 서버를 실행하여 서버가 잘 동작하는지 확인한다.

 

기본 서버 구성은 완료!

 

 

✓ 로컬 블록체인 네트워크와 서버 연결하기

 

가나슈를 실행 후 자신의 RPC 서버를 확인한다.

const express = require("express");
const app = express();
const port = 8080;
const Web3 = require("Web3");

function getWeb3() {
    const web3 = new Web3(
        new Web3.providers.HttpProvider("http://127.0.0.1:7545")
    );
    return web3;
}

async function getAccounts() {
    try {
        const accounts = await getWeb3().eth.getAccounts();
        console.log(accounts);
        return accounts;
    } catch (e) {
        console.log(e);
        return e;
    }
}

app.get("/", (req, res) => {
    getAccounts().then((accounts) => {
        res.send(accounts);
    });
});
app.listen(port, () => {
    console.log("Listening...");
});

 

코드 작성 후 서버를 실행한다. 이후 http://localhost:8080/ 으로 접속하면 Acoount에 관한 계정정보를 웹과 콘솔에서 확인할 수 있다.

 

 

위와 같은 방식으로 로컬 네트워크에서 web3 라이브러리를 활용할 수 있다. 

 

- 노드 관련 라이브러리: web3.eth, web3.eth.subscribe

- 컨트랙트 관련 라이브러리: web3.eth.Contract, web3.eth.abi

- 계정, 지갑 관련 라이브러리: web3.eth.accounts

- 트랜잭션 관련 라이브러리: web3.eth.personal

- 이더리움이 아닌 다른 블록체인 네트워크를 추가하여 사용하는 경우: web3.*.net

- 암호화 등 유틸 라이브러리: web3.utils

- web3.eth.ens

- web3.eth.lban

 

 

✓ web3.eth.getBlock(blockHashOrBlockNumber) - 블록 정보

 

web3.eth.getBlock(blockHashOrBlockNumber) 는 블록 정보를 가져오기 위한 함수이다. 인자로는 블록의 해시값이나 블록 숫자를 넣을 수 있으며, String, Number, BN, BigNumber 타입으로 넣어야 한다. String 타입으로 값을 넣을 때는 "earliest", "latest", "pending"을 사용하여 제네시스 블록, 최신 블록, 펜딩 상태인 블록을 넣을 수 있다. 

 

const express = require("express");
const app = express();
const port = 8080;
const Web3 = require("Web3");

function getWeb3() {
    const web3 = new Web3(
        new Web3.providers.HttpProvider("http://127.0.0.1:7545")
    );
    return web3;
}

async function getBlock() {
    try {
        const getBlock = await getWeb3().eth.getBlock("latest");
        console.log(getBlock);
        return getBlock;
    } catch (e) {
        console.log(e);
        return e;
    }
}

async function getAccounts() {
    try {
        const accounts = await getWeb3().eth.getAccounts();
        console.log(accounts);
        return accounts;
    } catch (e) {
        console.log(e);
        return e;
    }
}
app.get("/", (req, res) => {
    getAccounts().then((accounts) => {
        res.send(accounts);
    });
});
app.get("/getblock", (req, res) => {
    getBlock().then((getBlock) => {
        res.send(getBlock);
    });
});
app.listen(port, () => {
    console.log("Listening...");
});

 

getBlock() 함수는 web3.eth.getBlock() 함수를 사용하여 최신 블록을 반환한다. 그리고 서버에는 GET /getblock 요청에 대한 응답으로 getBlock()의 결과값을 리턴한다.

 

다양한 함수에 대한 정보는 web3.js 공식 문서를 통해 확인할 수 있다.

 

https://web3js.readthedocs.io/en/v3.0.0-rc.5/

 

web3.js - Ethereum JavaScript API — web3.js 1.0.0 documentation

© Copyright 2016, Ethereum Revision 1c2edcc9.

web3js.readthedocs.io

 

반응형