【问题标题】:How do you read a value returned by a method in smartcontract using web3j?您如何使用 web3j 读取智能合约中的方法返回的值?
【发布时间】:2022-11-04 19:33:25
【问题描述】:

我在 Android Studio 中使用web3j 与智能合约进行交互。

在我的 SmartContract 中,我有 2 个函数 getName()getAge(),我在构造函数中设置年龄和名称,如下所示:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.5.0 <0.9.0;

contract Identify {

    string name;
    uint age;

    constructor() public {
        name = "Shoaib Khalid";
        age = 22;
    }

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


    function getAge() view public returns(uint){
        return age;
    }
}

但我无法读取这两个函数返回的值。正确部署智能合约后,以下是我尝试读取 getName() 函数返回的值的方法。

  val identityContract = Identity_sol_Identify.load(
            deployedContractAddress,
            web3j,
            getCredentialsFromPrivateKey(),
            DefaultGasProvider.GAS_PRICE,
            DefaultGasProvider.GAS_LIMIT
        )
  Log.d(TAG, "counter Result:  ${identityContract.name.sendAsync().get()}")

我没有得到我在构造函数中设置的值Shoaib Khalid,而是得到一个TranscriptReciept 对象,输出屏幕截图附在下面。

所以我想知道你能用web3j读取智能合约中getName()函数返回的确切值吗?

【问题讨论】:

    标签: ethereum smartcontracts web3-java


    【解决方案1】:

    请参考 Web3j 文档:

    无论方法上指定的返回类型如何,事务调用都不会返回任何值。因此,对于所有事务 方法与交易相关的交易收据是 返回 [1]
    ...

    交易收据之所以有用,有两个原因:

    它提供了交易驻留在 Solidity 中的已开采区块的详细信息,这些事件将被记录为 交易,然后可以提取。

    您正在收到交易收据。为了从您的状态变量中查询值,您应该参考Querying the state of a smart contract 部分并执行以下操作:

    Function function = new Function<>(
                 "getName", // This is the name of the solidity function in your smart contract
                 Collections.emptyList(),  // Solidity Types in smart contract functions, no input in the function so we set this to empty
                 Arrays.asList(new TypeReference<Utf8String>() {})); // result will be a string
    
    String encodedFunction = FunctionEncoder.encode(function);
    org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(
                 Transaction.createEthCallTransaction(contractAddress, encodedFunction),
                 DefaultBlockParameterName.LATEST)
                 .sendAsync().get();
    
      Iterator<Type> it = someType.iterator();
                    Type result = someType.get(0);
                    String a = result.toString();
                    Log.d("Name: ", a);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2020-08-26
      • 1970-01-01
      • 2020-01-13
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多