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.