2

I am trying to write a piece of javascript that calls a smart contract. The smart contract has been deployed to a local test net with truffle and ganache and the javascript is producing the following error:

Promise { <pending> }
/Users/user/node_modules/web3-core-helpers/lib/errors.js:43
        return new Error(message);
               ^

Error: Invalid JSON RPC response: ""
    at Object.InvalidResponse (/Users/user/node_modules/web3-core-helpers/lib/errors.js:43:16)
    at XMLHttpRequest.request.onreadystatechange (/Users/user/node_modules/web3-providers-http/lib/index.js:95:32)
    at XMLHttpRequestEventTarget.dispatchEvent (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpRequestError (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:349:14)
    at ClientRequest.<anonymous> (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:252:61)
    at ClientRequest.emit (node:events:390:28)
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:390:28)
    at emitErrorNT (node:internal/streams/destroy:164:8)
    at emitErrorCloseNT (node:internal/streams/destroy:129:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Node.js v17.3.0

Javascript code:

onst Web3 = require('web3');

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const contract_abi = [
   {
      "inputs":[

      ],
      "name":"getName",
      "outputs":[
         {
            "internalType":"string",
            "name":"",
            "type":"string"
         }
      ],
      "stateMutability":"view",
      "type":"function"
   },
   {
      "inputs":[
         {
            "internalType":"string",
            "name":"newName",
            "type":"string"
         }
      ],
      "name":"setName",
      "outputs":[

      ],
      "stateMutability":"nonpayable",
      "type":"function"
   }
]


const contract_address = "0x6C1750bfDD9D1327AE8c5dBD1Af75dc73C138Fd7";
var Contract = new web3.eth.Contract(contract_abi, contract_address);

console.log(Contract.methods.getName().call());

Solidity code:

pragma solidity >=0.4.24;

contract NameContract {

    string private name = "This is working!";

    function getName() public view returns (string memory)
    {
        return name;
    }

    function setName(string memory newName) public
    {
        name = newName;
    }
}

I am not sure if the issue is coming from me not handling the async request properly, the JSON abi being malformed or the smart contract response not being handled correctly.

Any help would be greatly appreciated.

EDIT:

I confirmed ganache is running on 8545 through the ganache output:

Gas Price
==================
20000000000

Gas Limit
==================
6721975

Call Gas Limit
==================
9007199254740991

Listening on 127.0.0.1:8545

I also confirmed this through adding the following method that returned the correct block number.

async function getBlockNum(){
  console.log(await web3.eth.getBlockNumber());
}

Also I got the contract address from the truffle output contract address parameter. Is this the correct place to get a contract address?

 Deploying 'Migrations'
   ----------------------
   > transaction hash:    0xd60debe1fa028b95152eb4b32853ba948b172624cdc4615e429cd44c908fa445
   > Blocks: 0            Seconds: 0
   > contract address:    0x6C1750bfDD9D1327AE8c5dBD1Af75dc73C138Fd7
   > block number:        1

I changed the script code slightly to have the console.log(Contract.methods.getName().call()); be an async call which looks like this:

async function getOutput(){
  const contract_address = "0x6C1750bfDD9D1327AE8c5dBD1Af75dc73C138Fd7";
  var Contract = new web3.eth.Contract(contract_abi, contract_address);
  console.log(await Contract.methods.getName().call());
}

And now I am getting the following slightly more detailed but still very confusing error:

        var err = new Error('Returned error: ' + message);
                  ^

Error: Returned error: VM Exception while processing transaction: revert
    at Object.ErrorResponse (/Users/user/node_modules/web3-core-helpers/lib/errors.js:28:19)
    at /Users/user/node_modules/web3-core-requestmanager/lib/index.js:302:36
    at XMLHttpRequest.request.onreadystatechange (/Users/user/node_modules/web3-providers-http/lib/index.js:98:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpResponseEnd (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
    at IncomingMessage.<anonymous> (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
    at IncomingMessage.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  data: {
    '0x014d2c7d3c399932858fd397142bafb110b513dd82ed746f0ad969961e42ce03': { error: 'revert', program_counter: 70, return: '0x' },
    stack: 'c: VM Exception while processing transaction: revert\n' +
      '    at Function.c.fromResults (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:4:192416)\n' +
      '    at /usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:42:50402',
    name: 'c'
  }
}

John11727
  • 85
  • 1
  • 6

1 Answers1

2

Your contract and javascript code is correct. Error

Error: Invalid JSON RPC response: ""

indicates that you are not getting a response from the ganache.

  • Make sure that ganache is running

  • Connect to correct port. You are connecting to port "8545" but usually ganache server listens to 7545.

enter image description here

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • I have confirmed that ganache is running on the correct port and that other information is accessible through ganache. I added some details to the question showing this. I am also getting a slightly different error now after updating the script a bit. – John11727 Dec 24 '21 at 05:52
  • your javascript cde is still connecting to port 8545: const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost: 8545 ")); – Yilmaz Dec 24 '21 at 16:18
  • I confirmed ganache was running on 8545 and that the script was connecting to it and retrieving data correctly. – John11727 Dec 24 '21 at 19:57
  • @John11727 did u connect metamask with ganache correctly and metamsk is connected to ganasche not do a different network – Yilmaz Dec 24 '21 at 21:28