简体   繁体   中英

How to sign messages with Web3 and MetaMask from a React app

I am working on my first dapp and I am trying to use Web3 and MetaMask to sign a message but I keep getting this error:

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

I have the MetaMask privacy mode turned off. The getCoinBase() method is correctly returning the address I have selected in MetaMask. But when I try to use it to sign a message it does not work.

Here's my code: The lines of dots are to skip over the unimportant pieces.

 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); }) }

Metamask recently made changes about how they reveal addresses to users. I found a StackOverflow post that seems related here . To quote:

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

Related blog post from Metamask team: https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8

 const accounts = (await ethereum?.request({ method: "eth_requestAccounts", })) as string[]; // account will be the signer of this message const account = accounts[0]; const signedData = await ethereum?.request({ method: "personal_sign", params: [ JSON.stringify(messageToSign), account, passwordHere, ], });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM