Web3j – How to Deploy Smart Contracts Using Web3j Java Library

go-ethereumweb3j

I am using web3j java library to deploy a smart contract.

// I am encoding the constructor parameters here -- 2 & 3, 10 & 20
String encodedConstructor =
         FunctionEncoder.encodeConstructor(Arrays.asList(new Type(value), ...));

RawTransaction rawTransaction = RawTransaction.createContractTransaction(
    <nonce>,
    <gasPrice>,
    <gasLimit>,
    <value>,
    "0x <compiled smart contract code>" + encodedConstructor);

byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, <credentials>);

String hexValue = Numeric.toHexString(signedMessage);

I am using

web3.eth.sendRawTransaction(hexValue) 

to deploy the contract.

My smart contract has a constructor which accepts some parameters(a, b) and it has a function sum which returns sum of a and b. After deployment if I call the sum function, it always returns me 0.

Need help.

Reference Link: https://docs.web3j.io/transactions.html#creation-of-a-smart-contract

Best Answer

you need to create a Function Object for your smart contract constructor then in data field were you put compiled solidity add the decode result of this function 'compiled smart contract'+'decoded function of the constructor'