web3.eth.account[0] error:invalid address的解决方法

问题描述:

最近在前端想获取到当前用户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.com/questions/19524/invalid-address-error-when-interacting-with-a-smart-contract-with-metamask

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值