首页 > 解决方案 > 如何在 React 应用程序中使用 Web3 和 MetaMask 签署消息

问题描述

我正在开发我的第一个 dapp,我正在尝试使用 Web3 和 MetaMask 来签署消息,但我不断收到此错误:

inpage.js:1 MetaMask - RPC Error: Error: WalletMiddleware - Invalid "from" address.

我关闭了 MetaMask 隐私模式。getCoinBase() 方法正确返回了我在 MetaMask 中选择的地址。但是当我尝试使用它来签署消息时,它不起作用。

这是我的代码:点线是为了跳过不重要的部分。

let Web3 = require('web3')
.
.
.
constructor(props) {

    super(props);

    if (typeof web3 != 'undefined') {
      // eslint-disable-next-line no-undef  
      this.web3 = new Web3(web3.currentProvider);
    }

    this.web3.eth.getCoinbase()
    .then(account => {
      this.web3.eth.sign('test message', account);
    });
}

标签: ethereumweb3metamaskganache

解决方案


Metamask 最近对向用户显示地址的方式进行了更改。我在这里找到了一个似乎相关的 StackOverflow 帖子。去引用:

The Invalid address error can also happen if you haven't called window.ethereum.enable(); yet.

Metamask 团队的相关博文:https ://medium.com/metamask/https-medium-com-metamask-break-change-injecting-web3-7722797916a8


推荐阅读