admin管理员组

文章数量:1648420

问题描述:

最近在前端想获取到当前用户eth账户的时候,老是报错显示 invalid address。网上查找了几种方法之后终于解决了。

1.问题代码:let user_address = web3.eth.account[0]

2.报错:无法获取到当前的account[0] 

3.浏览器使用的钱包插件:metamask 

 

解决方案:(两种方案)

一、

web3.eth.accounts[0] not being populated. In Web3.js 1.0, this value is not populated by default. Instead you need to get accounts using something like: 

var accounts = await web3.eth.getAccounts()
console.log(accounts[0])

即在web3.js 1.0这个版本里,account[0]是不会被默认定义的,所以想要获取到当前账户,可以调用getAccounts()方法,这里用 await 是因为web3.eth.getAccounts 是个异步方法。

博主用这个方法成功deal了这个问题,希望这个方法也能帮助到你。

二、

 就像方案一说的那样,既然defaultAccount没有默认定义,那就手动定义。

2.1

You need to set the default account of the contract too. or if contractinstance is what you use to call the functions

Contractinstance.web3.eth.defaultAccount=Contractinstance.web3.eth.coinbase

附coinbase这个api的解释:只读属性,由节点配置,如果挖矿成功奖励的地址。异步方法web3.eth.getCoinbase

2.2

第二种设置defaultAccount的方法如下,这个方法博主并没有尝试成功,所以把这个deal放在了最后。以及不太清楚为何需要unlock这个地址,如果有知道的伙伴能帮解答一下,就更好了。抱拳感谢!!!

web3.eth.defaultAccount = web3.eth.accounts[0]
personal.unlockAccount(web3.eth.defaultAccount)
contractObj = web3.eth.contract(contractABI).at(contractAddr)
contractObj.method(args...)

  

 

参考文章:

1. https://ethereum.stackexchange/questions/19524/invalid-address-error-when-interacting-with-a-smart-contract-with-metamask

2.https://ethereum.stackexchange/questions/49343/web3-eth-sign-error-invalid-address

本文标签: 解决方法AccountEthAddressInvalid