MetaMask应用开发入门 - Brings Ethereum to your browser(中英版)







Brings Ethereum to your browser

MetaMask is a bridge that allows you to visit the distributed web of tomorrow in your browser today. It allows you to run Ethereum dApps right in your browser without running a full Ethereum node



MetaMask includes a secure identity vault, providing a user interface to manage your identities on different sites and sign blockchain transactions.



You can install the MetaMask add-on in Chrome, Firefox, Opera, and the new Brave browser. If you’re a developer, you can start developing with MetaMask today.



Our mission is to make Ethereum as easy to use for as many people as possible.



MetaMask Compatibility Guide 


While MetaMask exposes the standard Ethereum web3 API, there are few things to keep in mind. Below are requirements for MetaMask support as well as some best practices to keep in mind.

虽然MetaMask公开了标准的以太坊web3 API,但是要记住几件事情。以下是MetaMask支持要求以及要记住的一些最佳实践。

Requirement - 要求


Http(s) - Web Server Required 

Http(s) - Web服务器必需

Due to browser security restrictions, we can't communicate with dapps running on file://. Please use a local server for development.


Web3-Ethereum Browser Environment Check 

Web3 - 以太坊浏览器环境检查

MetaMask injects web3 object and convenience Web3.js library into the javascript context. Look for this before using your fallback strategy (local node / hosted node + in-dapp id mgmt / read-only / fail). You can use the injescted Web3.js directly, but the best practice is to explicitly bundle the version of web3.js you used during development.

Note that the environmental web3 check is wrapped in a window.addEventListener('load', ...) handler. This approach avoids race conditions with web3 injection timing.

MetaMaskweb3对象和便利Web3.js库注入到javascript环境中。在使用您的回退策略(本地节点/托管节点+ in-dapp id mgmt /只读/失败)之前查找此内容。您可以直接使用注入的Web3.js,但最佳做法是显式捆绑您在开发期间使用的web3.js版本。


window.addEventListener('load'function() {


  // Checking if Web3 has been injected by the browser (Mist/MetaMask)

  if(typeofweb3 !=='undefined') {

    // Use Mist/MetaMask's provider

    web3js =newWeb3(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 =newWeb3(newWeb3.providers.HttpProvider("http://localhost:8545"));



  // Now you can start your app & access web3 freely:




This code snippet is modified from theethereum wiki on "adding web3"

此代码段已从ethereum wiki on "adding web3"中修改

You can find more notes ondetecting metamask here.

你可以在detecting metamask here到更多的笔记

We Handle User Authorization


Forget what you know about key management, your Dapp likely won't need to call sendRawTransaction anymore.

Any time you make a call that requires a private key to sign something (sendTransaction, sign), MetaMask will automatically prompt the user for permission, and then forward the signed request on to the blockchain (or return it to you, if it was a call to sign).

Just listen for a response, and when the blockchain RPC has received the transaction and broadcast it, you'll get a callback.




All Async -Think of MetaMask as a light client


The user does not have the full blockchain on their machine, so data lookups can be a little slow. For this reason, we are unable to support most synchronous methods. The exceptions to this are:


   eth_accounts (web3.eth.accounts)

   eth_coinbase (web3.eth.coinbase)

   eth_uninstallFilter (web3.eth.uninstallFilter)

   web3.eth.reset (uninstalls all filters).

   net_version (

Usually, to make a method call asynchronous, add a callback as the last argument to a synchronous method. See the Ethereum wiki on "using callbacks"

Using synchronous calls is both a technical limitation and a user experience issue. They block the user's interface. So using them is a bad practice, anyway. Think of this API restriction as a gift to your users.

通常,要使方法调用异步,请将回调添加为同步方法的最后一个参数。详见Ethereum wiki on "using callbacks"


Best Practices最佳实践

Network check


When a user interacts with a dapp via MetaMask, they may be on the mainnet or testnet. As a best practice, your dapp should inspect the current network via the net_version json rpc call. Then, the dapp can use the correct deployed contract addresses for the network, or show which network is expected in a message.

当用户通过MetaMaskdapp交互时,它们可能位于主网或testnet上。作为最佳实践,您的dapp应该通过net_version json rpc调用检查当前网络。然后,dapp可以使用正确部署的网络合同地址,或显示消息中预期的网络。

For example:

web3.version.getNetwork((err, netId) =>{

  switch(netId) {


      console.log('This is mainnet')



      console.log('This is the deprecated Morden test network.')



      console.log('This is the ropsten test network.')



      console.log('This is the Rinkeby test network.')



      console.log('This is the Kovan test network.')



      console.log('This is an unknown network.')



See the ethereum wiki on "getNetwork"

详见:ethereum wiki on "getNetwork"

Account management and transaction signing ismanaged externally to the dapp


Many Dapps have a built-in identity management solution as a fallback. When an Ethereum Browser environment has been detected, the user interface should reflect that the accounts are being managed externally.



Also see theEthereum wiki on "accounts"

Account List Reflects User Preference


When a user selects an account in MetaMask, that account silently becomes the web3.eth.accounts[0] in your JS context, the only member of the web3.eth.accounts array.

For your convenience, consider the web3.eth.defaultAccount variable a dapp-provided variable. However, it should not be used as a data source of user intention.

当用户在MetaMask中选择一个帐户时,该帐户将默认成为JS上下文中的web3.eth.accounts [0],这是web3.eth.accounts数组的唯一成员。


Listening for Selected Account Changes       


Since these variables reflect user intention, but do not (currently) have events representing their values changing, we somewhat reluctantly recommend using an interval to check for account changes.

For example, if your application only cares about the web3.eth.accounts[0] value, you might add some code like this somewhere in your application:


例如,如果您的应用程序只关心web3.eth.accounts [0]值,您可以在应用程序的某处添加一些这样的代码:

varaccount =web3.eth.accounts[0];

varaccountInterval =setInterval(function() {

  if(web3.eth.accounts[0]!==account) {

    account =web3.eth.accounts[0];




If you think this is an antipattern, and should be replaced with an event/subscription model, we encourage you to voice that opinion. Let us know, and we could get an improved API adopted as an EIP.

如果您认为这是一个反(not good)模式,应该用事件/订阅模型替换,我们建议您发表意见。让我们知道,我们可以获得一个改进的API作为EIP采用。

Download MetaMask Badge

If you'd like to encourage your users to download MetaMask, feel free to use either of these images, linking to





  • 发表于 2018-11-06 11:30
  • 阅读 ( 1074 )
  • 分类:以太坊

0 条评论

请先 登录 后评论


17 篇文章

作家榜 »

  1. 社区运营-小以 623 文章
  2. 社区运营-小链 243 文章
  3. 涂晶 82 文章
  4. 于中阳Mercina-zy 79 文章
  5. 李晓琼 44 文章
  6. 兄弟连区块链培训 42 文章
  7. 吴寿鹤 38 文章
  8. John-smith 25 文章