[Ethereum] Using Web3j to load a smart contract, how do i specify the credentials

cryptographyjavaweb3j

I am using the Web3j library to generate a Java wrapper for my solidity contract, i have already deployed the contract to the blockchain and it has been mined, i now want to load the contract in java using the java wrapper.

The java wrapper is SimpleStorage, Web3j has generated the following method signatures for loading the contract;

    public static SimpleStorage load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
    return new SimpleStorage(contractAddress, web3j, credentials, gasPrice, gasLimit);
}

public static SimpleStorage load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
    return new SimpleStorage(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}

How do i supply the Credentials object? I have the public key, private key and address of the node from which i deployed the contract on the blockchain but the Credentials object takes a ECKeyPair which expects the Private Key and Public Key to be a BigInteger however my keys are just an arbitrary string of characters.

Is there something i am missing?

To be a little more clear i have the following;

String publicKey
String privateKey
String address

and i want

Credentials creds

to pass in to the load method but Credentials only takes

    public static Credentials create(String privateKey, String publicKey) {
    return create(new ECKeyPair(Numeric.toBigInt(privateKey), Numeric.toBigInt(publicKey)));
}

Where this is failing for my public and private keys because they can't be converted to BigInt

Best Answer

To generate the Credentials if you have a plain public key and private key, you need to convert them in to the hex representation and then pass them in to the constructor for Credentials

String hexPrivateKey = String.format("%040x", new BigInteger(1, privateKey.getBytes()));
String hexPublicKey = String.format("%040x", new BigInteger(1, publicKey.getBytes()));  
Credentials creds = Credentials.create(hexPrivateKey, hexPublicKey);

Where publicKey and privateKey are Strings containing your plain pub and priv keys

Related Topic