使用web3.js库调用智能合约方法

时间:2019-01-27 14:14:42

标签: javascript ethereum solidity smartcontracts

我是web3.js的新手,我试图从omesigo智能合约调用方法,但出现一个令人困惑的错误。 我已经阅读过web3文档并尝试过。

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相关行:

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)

它应该显示Omisego令牌名称。 预先感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我遇到了同样的错误,并通过将Web3库升级到main()

来解决了该错误。

更深入地研究错误,似乎与"web3": "^1.0.0-beta.39"的深度克隆有关。经过数小时徒劳的调试之后,我偶然发现了Web3版本,并发现它是contract.method arguments的功能版本。 (一天前发布)

答案 1 :(得分:0)

我一直面临着相同的问题,与您的方法唯一的不同是web3 api的版本,对我来说,该版本是1.0.0-beta.46。这个问题的解决方案似乎牵强附会。