javascriptsolidityweb3jstruffleganache

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


I created a NameContracts as described here: https://bitsofco.de/calling-smart-contract-functions-using-web3-js-call-vs-send/

I compiled & migrated it with truffle and started the ganache-cli. Then I tried to call the function getName with web3, but always get the error:

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.

I'm not sure what that means or what I did wrong. I already searched the web, but none of the suggested solutions worked for me. Here's my code:

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

Solution

  • When instantiating your contract, you pass your account address to the constructor instead of the address of your deployed contract. When executing contract.methods.getName().call(), it tries to invoke <your_account_name>.getName() which will fail, of course, since there is no contract code behind your account because it is just a regular externally owned account.

    When you deployed your contract with $ truffle migrate, it should have displayed the address of your deployed contract. You have to create the contract instance with that contract address in your javascript code.

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