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

MetaMask是一款允许你能在现在访问未来分页式网页程序的桥梁。允许你在浏览器端,不依赖于以太坊节点,而运行以太坊Dapp

官网

https://metamask.io

索引

https://github.com/MetaMask/faq/

Dapp开发人员

https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md

 

其它相关参考:

https://github.com/ethereum/wiki/wiki/JavaScript-API#adding-web3

https://github.com/MetaMask/faq/blob/master/detecting_metamask.md

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是一款允许你能在现在访问未来分页式网页程序的桥梁。允许你在浏览器端,不依赖于以太坊节点,而运行以太坊Dapp

 

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

MetaMask包括一个安全的身份库,提供用户界面来管理不同站点上的身份并签署区块链交易事务。

 

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.

您可以在ChromeFirefoxOpera和新的Brave浏览器中安装MetaMask插件。如果您是开发人员,可以立即开始使用MetaMask进行开发。

 

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

我们的使命是让以太坊尽可能易于使用。

 

MetaMask Compatibility Guide 

MetaMask兼容性指南

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.

由于浏览器安全限制,我们无法与在file//上运行的dapp进行通信。请使用本地服务器进行开发。

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版本。

请注意,环境web3检查包含在window.addEventListener'load'...)处理程序中。这种方法避免了web3注入定时的竞争条件。

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:

  startApp()

 

})

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.

忘记你对密钥管理的了解,你的Dapp可能不再需要调用sendRawTransaction了。

任何时候你打一个需要私钥来签名的调用(sendTransactionsign),MetaMask会自动提示用户获得许可,然后将签名的请求转发给区块链(或者如果它是一个,则返回给你呼号(签名)。

只需监听响应,当区块链RPC收到交易并进行广播时,您将收到回调。

All Async -Think of MetaMask as a light client

所有异步-MetaMask视为轻量级客户端

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 (web3.version.network).

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"

使用同步调用既是技术限制,也是用户体验问题。它们会阻止用户的界面。无论如何,使用它们是一种不好的做法。将此API限制视为礼物送给用户。

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) {

    case"1":

      console.log('This is mainnet')

      break

    case"2":

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

      break

    case"3":

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

      break

    case"4":

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

      break

    case"42":

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

      break

    default:

      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

帐户管理和交易签名在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.

许多Dapps都有内置的身份管理解决方案作为后备。检测到以太坊浏览器环境时,用户界面应反映该帐户是在外部进行管理的。

另见帐号上的以太坊维基

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数组的唯一成员。

为方便起见,请将web3.eth.defaultAccount变量视为dapp提供的变量。但是,它不应该用作用户意图的数据源。

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];

    updateInterface();

  }

},100);

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 metamask.io:

                                          

如果您想鼓励用户下载MetaMask,请随意使用其中任何一个图片,链接到metamask.io

attachments-2018-11-SFMjWfdj5be1467a6522b.png

attachments-2018-11-0wSipfYj5be14688b0ca8.png

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

0 条评论

请先 登录 后评论
不写代码的码农
梁雁明

区块链研究员

22 篇文章

作家榜 »

  1. 社区运营-小以 501 文章
  2. 社区运营-小链 246 文章
  3. 于中阳Mercina-zy 79 文章
  4. 涂晶 75 文章
  5. 李晓琼 45 文章
  6. 兄弟连区块链培训 42 文章
  7. 吴寿鹤 36 文章
  8. John-smith 26 文章