Search code examples
mocha.jssoliditysmartcontractsweb3jstruffle

why is my web3 import not working properly?


I am using truffle with mocha to test my smart contract. I have required web3 like so const web3 = require('web3')

the import seems only to work partially. for example, this statement works just fine

const amount = web3.utils.toWei('0.23')

however this statement

const balance = await web3.eth.getBalance(myContract.address)

causes the following error message:

TypeError Cannot read property 'getBalance' of undefined.

Moreover, Visual Studio Code gives me the following error message if I hover of the word eth in this following code:

web.eth.getBalance(myContract.address)

Property 'eth' does not exist on typeof import (/Users/eitanbronschtein/Desktop/fundraiser/node_modules/web3/types/index)

I am using javascript and not typescript.

What is going on?


Solution

  • web3 does not work without provider. install ganach-cli

    const ganache = require("ganache-cli");
    const Web3 = require("web3");
    
    // this is in local ganache network gasLimit has to be set to 10million and and factory gas must be 10million
    // if u get error about gasLimit, this keep changing. look for docs
    const web3 = new Web3(ganache.provider({ gasLimit: 10000000 }));
    

    If you set truffle suit, you should have "test" directory in your project and web3 would be already set and available globally