簡體   English   中英

web3j無法使用合同功能嗎?

[英]web3j not working with contract function?

這是我在私人網絡中的簡單合同

contract AB {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function AB () {
        balanceOf[msg.sender] = 1200;              // Give the creator all initial tokens
    }

    /* Send coins */
    function transfer(address _to, uint256 _value) {
        if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
    }

    function gettokenBalance(address to)constant returns (uint256){
          return balanceOf[to];
       }
}

我已經使用web3J生成了智能合約包裝器,並且有類似的功能

public Future<Uint256> gettokenBalance(Address to) {
        Function function = new Function("gettokenBalance", 
                Arrays.<Type>asList(to), 
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
        return executeCallSingleValueReturnAsync(function);
    }

當我嘗試訪問我的合同功能時

AB newAB = AB.load(contractaddress, web3j, credentials, gasprice, gaslimit);
        Future<Uint256> result = newAB.gettokenBalance(new Address(address));
        LOGGER.info("result:::"+result.get());

這給了我一個例外

 java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 0
    at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357) ~[na:1.8.0_91]
    at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_91]
    at com.belrium.service.UserWalletService.check(UserWalletService.java:197) ~[classes/:na]
    at com.belrium.controller.UserController.check(UserController.java:119) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]

請幫忙。

期貨是異步的,因此get()將嘗試獲取當前仍在計算中的結果值。 它僅在計算完成后才起作用。

我認為Java Future API不支持您想要的。 相反,我建議使用CompletableFuture ,它具有一個join()方法,該方法完全可以實現您想要的:等待並獲取。

從合同生成代碼時,我遇到了同樣的問題。 因此,我放棄了生成器,並用CompletableFuture替換了生成的代碼中的所有Future 我認為這是web3j的疏忽,盡管也許有另一種方式解決我不知道的問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM