简体   繁体   中英

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 give 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?

The Web3 class is an umbrella package to house all Ethereum related modules.

var Web3 = require('web3');

// "Web3.providers.givenProvider" will be set if in an Ethereum supported browser.
var web3 = new Web3(Web3.givenProvider || 'ws://some.local-or-remote.node:8546');

//now you can do web3.eth

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM