[Moralis] NodeJS 프로젝트로 이더리움 balance 가져오기

jhcha·2023년 8월 20일
0

DApp

목록 보기
5/9
post-thumbnail

이번 글에서는 DApp NodeJS 프로젝트에서 Moralis를 사용하여 이더리움 잔액을 조회하는 튜토리얼을 진행한다.

가장 먼저, Moralis 플랫폼 회원가입을 진행한다.
https://moralis.io/

Moralis 회원가입

  • Sign in Moralis

  • Moralis 프로젝트 생성 완료

Node.js 모랄리스 서버 생성

다음은 모랄리스 공식 문서, Quickstart NodeJS 내용을 참고하여 모랄리스를 사용한다.

  • 프로젝트 생성
npm init
  • express, moralis 라이브러리 추가
npm install moralis express @moralisweb3/common-evm-utils
  • index.js 파일 생성하고, npm start 추가해서 실행 환경 구축
// index.js
const express = require("express");
const app = express();
const port = 3535;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
//package.json
"scripts": {
	"start": "node src/index.js",
}
  • 브라우저로 실행 확인
npm run start

  • Moralis API Key 가져오기

    모랄리스 프로젝트 > Settings > Secrets에서 Web3 API Key 값을 복사한다.
const MORALIS_API_KEY = "";
const address = "0xf2E20495012CF25dEDEF60b238fCE966252609E6";
  • native (ether) 가져오기
// Get native balance
async function getDemoData() {
  const nativeBalance = await Moralis.EvmApi.balance.getNativeBalance({
    address,
    chain,
  });
  const native = nativeBalance.result.balance.ether;
  return native
}

app.get("/demo", async (req, res) => {
  try {
    // Get and return the crypto data
    const data = await getDemoData();
    res.status(200);
    res.json(data);
  } catch (error) {
    // Handle errors
    console.error(error);
    res.status(500);
    res.json({ error: error.message });
  }
});
  • 조회한 address 잔액 조회 확인

모랄리스 회원가입 후 간단하게 NodeJS 서버를 생성하고 Moralis API를 통해 이더 잔액을 조회할 수 있다.

참고자료: https://docs.moralis.io/web3-data-api/evm/quickstart-nodejs

0개의 댓글

관련 채용 정보