본문 바로가기
블록체인

MetaMask Docs (Methods &&Events)

by 위그든씨 2023. 3. 24.

MetaMask Docs

1. ethereum.isConnected() 

ethereum.isConnected(): boolean;
/**
If the provider is not connected, the page will have to be reloaded in order for connection to be re-established. 
Please see the connect and disconnect events for more information.
*/

2. ethereum.request(args) 

interface RequestArguments {
  method: string;
  params?: unknown[] | object;
  			//The params and return value will vary by RPC method. 
            //If a method has any params, they are almost always of type Array<any>.
}

ethereum.request(args: RequestArguments): Promise<unknown>;

// Metamask는 가장 기본적인 이더리움 RPC 메서드를 지원함. 다른 지갑에서는 지원하지 않는
// https://docs.metamask.io/guide/rpc-api.html 여기에서 메타마스크 디테일 확인

eg) 

params: [
  {
    from: '0xb60e8dd61c5d32be8058bb8eb970870f07233155',
    to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567',
    gas: '0x76c0', // 30400
    gasPrice: '0x9184e72a000', // 10000000000000
    value: '0x9184e72a', // 2441406250
    data:
      '0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675',
  },
];


ethereum
  .request({
    method: 'eth_sendTransaction',
    params,
  })
  .then((result) => {
    // This method will return a transaction hash hexadecimal string on success.
  })
  .catch((error) => {
    // If the request fails, the Promise will reject with an error.
  });

3. Event 

interface ConnectInfo {
  chainId: string;
}

interface ProviderMessage {
  type: string;
  data: unknown;
}

ethereum.on('message', handler: (message: ProviderMessage) => void);
	// 메시지의 종류는 type 에 의해 분류됨
    

ethereum.on('accountsChanged', (accounts) => {
  	// "accounts" 는 배열이거나 비었음
    // 가장 최근에 사용된 계정의 주소를 리턴함
});

ethereum.on('chainChanged', (chainId) => {
  	// 합당한 이유 있는거 아니면 window.location.reload() 를 수행하길 추천함
    // All RPC requests are submitted to the currently connected chain. 
    // Therefore, it's critical to keep track of the current chain ID by listening for this event.
});

ethereum.on('connect', handler: (connectInfo: ConnectInfo) => void);
	//ethereum.isConnected() 메서드를 수행하는 것보다 connect를 더 추천함 

ethereum.on('disconnect', handler: (error: ProviderRpcError) => void);


ethereum.removeListener('accountsChanged', handleAccountsChanged);
	// 리스닝 끝났다면 listeners 제거하는거 잊지말아라 
	// 두번째 인자로 오는 함수는 ethereum.on 에 대한 event 를 다루는 함수 이름과 같아야함.

 

4. Error 

interface ProviderRpcError extends Error {
  message: string;
  code: number;
  data?: unknown;
}

	// 4001: user에 의해 req가 거절됨
	//-32602: 파라미터가 유효하지 않음
	//-32603: 내부 에러

 

'블록체인' 카테고리의 다른 글

[블록체인] 용어 정리 (ing)  (1) 2023.03.13
[블록체인] Ether.js provider, signer  (0) 2023.03.13
[블록체인] Web3.js vs Ether.js  (0) 2023.03.13