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

김도영·2022년 8월 1일
1

서버 구축하기

프로젝트를 위한 폴더 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 파일에 scripts 항목에 start를 추가한다.

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

npm start로 서버를 실행하고 http://localhost:8080에 접속하여 서버가 잘 동작하는지 확인한다.

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

먼저 가나슈(Ganache를 실행 후 자신의 RPC SERVER를 확인한다.

http://127.0.0.1:7545를 확인 후 서버에서 가나슈에 있는 계정을 가져온다.

const express = require('express');
const app = express();
const port = 8080;
const Web34 = 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();
      	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으로 접속하면 Account에 관한 계정 정보를 웹과 콘솔에서 확인할 수 있다.

web3.eth.getGasPrice() - 가스비 확인 함수

web3.eth.getGasPrice()는 가스비를 확인할 수 있는 함수이다. 블록체인 서비스를 제공할 때는 네트워크 사용량에 따라 변화하는 가스비를 책정해야 된다. 가스비를 잘못 책정하는 경우에는 트랜잭션을 실행하다가 가스비가 부족해지면 트랜잭션이 revert 되는 문제가 발생한다. 따라서 적절한 가스비를 계산해야하는 함수가 필요하다.

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

app.get('/gasprice', (req, res) => {
  	getGasPrice().then( (gasPrice) => {
      	res.send(gasPrice);
    })
})

getGasPrice()함수는 web3.eth.getGasPrice()함수를 사용하여 만든 가스비를 리턴한다. 그리고 서버에서는 GET /gasprice요청에 대한 응답으로 getGasPrice()의 결과값을 리턴한다. 이제 터미널에서 서버를 실행하고 http://localhost:8080/gasprice 에서 가스비를 받아오는것을 확인한다.

web3.eth.getBlock - 블록정보

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

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

app.get('/getblock', (req, res) => {
  	getBlock().then( (getBlock) => {
      	res.send(getBlock);
    })
})

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

profile
Blockchain Developer

1개의 댓글

comment-user-thumbnail
2023년 4월 2일

덕분에 도움 많이 됐습니다 :) 감사합니다

답글 달기