2017-06-23 18 views
0

這是我在我的私人網絡web3j不與合同功能一起工作?

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] 

請幫忙。

回答

0

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

我認爲Java Future API不支持你想要的。相反,我可以推薦使用CompletableFuture,它有一個join()方法,它完全符合你的要求:等待並獲得。

當我從合同生成代碼時,我遇到了同樣的問題。所以我放棄了發電機,並用CompletableFuture s替換了我生成的代碼中的所有Future。我認爲這是web3j的疏忽,儘管也許有不同的方式來處理這個我不知道的問題!

+0

web3j使用常規期貨,因爲生成的智能合約包裝需要與Android 1.6兼容。我希望在未來的版本中提供類似JSON-RPC調用的sync/async選項。 –

+0

@ConorSvensson看看Kotlin可能會很有趣 - 它支持Android,它可以定位舊的Java版本。它也有非常好看的異步支持,但我還沒有嘗試過。 – Jodiug