Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get value from solidity contract using java

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)?

like image 912
Jim Green Avatar asked Feb 03 '26 02:02

Jim Green


1 Answers

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.

like image 84
Conor Svensson Avatar answered Feb 05 '26 14:02

Conor Svensson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!