【问题标题】:Error when attempting to call smart contract with javascript尝试使用 javascript 调用智能合约时出错
【发布时间】:2022-01-24 21:18:58
【问题描述】:

我正在尝试编写一段调用智能合约的 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 ethereum solidity truffle ganache


    【解决方案1】:

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

    Error: Invalid JSON RPC response: ""
    

    表示您没有收到来自 ganache 的响应。

    • 确保 ganache 正在运行

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

    【讨论】:

    • 我已经确认 ganache 正在正确的端口上运行,并且可以通过 ganache 访问其他信息。我在显示这一点的问题中添加了一些细节。在稍微更新脚本后,我现在也遇到了一个稍微不同的错误。
    • 您的 javascript cde 仍在连接到端口 8545: const web3 = new Web3(new Web3.providers.HttpProvider("localhost: 8545 "));
    • 我确认 ganache 正在 8545 上运行,并且脚本正在连接到它并正确检索数据。
    • @John11727 你是否正确地将 metamask 与 ganache 连接,并且 metamsk 已连接到 ganasche 而不是其他网络
    猜你喜欢
    • 2021-10-09
    • 2021-11-29
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2021-11-15
    • 2022-07-08
    • 2017-08-07
    • 2019-01-24
    相关资源
    最近更新 更多