【问题标题】:why is my web3 import not working properly?为什么我的 web3 导入无法正常工作?
【发布时间】:2021-12-30 07:41:29
【问题描述】:

我正在使用 truffle 和 mocha 来测试我的智能合约。我需要 web3 像这样 const web3 = require('web3')

导入似乎只能部分起作用。 例如,这个语句可以正常工作

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

不过这个说法

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

导致以下错误消息:

TypeError 无法读取未定义的属性“getBalance”。

此外,如果我在以下代码中悬停单词 eth,Visual Studio Code 会给我以下错误消息:

web.eth.getBalance(myContract.address)

typeof 导入时不存在属性“eth”(/Users/eitanbronschtein/Desktop/fundraiser/node_modules/web3/types/index)

我使用的是 javascript 而不是打字稿。

发生了什么事?

【问题讨论】:

    标签: mocha.js solidity smartcontracts web3 truffle


    【解决方案1】:

    没有提供者,web3 无法工作。安装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 }));
    

    如果你设置了 truffle suit,你的项目中应该有“test”目录,web3 已经设置好了并且可以全局使用

    【讨论】:

      【解决方案2】:

      Web3 类是一个包含所有以太坊相关模块的综合包。

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-27
        • 2021-04-03
        相关资源
        最近更新 更多