尝试使用 javascript 调用智能合约时出错

Error when attempting to call smart contract with javascript

我正在尝试编写一段调用智能合约的 javascript。智能合约已部署到带有 truffle 和 ganache 的本地测试网,javascript 产生以下错误:

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代码:

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());

实体代码:

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

我不确定问题是否出自我没有正确处理异步请求、JSON abi 格式错误或智能合约响应未正确处理。

如有任何帮助,我们将不胜感激。

编辑:

我通过 ganache 输出确认 ganache 在 8545 上 运行:

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

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

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

Listening on 127.0.0.1:8545

我还通过添加以下返回正确块号的方法确认了这一点。

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

我还从truffle输出合约地址参数中得到了合约地址。这是获取合约地址的正确位置吗?

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

我稍微更改了脚本代码,使 console.log(Contract.methods.getName().call()); 成为一个异步调用,如下所示:

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

现在我得到以下更详细但仍然非常混乱的错误:

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

您的合同和 javascript 代码是正确的。错误

Error: Invalid JSON RPC response: ""

表示您没有收到来自甘那许的回复。

  • 确保甘那许 运行

  • 连接到正确的端口。您正在连接到端口“8545”,但通常 ganache 服务器会侦听 7545。