MetaMask的常用接口调用

2021-09-26 15

MetaMask是Chrome上使用的插件类型的以太坊钱包,只需要在谷歌浏览器添加对应的扩展程序即可,非常轻量级,使用起来也非常方便。

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, ], })
作者:Agur Xu

欢迎区块链行业志同道合的小伙伴添加小极微信,加入blockgeek区块链技术交流群,共同推动区块链技术普及和发展~