【问题标题】:Smart Contract failed to load Web3 with truffle智能合约无法用松露加载 Web3
【发布时间】:2021-06-29 09:08:28
【问题描述】:

我正在尝试使用solidity 0.5.10、truffle 和web3 创建一个ETH 智能合约。一切似乎都很好,除了我得到:

ParserError:预期的编译指示、导入指令或合同/接口/库定义。 const web3 = require('web3');

当我尝试加载 web3 时。

我已经安装了 web3(dir {project folder} npm install web3)和我的 package.json(位于我的项目文件夹中):

“依赖”:{ “web3”:“^1.3.4” }

我都试过了: 从“web3”导入 Web3;

并且 const Web3 = require('web3');

但是还是无法加载web3,我做错了什么?

导致错误的合约

pragma solidity 0.5.10;

const web3 = require('web3');

contract UserRepository {

  struct User {
      uint id;
      bytes32 firstName;
      bytes32 lastName;
  }
  mapping(uint => User) public users;

  uint public latestUserId = 0;
  address private owner;

  constructor() public {
    owner = msg.sender;
  }
}

package.json

{
  "name": "helloworld",
  "version": "1.0.0",
  "main": "truffle-config.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "web3": "^1.3.4"
  }
}

【问题讨论】:

  • 请编辑您的问题并显示导致错误的代码。 “预期的编译指示”解析错误看起来像 solc(solidity 编译器)错误,所以它可能与 web3 无关。
  • 抱歉,现在包含@PetrHejda

标签: solidity web3 truffle


【解决方案1】:

您正在将 node.js 混合到您的 Solidity 代码中。

pragma solidity 0.5.10;

const web3 = require('web3'); // this is node.js

contract UserRepository {

删除const web3 = require('web3'); 行,它将成功编译(在 Remix 中测试)


在这里,我只是猜测您想使用web3 来启用 JS 代码与您的智能合约进行通信(例如,用于测试目的)。

如果是这种情况,您需要创建一个单独的 JS 文件来导入 web3 并使用 web3.eth.Contract 实例化此合约。

或者由于您已经在使用 Truffle 进行编译,您可以使用他们的test tools 进行智能合约的 JS 测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2018-12-28
    • 2022-09-29
    • 1970-01-01
    • 2018-11-15
    • 2019-01-24
    • 2018-07-10
    相关资源
    最近更新 更多