首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Web3j java函数调用在可靠协定上返回空列表

Web3j java函数调用在可靠协定上返回空列表
EN

Stack Overflow用户
提问于 2018-08-27 02:03:06
回答 1查看 1.5K关注 0票数 2

我尝试从这个可靠的约定中调用函数getPrice

代码语言:javascript
复制
pragma solidity ^0.4.0;

contract DataExchangeOfferContract {    
    uint price;

    constructor(uint _price) public {
        price = _price;
    }

    function getPrice() public constant returns (uint) {
        return price;
    }
}

我正在使用geth在调试模式下运行一个私有区块链客户端,并且我使用一个值部署了一个契约。下面是我尝试调用所部署的唯一合约的函数的方法:

代码语言:javascript
复制
EthBlock.Block block = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, true).send().getBlock();
Transaction transaction = web3j.ethGetTransactionByBlockHashAndIndex(block.getHash(), BigInteger.ZERO).send().getTransaction().get();
String hash = transaction.getHash();

Function function = new Function(DataExchangeOfferContract.FUNC_GETPRICE, Collections.emptyList(), Collections.singletonList(new TypeReference<Uint256>() {}));
String functionEncoder = FunctionEncoder.encode(function);

Transaction transaction = Transaction.createEthCallTransaction(address, functionEncoder, null);
EthCall response = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
List<Type> types = FunctionReturnDecoder.decode(response.getValue(), function.getOutputParameters());
BigInteger price = (BigInteger) types.get(0).getValue();

这里的types有0个元素。我做错了什么?

编辑:

缺少的是合约地址不是事务散列。合同地址的检索方式如下:

代码语言:javascript
复制
EthGetTransactionReceipt transactionReceipt = web3j.ethGetTransactionReceipt(hash).send();
String address = transactionReceipt.getTransactionReceipt().get().getContractAddress();

然后,如响应中所指出的,可以使用约定包装器或使用前面描述的方法调用该调用,将约定地址而不是事务散列作为参数进行传递。

EN

回答 1

Stack Overflow用户

发布于 2018-08-27 06:40:29

如果您的目标只是从最新的区块中获取价格,那么您将使它变得比需要的更复杂。假设DataExchangeOfferContract是您生成的存根(您的实代码只显示为Contract),那么您已经定义了一个getPrice方法。要使用它,您的代码应如下所示:

代码语言:javascript
复制
Web3j web3j = Web3j.build(new HttpService());

TransactionManager manager = new ReadonlyTransactionManager(web3j, "YOUR_ADDRESS");
DataExchangeOfferContract contract = DataExchangeOfferContract.load("CONTRACT_ADDRESS", web3j, 
                                                                    manager, Contract.GAS_PRICE,
                                                                    Contract.GAS_LIMIT);
RemoteCall<BigInteger> remoteCall = contract.getPrice();
BigInteger price = remoteCall.send();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52028956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档