본문 바로가기
  • 개발 / 공부 / 일상
BlockChain

(BlockChain) Metamask 내장 객체 사용하기

by JJeongHyun 2023. 2. 13.
반응형

Web3 라이브러리를 사용하기 앞서서 metamask에서 기본적으로 제공해 주는 객체 사용법!

ethereum 객체 사용 하지 않았을 때 요청 방식

ethereum 객체 사용 시 요청 방식

ethereum 객체 사용 시 요청 방식

 

  • metaMask 객체
console.log(window.ethereum);

window.ethereum 결과 창

  • metaMask 연결 확인
if(window.ethereum){
	const isConnected = window.ethereum.isConnected();
	console.log("JS 읽자 마자 isConnected : ", isConnected);
}

window.ethereum.isConnected 결과

 

  • 이벤트 등록
    • connect : 연결됐을 때
if (window.ethereum) {
  const isConnected = window.ethereum.isConnected();
  console.log("JS Onload isConnected : ", isConnected);

  ethereum.on("connect", async (connectInfo) => {
    console.log(connectInfo);
    console.log(connectInfo.chainId);

    const isConnected = window.ethereum.isConnected();
    console.log("After connect isConnected : ", isConnected);
	}
}

ethereum.on ("connect") console.log 결과

  • disconnect : 연결이 끊어 졌을 때
ethereum.on("disconnect", handler : (error:ProviderRpcError)=>void)
 interface ProviderRpcError extends Error{
    code:number;
    data?:unknown;
 }

 

  • accountsChange: 계정이 변경되었을 때
ethereum.on("accountsChanged", (accounts) => {
    console.log(accounts);
}

accountsChanged console.log 결과
metaMask에서 주소값이 console.log에 출력된 주소값과 일치

 

  • chainChange : 블록체인 네트워크(체인) 변경되었을 때
ethereum.on("chainChanged", (chainId) => {
    console.log(chainId);
  });

chainChanged console.log 결과 창 (좌 : 이더리움 메인넷, 우 : ganache )
좌) Ethereum MainNet 우) ganache Chain

 

  • metaMask RPC 요청
    • eth_getBalance : 잔액 조회
<html lang="ko">
  <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>metamask</title>
  </head>
  <body>
    <h3 id="balance"></h3>
    <script src="./metamask.js"></script>
  </body>
</html>
const balanceElem = document.getElementById("balance");

const balance = await ethereum.request({
      method: "eth_getBalance",
      params: ["0x36bAe4f6689c33DC2A18D3420A73eC5C37f4ab6E"],
});
balanceElem.innerHTML = `잔액 : ${parseInt(balance) / Math.pow(10, 18)}ETH `;

eth_getBalance HTML 출력
출력된 잔액이 metaMask 잔액과 일치 여부 확인

 

  • eth_chainId : 체인 아이디 조회
const tempChainId = await ethereum.request({
      method: "eth_chainId",
});
console.log("chainId : ", tempChainId);

chainId console.log 창

  • eth_requestAccounts 
    • 메타마스크 프로그램의 계정 조회
    • 보안 정책 상의 문제로 현재 선택한 계정 주소만 가져온다
const tempRequestAccounts = await ethereum.request({
      method: "eth_requestAccounts",
});
console.log("requestAccounts : ", tempRequestAccounts);

eth_requestAccounts console.log 결과 확인

'BlockChain' 카테고리의 다른 글

(BlockChain) Web3 라이브러리 (ws)  (0) 2023.02.15
(BlockChain) Web3 라이브러리  (0) 2023.02.14
(BlockChain) Web3  (0) 2023.02.13
(BlockChain) Ganache  (0) 2023.02.10
(BlockChain) MetaMask axios 통신  (0) 2023.02.09