브라우저 접속시 메타마스크 연동하기 / 잔액 조회

이재영·2023년 9월 26일
0

BlockChain

목록 보기
7/13
post-thumbnail

결과물


App.js

import { useEffect, useState } from "react";
import Web3 from "web3";
import "./App.css";

function App() {
 
  const [account, setAccount] = useState(null);
  const [web3, setWeb3] = useState(null);
  const [balance, setBalance] = useState(0);

  useEffect(() => {
    (async () => {
      const [data] = await window.ethereum.request({
        method: "eth_requestAccounts",
      });
      console.log("data : ", data);
      setWeb3(new Web3(window.ethereum));
      setAccount(data);
    })();
  }, []);

  const balanceBtn = async () => {
    const balance = await web3.eth.getBalance(account);
    const _balance = await web3.utils.fromWei(balance, "ether");
    setBalance(_balance);
  };

  return (
    <div className="App">
      {account || "login please"}
      <br />
      {balance} ETH
      <br />
      <button onClick={balanceBtn}>잔액 조회</button>
    </div>
  );
}

export default App;

동작설명

먼저, npm install web3 : web3 라이브러리 설치
useEffect []로 렌더링시 최초 실행.

즉시 실행함수로 한번만 실행되게끔 하고,

즉시 실행함수 형식

(() =>{
	//코드
})();

window.ethereum.request 메서드는 Ethereum 지갑에서 사용자의 Ethereum 계정에 접근하고 권한을 요청하는 데 사용된다.
여기서 method: "eth_requestAccounts"를 사용하면 사용자에게 Ethereum 계정에 대한 액세스 권한을 요청하는 메소드를 호출하게 되고, 이 요청을 통해 사용자에게 지갑의 로그인 창이 표시된다.

로그인을 하면, 지갑주소가 배열에 담겨 표시가 되기때문에 구조분해로 지갑주소를 가져온다.

setWeb3(new Web3(window.ethereum))
window.ethereum는 브라우저 환경에서 이더리움 네트워크로 접근할수 있는 provider 객체이고,
new Web3() 를 통해 web3 인스턴스 생성.

web3를 통해 Ethereum 블록체인과의 통신을 하고, 스마트 컨트렉트의 함수를 호출하거나 트랜잭션을 생성하는 데 사용한다.

profile
한걸음씩

0개의 댓글