I'm new to Ethereum and I got stuck on trying to call balanceOf on a deployed ERC20 contract.

Here is the code I have so far:

    Web3j web3j = Web3j.build(new HttpService());

    RemoteCall<BigInteger> customerBalance;
    Function function = new Function(
            Arrays.asList(new Address(<address_of_the_account>,
            new ArrayList<>());
    String encodedFunction = FunctionEncoder.encode(function);
    org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(
            Transaction.createEthCallTransaction(<not_sure_what_the _FROM_address_is>, <not_sure_what_the_TO_address_is>, encodedFunction),

    List<Type> result = FunctionReturnDecoder.decode(
            response.getValue(), function.getOutputParameters());

In the documentation (https://docs.web3j.io/transactions.html#querying-the-state-of-a-smart-contract) has a different signature (Transaction.createEthCallTransaction(contractAddress, encodedFunction), but that doesn't compile.

I'm on the 3.1.1 version of web3j (latest). I don't know what the to and from addresses are (in the documentation there's just one address which I assume is the deployed contract's address).


The example in the documentation is wrong.

If the code is the truth, the Transaction#createEthCallTransaction function always had three parameters:

public static Transaction createEthCallTransaction(String from, String to, String data) {
        return new Transaction(from, null, null, null, to, null, data);

The documentation describes the "from" attribute of transactions like this:

The different types of transaction in web3j work with both Transaction and RawTransaction objects. The key difference is that Transaction objects must always have a from address, so that the Ethereum client which processes the eth_sendTransaction request know which wallet to use in order to sign and send the transaction on the message senders behalf. As mentioned above, this is not necessary for raw transactions which are signed offline.

So, you just need to map the address from which you are querying the contract into the "from" field and the contract address (as you already assumed) into the "to" field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.