Web3.js Type Error – Resolving web3.eth.Contract Not a Constructor Issue

contract-developmentweb3js

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?

Best Answer

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

Related Topic