0
votes

I'm trying to create a ETH smart contract with solidity 0.5.10, truffle and web3. Everythings seems to work well except that i get :

ParserError: Expected pragma, import directive or contract/interface/library definition. const web3 = require('web3');

When I'm trying to load web3.

I have installed web3 (dir {project folder} npm install web3) and in my package.json (located in my project folder) :

"dependencies": { "web3": "^1.3.4" }

I've tried both : import Web3 from 'web3';

And const Web3 = require('web3');

But it still can't load web3, what do I do wrong?

contract that cause the error

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"
  }
}

enter image description here

1
Please edit your question and show the code that causes the error. "Expected pragma" parse error seems like solc (solidity compiler) error, so it might not be related to web3.Petr Hejda
Sorry, inlcuded now @PetrHejdaKrika

1 Answers

1
votes

You're mixing node.js into your Solidity code.

pragma solidity 0.5.10;

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

contract UserRepository {

Remove the const web3 = require('web3'); line and it's going to compile successfully (tested in Remix).


Here I'm just guessing that you wanted to use web3 to enable JS code to communicate with your smart contract (e.g. for test purposes).

If that's the case, you need to create a separate JS file that imports web3 and instantiates this contract using web3.eth.Contract.

Or since you're already using Truffle for compilation, you can use their test tools for JS tests of smart contracts.