如何在java中使用web3j将元组编码为输出参数来运行

问题描述 投票:0回答:1
struct AccountReaderResult {
    int256 cash;
    int256 position;
    int256 availableMargin;
    int256 margin;
    int256 settleableMargin;
    bool isInitialMarginSafe;
    bool isMaintenanceMarginSafe;
    bool isMarginSafe;
    int256 targetLeverage;
}

function getAccountStorage(
    address liquidityPool,
    uint256 perpetualIndex,
    address account
) public returns (bool isSynced, AccountReaderResult memory accountStorage) {
    try ILiquidityPool(liquidityPool).forceToSyncState() {
        isSynced = true;
    } catch {
        isSynced = false;
    }
    (bool success, bytes memory data) =
        liquidityPool.call(
            abi.encodeWithSignature(
                "getMarginAccount(uint256,address)",
                perpetualIndex,
                account
            )
        );
    require(success, "fail to retrieve margin account");
    accountStorage = _parseMarginAccount(data);
}

以上是智能合约代码。

public RemoteCall<List<Type>> getAccountStorage(String liquidityPool, BigInteger perpetualIndex, String account) {
    final Function function = new Function(
            "getAccountStorage",
            Arrays.<Type>asList(new Address(liquidityPool),
                    new Uint256(perpetualIndex), new Address(account)),
            Arrays.<TypeReference<?>>asList(new TypeReference<Bool>() {}, new TypeReference<Utf8String>() {}));
    return executeRemoteCallMultipleValueReturn(function);
}

这是智能合约对应的java代码,需要使用web3j来调用。现在遇到struct类型的返回值,不知道java中如何接收。 上面的java代码返回参数错误,我该如何接收这个tuple类型参数?

java tuples web3-java
1个回答
0
投票

我希望还不算太晚...

  1. 合约中的功能。作为“视图”很重要。
function get(uint _id) public view returns (string memory content, uint id) {
    Oferta storage oferta = ofertas[_id];
    return (oferta.content, oferta.id);
}

我们的返回值有 2 个:“content”(字符串)和“id”(整数)。

  1. 您在 Java 包装器中的代码与我的类似: 这里我返回Utf8String和Uint256。
private RemoteCall<List<Type>> get(BigInteger _id) {
    final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(
            "get", 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Uint(_id)), 
            Arrays.<TypeReference<?>>asList(  
                new TypeReference<Utf8String>() {}, 
                new TypeReference<Uint256>() {}   
            ));   
    return executeRemoteCallMultipleValueReturn(function);
}   
  1. 现在是窍门。不要直接使用它。使用另一个函数转换为 POJO。
public static class Oferta {
    public String content;
    public BigInteger id;
}

public Oferta getOferta( BigInteger _id ) {
    Oferta of = new Oferta();
    try {
        List<Type> res = get(_id).send( );
        of.content = ((Utf8String)res.get(0)).getValue();
        of.id = ((Uint256)res.get(1)).getValue();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return of;
}   

注意结果数组的转换。尊重参数索引顺序。

© www.soinside.com 2019 - 2024. All rights reserved.