首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DAPP中的集成元DAPP

DAPP中的集成元DAPP
EN

Ethereum用户
提问于 2019-01-24 11:39:26
回答 1查看 797关注 0票数 0

我正在尝试将MetaMask版本5.3.1集成到我的Dapp中。我无法用给定的实例调用web3函数(如getBalance ),也无法发布事务。

这方面有什么文件吗?

错误:

  • ethereum.eth是未定义的,用于调用getBalance等web函数
  • 在向元问询发送tx时,来自地址的事务对此帐户无效

我使用的代码:

代码语言:javascript
复制
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})
    })
  }
EN

回答 1

Ethereum用户

发布于 2019-01-24 13:12:09

我找到了答案。我需要用户web3,按规定传递由Metamask注入的ethereum。守则如下:

代码语言:javascript
复制
 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
  })
};
票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/66064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档