2

I have developed smart contract in solidity using truffle and ganache. Now, I want to access that smart contract using some API. So how to do it ? Should I need to use web3j compulsory or is there any other way to do that ?

1 Answer 1

2

You could use web3j.

Assuming you deployed you contract to ganache using truffle, in your java code you can use TruffleJsonFunctionWrapperGenerator to generate a wrapper for your contract. Add maven dependencies:

    <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>core</artifactId>
        <version>LATEST</version>
    </dependency>
    <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>codegen</artifactId>
        <version>LATEST</version>
    </dependency>

Generate the wrapper class:

        String outputDir = PROJECT_DIR + \\src\main\java;
        String packageName = "domain.yourCompany.yourApp.somePackage";  //output package
        String[] contractGenerationArgs = new String[7];
        contractGenerationArgs[0] = "generate";
        contractGenerationArgs[1] = "--javaTypes";
        contractGenerationArgs[2] = PATH_TO_TRUFFLE_JSON_OUTPUT_FILE_OF_THE_CONTRACT;
        contractGenerationArgs[3] = "-o";
        contractGenerationArgs[4] = outputDir;
        contractGenerationArgs[5] = "-p";
        contractGenerationArgs[6] = packageName;
        TruffleJsonFunctionWrapperGenerator.run(contractGenerationArgs);

Now use it:

Web3j web3 = Web3j.build(new HttpService("http://localhost:7545/")); //running ganache over port 7545
Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
String account = web3.ethAccounts().send().getAccounts().get(0);
Credentials credentials = Credentials.create(account);
String contractAddress = "0x345ca3e014aaf5dca488057592ee47305d9b3e10"; //The deployed contract address, taken from truffle console or ganache logs
BigInteger gasPrice = new BigInteger(GAS_PRICE);
BigInteger gasLimit = new BigInteger(GAS_LIMIT);
MyContract myContract = MyContract.load(contractAddress, web3, credentials, gasPrice, gasLimit);

//Now you can call methods
myContract.someMethod().send();

If you don't want to use web3j you can also use truffle from the terminal/windows power shell:

  1. truffle develop
  2. migrate --compile-all --reset (if not deployed already)
  3. MyContract.deployed().then(function(instance){app = instance;})
  4. app.someMethod()

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.