Search code examples
javascriptethereumsoliditysmartcontracts

Calling a smart contract method using web3.js library


I am new to web3.js and I am trying to call a method from omesigo smart contract but I get a confusing error. I have already read web3 doc and tried it.

package.json

{
  "name": "web3-learn",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@babel/runtime": "^7.3.1",
    "babel-cli": "^6.26.0",
    "web3": "^1.0.0-beta.38"
  }
}

node version: 10.15.0

index.js related lines:

let contract = web3.eth.Contract(abi, address);
contract.methods.name().call((err, res) => {console.log(res)});
/home/amin/Documents/projects/solidity-workshop/solidity-learn/src/web3-learn/node_modules/@babel/runtime/helpers/nonIterableSpread.js:2
  throw new TypeError("Invalid attempt to spread non-iterable instance");
  ^

TypeError: Invalid attempt to spread non-iterable instance
    at _nonIterableSpread (/home/amin/Documents/projects/solidity-workshop/solidity-learn/src/web3-learn/node_modules/@babel/runtime/helpers/nonIterableSpread.js:2:9)
    at _toConsumableArray (/home/amin/Documents/projects/solidity-workshop/solidity-learn/src/web3-learn/node_modules/@babel/runtime/helpers/toConsumableArray.js:8:60)
    at CallContractMethod.set (/home/amin/Documents/projects/solidity-workshop/solidity-learn/src/web3-learn/node_modules/web3-core-method/dist/web3-core-method.cjs.js:405:34)
    at MethodsProxy.executeMethod (/home/amin/Documents/projects/solidity-workshop/solidity-learn/src/web3-learn/node_modules/web3-eth-contract/dist/web3-eth-contract.cjs.js:525:26)
    at Function.anonymousFunction.(anonymous function) [as call] (/home/amin/Documents/projects/solidity-workshop/solidity-learn/src/web3-learn/node_modules/web3-eth-contract/dist/web3-eth-contract.cjs.js:497:27)
    at Object.<anonymous> (/home/amin/Documents/projects/solidity-workshop/solidity-learn/src/web3-learn/index.js:34:25)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

It should print Omisego token name. Thanks in advance for your help.


Solution

  • I was experiencing the same error, and solved it by upgrading the Web3 library to "web3": "^1.0.0-beta.39"

    Looking deeper into the error, it seems related to the deep cloning of contract.method arguments. After a few hours of fruitless debugging, I stumbled upon the Web3 releases and saw that it was a featured release of beta.39. (released a day ago)