Error: Returned values aren't valid when trying to call function

Error: Returned values aren't valid when trying to call function

我创建了一个 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.

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

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

实例化您的合约时,您将账户地址传递给构造函数,而不是已部署合约的地址。当执行 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);