我正在尝试使用web3.js
为我的合同开发一个简单的UI,但我比较早:定义了web3
(和window.web3
),但currentProvider
属性没有定义。
var Web3 = require('web3');
var web3 = new Web3();
function init() {
if (typeof web3 !== 'undefined') {
console.log('Web3 found');
window.web3 = new Web3(web3.currentProvider);
web3.eth.defaultAccount = web3.eth.accounts[0];
} else {
console.error('web3 was undefined');
}
}
我试图使用的代码是在上面提供的,并且不包含额外的库或依赖项(如ethjs
)。init
函数与window.onload
事件一起调用。
我做错什么了吗?
发布于 2017-12-05 21:55:45
行var web3 = new Web3();
覆盖由MetaMask注入的web3提供程序。因此,定义了web3
,但没有定义currentProvider
。如果你把这一行换成
var web3;
您的代码从上面将起作用。
发布于 2019-03-02 20:17:32
web3 1.0.0 beta的一种建议方法是:
if ((typeof window.ethereum !== 'undefined')
|| (typeof window.web3 !== 'undefined')) {
return new Web3(window['ethereum'] || window.web3.currentProvider)
} else {
// here you could use a different provider, maybe use an infura account, or maybe let the user know that they need to install metamask in order to continue
return new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/..."))
}
https://metamask.github.io/metamask-docs/Advanced_Concepts/Provider_API
https://ethereum.stackexchange.com/questions/32551
复制相似问题