错误:尝试调用函数时返回值无效

Posted

技术标签:

【中文标题】错误:尝试调用函数时返回值无效【英文标题】:Error: Returned values aren't valid when trying to call function 【发布时间】:2020-04-10 05:43:50 【问题描述】:

我创建了一个 NameContracts,如下所述:https://bitsofco.de/calling-smart-contract-functions-using-web3-js-call-vs-send/

我用 truffle 编译和迁移它并启动了 ganache-cli。然后我尝试用web3调用函数getName,但总是报错:

Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.

我不确定这意味着什么或我做错了什么。我已经在网上搜索过,但没有一个建议的解决方案对我有用。这是我的代码:

const Web3 = require('web3');
const fs = require('fs');

const rpcURL = "http://localhost:8545";
const web3 = new Web3(rpcURL);

const rawData = fs.readFileSync('NameContract.json');
const jsonData = JSON.parse(rawData);
const abi = jsonData["abi"];

let accounts;
let contract;
web3.eth.getAccounts().then(result =>
  accounts = result;
  web3.eth.getBalance(accounts[0], (err, wei) => 
    balance = web3.utils.fromWei(wei, 'ether')
    console.log("Balance of accounts[0]: " + balance); // works as expected
  )
  contract = new web3.eth.Contract(abi, accounts[0]);
  console.log(contract.methods); // works as expected
  console.log(contract.address); // prints undefined
  contract.methods.getName().call((result) => console.log(result)); // throws error
)

【问题讨论】:

【参考方案1】:

在实例化您的合约时,您将您的帐户地址传递给构造函数,而不是您部署的合约的地址。在执行contract.methods.getName().call() 时,它会尝试调用<your_account_name>.getName(),这当然会失败,因为您的帐户后面没有合约代码,因为它只是一个普通的外部拥有的帐户。

当您使用$ truffle migrate 部署合约时,它应该会显示您部署的合约的地址。您必须在您的 javascript 代码中使用该合约地址创建合约实例。

let contract_address = "0x12f1a3..."; // the address of your deployed contract (see the result of $truffle migrate)
contract = new web3.eth.Contract(abi, contract_address);

【讨论】:

谢谢。我不再收到错误消息。但是,如果我尝试控制台记录 contract.address 我仍然未定义。 您不能直接访问它。试试console.log(contract.options.address);你可以在official documentation找到更多信息。

以上是关于错误:尝试调用函数时返回值无效的主要内容,如果未能解决你的问题,请参考以下文章

错误:非静态成员函数 C++ 的无效使用

oracle 自定义函数,调用时报“程序包或函数无效”

ERROR 错误:使用无效数据调用函数 DocumentReference.set()。不支持的字段值:未定义(在字段 activityId 中找到)

无效的钩子调用错误:只能在函数组件的主体内部调用钩子

为啥我在函数内部调用时会收到“错误:无效的挂钩调用”?

与数据库联系时出错:使用无效数据调用函数 Query.where()。不支持的字段值:自定义 U 对象