[英]Smart Contract failed to load Web3 with truffle
我正在尝试使用solidity 0.5.10、truffle 和web3 创建一个ETH 智能合约。 一切似乎都运作良好,除了我得到:
ParserError:预期的编译指示、导入指令或合同/接口/库定义。 常量 web3 = 要求('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"
}
}
您正在将 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 进行编译,您可以使用他们的测试工具对智能合约进行 JS 测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.