[英]Web3j java function call returns empty list on solidity contract
我正在嘗試從這個 Solidity 合約中調用函數getPrice
pragma solidity ^0.4.0;
contract DataExchangeOfferContract {
uint price;
constructor(uint _price) public {
price = _price;
}
function getPrice() public constant returns (uint) {
return price;
}
}
我正在使用geth
在調試模式下運行私有區塊鏈客戶端,並且我部署了一個帶有值的合同。 這是我嘗試調用唯一部署的合約的功能的方法:
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 個元素。 我究竟做錯了什么?
編輯:
缺少的是合約地址不是交易哈希。 合約地址是這樣檢索的:
EthGetTransactionReceipt transactionReceipt = web3j.ethGetTransactionReceipt(hash).send();
String address = transactionReceipt.getTransactionReceipt().get().getContractAddress();
然后正如響應中所指出的那樣,可以使用合約包裝器調用該調用,或者使用前面描述的方法,將合約地址而不是交易哈希作為參數傳遞。
如果您的目標只是從最新的區塊中獲取價格,那么您將使它變得比需要的更復雜。 假設DataExchangeOfferContract
是您生成的存根(您的 Solidity 代碼只是說Contract
),您已經定義了getPrice
方法。 要使用它,您的代碼應如下所示:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.