sheemar
sheemar

Reputation: 467

Interacting a smart contract from Java application

I am working on interacting my smart contract from java application, I am using testrpc.

To interact with the smart contract we need : 1- connect to the local host 2- have an account to send transactions (credentials). 3- deploy the contract and get the address (deployed to testrpc network using truffle and already have the address)

1- Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/
2- Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");

3- YourSmartContract contract = YourSmartContract.deploy(
    <web3j>, <credentials>,
    GAS_PRICE, GAS_LIMIT,
    <initialEtherValue>,
    <param1>, ..., <paramN>).get();  // constructor params

My questions are: how I can use testrpc accounts for "credentials"??!!

How I can use the address of the smart contract which already deployed by truffle??

Upvotes: 1

Views: 720

Answers (1)

Adam Kipnis
Adam Kipnis

Reputation: 10991

how I can use testrpc accounts for "credentials"??!!

You need the private and public keys to create the Credentials object. TestRPC displays the private keys when you start. They change on each restart, so if you want to keep them static, you can specify the initial set of accounts using your own private keys with the --accounts option.

Format: testrpc --account "<PRIVATE_KEY>,<STARTING_BALANCE_IN_WEI>"

Example:

testrpc --account "0x70f1384b24df3d2cdaca7974552ec28f055812ca5e4da7a0ccd0ac0f8a4a9b00,300000000000000000000" --account "0xad0352cfc09aa0128db4e135fcea276523c400163dcc762a11ecba29d5f0a34a,300000000000000000000"

With the private key, you can generate the public key. There are several examples online of how to do this. See here for a JS example or here for an example using web3j (this creates a new key pair, but you should be able to reuse it).

With the public and private keys, you can now create the Credentials object:

import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.utils.Numeric;

...

String privateKey = <YOUR_PRIVATE_KEY>;
String publicKey = <YOUR_PUBLIC_KEY>;

ECKeyPair keyPair = new ECKeyPair(Numeric.toBigInt(privateKey), Numeric.toBigInt(publicKey));

Credentials credentials = Credentials.create(keyPair);

How I can use the address of the smart contract which already deployed by truffle??

You don't deploy a contract, you load a contract. From the web3j docs:

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

Upvotes: 2

Related Questions