관리 메뉴

개발이야기

[ 블록체인 개발 ] 메타마스크 Provider , Web3 사용법 본문

블록체인 /블록체인 개발

[ 블록체인 개발 ] 메타마스크 Provider , Web3 사용법

안성주지몬 2019. 4. 3. 00:00

보통 메타마스크가 설치되어 있는 브라우저에서 web3를 사용할 때 아래와 같이 코드를 작성합니다.

 

<코드>

window.addEventListener('load', () => {
  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    // Use Mist/MetaMask's provider
    web3js = new Web3(web3.currentProvider);
  } else {
    console.log('No web3? You should consider trying MetaMask!');
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    web3js = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
  }

  // Now you can start your app & access web3 freely:
  startApp();
});

여기서 의문점이 하나 생깁니다.

if (typeof web3 !== 'undefined') 에서 web3 라이브러리를 제가 설치한적도 없고 import 를 하지도 않았음에도 메타마스크만 깔려 있다면 web3 는 undefined 가 아닙니다.

 

어떻게 이런일이 일어나게 될까요.

web3 는 메타마스크에 의해 주입된 인스턴트이기 때문입니다.

이 인스턴트는 Ethereum JSON-RPC 메세지들만 다루는 로우레벨 provider API인데요.

 

메타마스크의 깃허브 공식 문서를 보면 아래의 문구가 있습니다.

 

"The provider API itself is very simple, and wraps Ethereum JSON-RPC formatted messages, which is why developers usually use a convenience library for interacting with the provider, like web3, truffle, ethjs, Embark, or others "

 

메타마스크가 기본적으로 제공하는 이 인스턴스는 정말 간단한 기능만이 구현되어 있다고 나와 있습니다. 따라서  provider API를 가지고 헬퍼 함수들을 제공하는 web3, truffle, ethjs, Embark 같은 라이브러리들을 사용하는게 개발을 할 때 더 유용합니다. 

 

 

레퍼런스

[1]  코드 참고 

https://medium.freecodecamp.org/every-blockchain-developer-should-know-these-web3-and-metamask-use-cases-7f93c1f139b1 

 

Every blockchain developer should know these Web3 and Metamask use cases

Metamask is the de facto standard for dApps on the web. It injects a Web3 instance into a window object making it available for JavaScript…

medium.freecodecamp.org

[2] 메타마스크 공식 문서

https://metamask.github.io/metamask-docs/API_Reference/Ethereum_Provider#api-reference

Comments