首页 > 解决方案 > 如何通过调用编码函数获取智能合约的返回值

问题描述

我已经编码了我的智能合约的函数,它具有 methodID 和参数,即0xf7ea7a3d4000000000000000000015000000000000000000ff7f0000b200000000f7ea7a............... 假设,在这个编码函数中,还有两个参数,一个是 uint,另一个是字符串。这个编码函数实际上是我的合同的一个 getter(不改变状态)(在 ABI 中它的 stateMutability =view 表示),它还返回一个值,即totalSupply. 现在,我想通过 web3js/nodejs 调用这个函数,如下所示。正如预期的那样,此代码为我提供了交易收据/哈希,但我有兴趣检索 getter 函数返回值,即totalSupply

try {
    await web3.eth.sendTransaction(
        {
            from: account1,
            to: myContAddr,
            data: myFunc
        }).then(function (res) {
            console.log("Normal Getter", res);
        });
} catch (error) {
    console.log(" Normal Getters: ERROR !");
}

一种可能的解决方案是从给定的编码函数及其参数(但我不知道如何解码参数)中提取函数签名/方法ID(这对我来说很容易)并像这样调用函数..即

try {
    res = await myContractInstance.methods[myFuncID](????).call({ from: account1 })  // without parameters
    console.log("Getter output", res);
} catch (error) {
    console.log("Getter output: ERROR !", error);
}

所以,我的问题是

  1. 如何从上述编码函数中解码参数,按照我提到的解决方案进行(如果我的解决方案是正确的)?
  2. 或者是否有任何其他可行/简单的程序来调用这种编码(getter)函数?

标签: javascriptnode.jsethereumweb3js

解决方案


推荐阅读