0

I am trying to integrate MetaMask version 5.3.1 in my Dapp. I am unable to call web3 functions like getBalance with the given instance, also I am unable to post a transaction.

Is there any documentation on that?

Error:

  • ethereum.eth is undefined for calling web funcrtions like getBalance etc
  • Transaction from address isn't valid for this account while sending a tx to metamask

The code I am using:

let metamaskTx = async () => {
    console.log("is metamask" , ethereum.isMetaMask) // true
    let accounts = await ethereum.enable()
    console.log(ethereum.selectedAddress) // prints selected address
    console.log(ethereum.networkVersion) // prints network ID
    // ethereum.eth is undefined
    let balance = await ethereum.eth.getBalance(ethereum.selectedAddress) 
    console.log(balance) 

    let transactionParameters = {
      to: '0xe58db6b23575a93c185f756618f8e42745d7292b',
      value: '0x1'
    }
    // fails with RPC Error: Error: Transaction from address isn't valid for this account
    ethereum.sendAsync({
      method: 'eth_sendTransaction',
      params: [transactionParameters],
      from: ethereum.selectedAddress,
    }, function(err, res){
      console.log({err})
      console.log({res})
    })
  }
0

I found the answer. I needed to user web3 passing ethereum injected by Metamask as provided. The code goes by:

 async sendTxWithMetamask() => {
  const ethereum = window.ethereum;
  let web3 = new Web3()
  let accounts = await ethereum.enable()
  web3.setProvider(ethereum);
  let selectedAddress = ethereum.selectedAddress 
  let balance = await web3.eth.getBalance(selectedAddress)
  console.log('Balance', balance)
  await web3.eth.sendTransaction({
    to: '0xe58db6b23575a93c185f756618f8e42745d7292b', value: web3.utils.toWei('1', 'ether'), from: selectedAddress
  })
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.