简体   繁体   English

Web3j 调用智能合约中的变量

[英]Web3j call a variable in a smart contract

I am trying to get the value of a variable in a Smart Contract using solidity, geth and web3j.我正在尝试使用solidity、geth和web3j获取智能合约中变量的值。

The contract HelloWorld is very simple:合约 HelloWorld 非常简单:

pragma solidity ^0.6.10;
   contract HelloWorld {
   uint256 public counter = 5;
  
   function add() public {  //increases counter by 1
       counter++;
   }
 
   function subtract() public { //decreases counter by 1
       counter--;
   }
   
   function getCounter() public view returns (uint256) {
       return counter;
   }
}

web3j does not have a call() function, just only send() which is surprising. web3j 没有 call() function,只有 send() 令人惊讶。

when I try get counter following the web3j instructions:当我尝试按照 web3j 说明获取计数器时:

contract.getCounter().send()

I get a transaction receipt rather than the value uint256.我得到一个交易收据而不是价值 uint256。

Can anybody help?有人可以帮忙吗?

Thank you谢谢

Will将要

You need to modify the getCounter() function in the generated HelloWorld.java file.需要修改生成的HelloWorld.java文件中的getCounter() function。

public RemoteCall<Type> getCounter() {
    final Function function = new Function(
            FUNC_GETCOUNTER, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint>() {}));
    return executeRemoteCallSingleValueReturn(function);
}

And to get the value, use the following code:要获取该值,请使用以下代码:

Type message = contract.getCounter().send();
System.out.println(message.getValue()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM