1

I am trying to develop a simple UI for my contract using web3.js but I'm falling down relatively early: web3 (and window.web3) is defined but the currentProvider property is not.

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');
  }
}

The code I am attempting to use is provided above and contains no additional libraries or dependencies (such as ethjs). The init function is called with the window.onload event.

Is there something I'm doing wrong?

  • 3
    Possible duplicate of How does MetaMask inject Web3? – Malone Dec 5 '17 at 20:46
  • try waiting a little longer using e.g. setTimeout – Joël Dec 13 '17 at 1:40
  • this is just how normal javascript variable declaration works. The idea is to check first to see if there is web3 instance already declared in the global context (on the window object), if so, grab the provider from it and reset it on a newly created Web3 instance. This way you can control which version of web3 you want to use in your code while retaining the provider. – Cody Django Mar 2 '19 at 20:12
3

The line var web3 = new Web3(); overwrites the web3 provider that is injected by MetaMask. Therefore, web3 is defined, but currentProvider not. If you exchange this line by

var web3;

your code from above will work.

|improve this answer|||||
1

A suggested approach for web3 1.0.0 beta is:


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

|improve this answer|||||

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.