3

my solidity contract is following:

contract SimpleStorage {
uint storedData;

function set(uint x) {
    storedData = x;
}

function get() constant returns (uint retVal) {
    return storedData;
}}

and generate the abi is following:

[ { "constant": false, "inputs": [ { "name": "x", "type": "uint256" } ], "name": "set", "outputs": [], "type": "function" }, { "constant": true, "inputs": [], "name": "get", "outputs": [ { "name": "retVal", "type": "uint256", "value": "0" } ], "type": "function" } ]

and referenced by https://github.com/ethereum/wiki/wiki/JSON-RPC,

How to invoke get funtion and get the value by using java (not js)?

Jim Green
  • 1,088
  • 3
  • 15
  • 40

2 Answers2

3

web3j caters for this very use case. It generates Smart Contract wrappers in Java from a Solidity compiled binary and ABI file.

Once you've generated the wrapper code with web3j, you will be able to deploy, then call the methods on the above contract example as follows:

SimpleStorage simpleStorage = SimpleStorage.deploy(
    <web3j>, <credentials>, GAS_PRICE, GAS_LIMIT,
    BigInteger.ZERO);  // ether value of contract

TransactionReceipt transactionReceipt = simpleStorage.set(
        new Uint256(BigInteger.valueOf(1000))),
        .get();

Uint256 result = simpleStorage.get()
        .get();

Note: the additional get() is because web3j returns Java Futures when interacting with Ethereum clients.

See the docs for further information.

Conor Svensson
  • 1,151
  • 11
  • 17
  • #Conor i have following your answer and it is very nice to understand but i am facing some issue can you please look this and help me https://stackoverflow.com/questions/44719819/web3j-not-working-with-contract-function – Abhishek saini Jun 24 '17 at 05:28
  • #conor I want to call the smart contract methods from android app. so I deployed the smart contract using truffle framework and generate the wrapper class for the smart contract and it creates the.java file in android project so I call the set and get methods into android but it shows some error at by giving credentials details of waller path . That line is org.web3j.crypto.Credentials credentials = WalletUtils.loadCredentials(" ","/usr/local/Cellar/test3/keystore/UTC--2018-03-13T09-19-38.721370320Z--191a1be7c53236f916af5512329a5092f70fab59 "); .i got error like wallet address is not correct – vijju Jun 02 '18 at 06:56
  • please look this https://stackoverflow.com/questions/50654417/how-to-call-the-smart-contract-methods-from-android-app-using-web3j – vijju Jun 02 '18 at 07:09
0

Here is an example in Java (under Spring Boot) Good luck http://blockchainers.org/index.php/2016/09/22/static-type-safety-for-dapps-without-javascript/

ninjayoto
  • 693
  • 1
  • 7
  • 14