0

Why can't I instantiate my smart contract?

When I try and instantiate an instance of a smart contract with the following code...

let contractInstance = new web3.eth.Contract(abi, '0x6c6101607c84368dd130909bae7c7273d8914708');

... I get the following Error:

Uncaught TypeError: web3.eth.Contract is not a constructor

This is confusing to me because when I use web3.version in my console, it returns 1.0.0-beta.36. I instantiated my web3 provider in the following way:

window.addEventListener('load', async () => {
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
    console.log('MetaMask Success');
    await window.ethereum.enable();
    web3.eth.defaultAccount = web3.eth.accounts.givenProvider.selectedAddress;

} else {
    console.log('No web3? You should consider trying MetaMask!');
    web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
}
});

Any suggestions?

  • Make sure you are really using web3 v1.0, perhaps some dependency issue, or you are using a different instance of web3. – Ismael Sep 20 at 3:43
  • It seems like a dependency issue. When I type web3.version into my console, sometimes it returns 0.20.7 and other times it returns 1.0.0-beta.36. Do you have any idea what is going on? – Julian Martinez Sep 20 at 13:57
  • It is hard to say anything else without the source code. – Ismael Sep 20 at 16:12
  • did you do something to the console like move around directory or using different user then it get different version or did you just enter the version many time but get different results? – haxerl Sep 21 at 11:54
  • @Ismael Here is the source code. In order to test my code, I would serve index.html to localhost:5000. I used Ganache as the blockchain (localhost:7545). When I signed in to MetaMask, I made sure to switch Ethereum network to (localhost:7545) as well. – Julian Martinez Sep 26 at 23:03
1

In app.js you are initializing contractInstance outside of the 'load' event.

window.addEventListener('load', async () => {
    // ...
});

web3.eth.defaultAccount = web3.eth.accounts.givenProvider.selectedAddress;
contractInstance = new web3.eth.Contract(abi, '0x15013d783fadAaA9e9d2F0e8d71C575f81a39834'); // Ganache contract address ''0x15013d783fadAaA9e9d2F0e8d71C575f81a39834''

Due to the async nature of the web it is possible app.js code is executed before the load event is triggered. Make sure to initialize the contract after the load event was fired.

window.addEventListener('load', async () => {
    // ...



    web3.eth.defaultAccount = web3.eth.accounts.givenProvider.selectedAddress;
    contractInstance = new web3.eth.Contract(abi, '0x15013d783fadAaA9e9d2F0e8d71C575f81a39834'); // Ganache contract address ''0x15013d783fadAaA9e9d2F0e8d71C575f81a39834''
});

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.