关于接口:MetaMask的常用接口调用

39次阅读

共计 1327 个字符,预计需要花费 4 分钟才能阅读完成。

MetaMask 是 Chrome 上应用的插件类型的以太坊钱包,只须要在谷歌浏览器增加对应的扩大程序即可,十分轻量级,应用起来也十分不便。

library.provider 从 Web3Provider 中获取
BigNumber, utils 从 ethers.js 中获取

1. 增加 ERC-20 代币

    library.provider
      .request({
        method: 'wallet_watchAsset',
        params: {
          type: 'ERC20',
          options: {
            address: token.address,
            symbol: token.symbol,
            decimals: token.decimals,
            image: getTokenLogoURL(token.address, chainId, uriLocations),
          },
        },
      })
      .then((success) => {setSuccess(success)
      })
      .catch(() => setSuccess(false))

2. 切换网络

// 阐明 interface
interfaceAddEthereumChainParameter {
   chainId: string; // A 0x-prefixed hexadecimal string
   chainName: string;
   nativeCurrency: {
   name: string;
   symbol: string; // 2-6 characters long
   decimals: 18;
   };
   rpcUrls: string[];
   blockExplorerUrls?: string[];
   iconUrls?: string[]; // Currently ignored.}
[ChainId.MATIC]: {
   chainId: '0x89',
   chainName: 'Matic',
   nativeCurrency: {
   name: 'Matic',
   symbol: 'MATIC',
   decimals: 18,
   },
   rpcUrls: ['https://polygon-rpc.com'], // ['https://matic-mainnet.chainstacklabs.com/'],
   blockExplorerUrls: ['https://polygonscan.com'],
 },

 
const formattedChainId = utils.hexStripZeros(BigNumber.from(chainId).toHexString())
library?.provider.request({
 method:
   chainId === MAINNET || KOVAN || ROPSTEN || RINKEBY || GÖRLI
   ? 'wallet_switchEthereumChain'
   : 'wallet_addEthereumChain',
 params: [
   chainId === MAINNET || KOVAN || ROPSTEN || RINKEBY || GÖRLI
   ? {chainId: formattedChainId}
   : AddEthereumChainParameter,
   ],
 })

欢送区块链行业气味相投的小伙伴增加小极微信,退出 blockgeek 区块链技术交换群,独特推动区块链技术遍及和倒退~

正文完
 0