3

I have an existing Smart contract address,abi,binary code. I need to access it from a Java application.Is it possible to do this without creating a java wrapper class?

1
  • This is possible - but can you elaborate a bit why you do not want a wrapper class?
    – ligi
    Mar 18, 2018 at 12:50

4 Answers 4

1

use ERC20 Class of java ,then load your contract after after deploying it from remix ide to any network here's an small snippet of my code:

public class TokenAPI {
@Path("/erc")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Erc20Controller getErcTokenInfo() throws Exception{
    Web3j web3 = Web3j.build(new HttpService("HTTP:YourNetwrok"));
    Credentials creds = Credentials.create("b1427aa43d62f7592feff8874d20fa42d9dbc96005d2a1c8a5cfdd55ebbfca62");
    String contractAddress = "0x82b575F93bEffea73C3C3bb776C82F8D67cb064e"; // The deployed contract address, taken

    ERC20 javaToken = ERC20.load(contractAddress, web3, creds, new DefaultGasProvider());

    Erc20Controller erc=new Erc20Controller();
    erc.setTotalSupply(javaToken.totalSupply().send());
    erc.setTokenSymbol(javaToken.symbol().send());
    erc.setTotalDecimal(javaToken.decimals().send());
    erc.setTokenName(javaToken.name().send());
    erc.setTotalBalanceOnDeployedAccount(javaToken.balanceOf("0x82b575F93bEffea73C3C3bb776C82F8D67cb064e").send());
    return erc;
}
3
  • What do you need to include to be able to see the ERC20 class? I can see the file in the repo but my IDE isn't picking it up. Is there a special Gradle import?
    – Carlos
    Sep 10, 2020 at 19:33
  • @Carlos I've used web3j contract maven dependency for this ,but you can use Gradle one from here mvnrepository.com/artifact/org.web3j/contracts/4.5.18 ,upvote this answer if it helped you
    – Aniket
    Sep 11, 2020 at 7:43
  • @Aniket still with contracts dependency Erc20Controller can't be resolved... ERC20 was part of core, is there anything more you want to enlighten us with?? Jan 4 at 3:20
0

I was exploring this recently for an android application to interact with arbitrary ERC20 token contracts. You can do it using the address and bin of the contract.

My process for doing it was to create the wrapper class for a related contract, find the functions in it that I needed (as well as the "load" functions), then copy those over to a newly created "generic" wrapper class that could work with any arbitrary contract rather than needing to be tied to just one that has a pre-generated wrapper. As long as you've written the functions you'll be using into the generic wrapper, it'll work well. This works best if you're doing something like interacting with ERC20 token contracts since those have standard functions (transfer, totalSupply, etc). Here's a snippet of my code from the wrapper that would work with any ERC20 token given the bin, address, wallet credentials, and a few other things have been retrieved:

public RemoteCall<TransactionReceipt> transfer(String to, BigInteger tokens) {
    Function function = new Function(
            "transfer", 
            Arrays.<Type>asList(new org.web3j.abi.datatypes.Address(to), 
            new org.web3j.abi.datatypes.generated.Uint256(tokens)), 
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}

//...

public static Web3jWrapper load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, String binary) {
    BINARY = binary;
        return Web3jWrapper(contractAddress, web3j, credentials, gasPrice, gasLimit);
}

The rest of the heavy lifting is done behind the scenes with web3j, you just have to change the load function so it takes the binary along with the other parameters and you can load it with:

GenericSmartContract contract = GenericSmartContract.load(
    "0x<address>|<ensName>", web3j, credentials, GAS_PRICE, GAS_LIMIT, binary);

and from there call your functions:

TransactionReceipt receipt = contract.transfer("0x1234567890123456",100000).send();
0

You can do that, see the documentation von web3j here https://docs.web3j.io/transactions.html

In the Transaction section down in the page

1- Creation of a smart contract.

2- Transacting with a smart contract.

3- Querying the state of a smart contract.

By 1 & 2 don't forget to sign the Transaction. here a simple example:

EthGetTransactionCount ethGetTransactionCount = web3j
                .ethGetTransactionCount("account-address", DefaultBlockParameterName.LATEST).send();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();

// Encode the function
final Function function = new Function(
                "method-name example transfer",
                Arrays.<Type>asList(new org.web3j.abi.datatypes.Address("first parameter example fromAddress"),
                new org.web3j.abi.datatypes.Address("example toAddress"),
                new org.web3j.abi.datatypes.generated.Int256("example value")),
                Collections.<TypeReference<?>>emptyList());
String encodedFunction = FunctionEncoder
                .encode(contractFunctionProvider.getFunction(function);

// Create new Transaction
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, GASPRICE, GASLIMIT, "contract address", BigInteger.ZERO, encodedFunction);

// Sign the Transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);

// Send the Transaction
 org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3j
                .ethSendRawTransaction(hexValue).sendAsync().get();
-3

This is somewhat the standard for interacting with a smart contract via web3.js and linking it in your frontend

<script>

    if (typeof web3 !== 'undefined') {
       web3 = new Web3(web3.currentProvider);
   } else {
       web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
   }
   var contractAddress = 'youContractAddress';

   web3.eth.defaultAccount = web3.eth.accounts[0];

   var MyContract = web3.eth.contract();

   var MySiteContract = MyContract.at(contractAddress);

</script>
1
  • web3j is java, you example is for javascript
    – Ismael
    Mar 3, 2018 at 5:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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